aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/LocalAnime.cpp
blob: 53b26f54ecb95e1de359e96cc11b95a0bb1bb1f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#include "../../plugins/LocalAnime.hpp"
#include "../../include/Config.hpp"
#include "../../include/Theme.hpp"
#include "../../include/Storage.hpp"
#include "../../include/Notification.hpp"
#include "../../include/FileAnalyzer.hpp"
#include "../../include/ResourceLoader.hpp"
#include "../../include/StringUtils.hpp"
#include <mglpp/graphics/Rectangle.hpp>
#include <mglpp/window/Window.hpp>
#include <json/value.h>
#include <math.h>

namespace QuickMedia {
    static const mgl::Color finished_watching_color = mgl::Color(43, 255, 47);

    static float floor(float v) {
        return (int)v;
    }

    class LocalAnimeBodyItemData : public BodyItemExtra {
    public:
        void draw_overlay(mgl::Window &render_target, const Widgets &widgets) override {
            if(!std::holds_alternative<LocalAnimeEpisode>(anime_item) || !widgets.thumbnail)
                return;

            const int rect_height = 5;
            const double watch_ratio = watch_progress.get_watch_ratio();

            mgl::Rectangle watch_rect;
            watch_rect.set_position({ widgets.thumbnail->position.x, widgets.thumbnail->position.y + widgets.thumbnail->size.y - rect_height });
            watch_rect.set_size({ floor(widgets.thumbnail->size.x * watch_ratio), rect_height });
            watch_rect.set_color(mgl::Color(150, 0, 0, 255));
            render_target.draw(watch_rect);

            mgl::Rectangle unwatch_rect;
            unwatch_rect.set_position({ floor(widgets.thumbnail->position.x + widgets.thumbnail->size.x * watch_ratio), widgets.thumbnail->position.y + widgets.thumbnail->size.y - rect_height });
            unwatch_rect.set_size({ floor(widgets.thumbnail->size.x * (1.0 - watch_ratio)), rect_height });
            unwatch_rect.set_color(mgl::Color(150, 150, 150, 255));
            render_target.draw(unwatch_rect);
        }

        LocalAnimeItem anime_item;
        WatchProgress watch_progress;
    };

    static std::vector<LocalAnimeItem> get_episodes_in_directory(const Path &directory) {
        std::vector<LocalAnimeItem> episodes;
        for_files_in_dir_sort_name(directory, [&episodes](const Path &filepath, FileType file_type) -> bool {
            if(file_type != FileType::REGULAR || !is_video_ext(filepath.ext()))
                return true;

            time_t modified_time_seconds;
            if(!file_get_last_modified_time_seconds(filepath.data.c_str(), &modified_time_seconds))
                return true;

            episodes.push_back(LocalAnimeEpisode{ filepath, modified_time_seconds });
            return true;
        }, FileSortDirection::DESC);
        return episodes;
    }

    static std::vector<LocalAnimeItem> get_episodes_or_seasons_in_directory(const Path &directory) {
        std::vector<LocalAnimeItem> anime_items;
        for_files_in_dir_sort_name(directory, [&](const Path &filepath, FileType file_type) -> bool {
            time_t modified_time_seconds;
            if(!file_get_last_modified_time_seconds(filepath.data.c_str(), &modified_time_seconds))
                return true;

            if(file_type == FileType::REGULAR) {
                if(is_video_ext(filepath.ext()))
                    anime_items.push_back(LocalAnimeEpisode{ filepath, modified_time_seconds });
                return true;
            }

            LocalAnimeSeason season;
            season.path = filepath;
            season.episodes = get_episodes_in_directory(filepath);
            season.modified_time_seconds = modified_time_seconds;
            if(season.episodes.empty())
                return true;

            anime_items.push_back(std::move(season));
            return true;
        }, FileSortDirection::DESC);
        return anime_items;
    }

    static std::vector<LocalAnimeItem> get_anime_in_directory(const Path &directory) {
        std::vector<LocalAnimeItem> anime_items;
        auto callback = [&anime_items](const Path &filepath, FileType file_type) -> bool {
            time_t modified_time_seconds;
            if(!file_get_last_modified_time_seconds(filepath.data.c_str(), &modified_time_seconds))
                return true;

            if(file_type == FileType::REGULAR) {
                if(is_video_ext(filepath.ext()))
                    anime_items.push_back(LocalAnimeEpisode{ filepath, modified_time_seconds });
                return true;
            }
            
            LocalAnime anime;
            anime.path = filepath;
            anime.items = get_episodes_or_seasons_in_directory(filepath);
            anime.modified_time_seconds = modified_time_seconds;
            if(anime.items.empty())
                return true;

            anime_items.push_back(std::move(anime));
            return true;
        };

        if(get_config().local_anime.sort_by_name)
            for_files_in_dir_sort_name(directory, std::move(callback), FileSortDirection::ASC);
        else
            for_files_in_dir_sort_last_modified(directory, std::move(callback));

        return anime_items;
    }

    static const LocalAnimeEpisode* get_latest_anime_item(const LocalAnimeItem &item) {
        if(std::holds_alternative<LocalAnime>(item)) {
            const LocalAnime &anime = std::get<LocalAnime>(item);
            return get_latest_anime_item(anime.items.front());
        } else if(std::holds_alternative<LocalAnimeSeason>(item)) {
            const LocalAnimeSeason &season = std::get<LocalAnimeSeason>(item);
            return get_latest_anime_item(season.episodes.front());
        } else if(std::holds_alternative<LocalAnimeEpisode>(item)) {
            const LocalAnimeEpisode &episode = std::get<LocalAnimeEpisode>(item);
            return &episode;
        } else {
            return nullptr;
        }
    }

    PluginResult LocalAnimeSearchPage::submit(const SubmitArgs &args, std::vector<Tab> &result_tabs) {
        LocalAnimeBodyItemData *item_data = static_cast<LocalAnimeBodyItemData*>(args.extra.get());
        if(std::holds_alternative<LocalAnime>(item_data->anime_item)) {
            const LocalAnime &anime = std::get<LocalAnime>(item_data->anime_item);
            result_tabs.push_back(Tab{ create_body(), std::make_unique<LocalAnimeSearchPage>(program, anime.path.data, LocalAnimeSearchPageType::ANIME), create_search_bar("Search...", SEARCH_DELAY_FILTER) });
            return PluginResult::OK;
        } else if(std::holds_alternative<LocalAnimeSeason>(item_data->anime_item)) {
            const LocalAnimeSeason &season = std::get<LocalAnimeSeason>(item_data->anime_item);
            result_tabs.push_back(Tab{ create_body(), std::make_unique<LocalAnimeSearchPage>(program, season.path.data, LocalAnimeSearchPageType::SEASON), create_search_bar("Search...", SEARCH_DELAY_FILTER) });
            return PluginResult::OK;
        } else if(std::holds_alternative<LocalAnimeEpisode>(item_data->anime_item)) {
            const LocalAnimeEpisode &episode = std::get<LocalAnimeEpisode>(item_data->anime_item);
            result_tabs.push_back(Tab{ nullptr, std::make_unique<LocalAnimeVideoPage>(program, episode.path.data, item_data->watch_progress), nullptr });
            return PluginResult::OK;
        }
        return PluginResult::ERR;
    }

    PluginResult LocalAnimeSearchPage::lazy_fetch(BodyItems &result_items) {
        std::unordered_map<std::string, WatchProgress> watch_progress = get_watch_progress_for_plugin("local-anime");

        std::vector<LocalAnimeItem> anime_items;
        switch(type) {
            case LocalAnimeSearchPageType::DIRECTORY:
                anime_items = get_anime_in_directory(directory);
                break;
            case LocalAnimeSearchPageType::ANIME:
                anime_items = get_episodes_or_seasons_in_directory(directory);
                break;
            case LocalAnimeSearchPageType::SEASON:
                anime_items = get_episodes_in_directory(directory);
                break;
        }

        fprintf(stderr, "num watched animu: %zu\n", watch_progress.size());
        for(auto &it : watch_progress) {
            fprintf(stderr, "watch progress: %s, time: %d, duration: %d\n", it.first.c_str(), (int)it.second.time_pos_sec, (int)it.second.duration_sec);
        }

        const time_t time_now = time(nullptr);
        for(LocalAnimeItem &anime_item : anime_items) {
            std::string filename_relative_to_anime_dir = get_latest_anime_item(anime_item)->path.data.substr(get_config().local_anime.directory.size() + 1);

            auto body_item_data = std::make_shared<LocalAnimeBodyItemData>();
            body_item_data->watch_progress = watch_progress[filename_relative_to_anime_dir];
            const bool has_finished_watching = body_item_data->watch_progress.has_finished_watching();

            fprintf(stderr, "watch progress %s: time: %d, duration: %d\n", filename_relative_to_anime_dir.c_str(), (int)body_item_data->watch_progress.time_pos_sec, (int)body_item_data->watch_progress.duration_sec);

            if(std::holds_alternative<LocalAnime>(anime_item)) {
                const LocalAnime &anime = std::get<LocalAnime>(anime_item);

                std::string title;
                if(has_finished_watching)
                    title = "[Finished watching] ";
                title += anime.path.filename();

                auto body_item = BodyItem::create(std::move(title));
                if(has_finished_watching)
                    body_item->set_title_color(finished_watching_color);

                body_item->set_description("Updated " + seconds_to_relative_time_str(time_now - anime.modified_time_seconds));
                body_item->set_description_color(get_theme().faded_text_color);

                body_item->url = anime.path.data;

                body_item_data->anime_item = std::move(anime_item);
                body_item->extra = std::move(body_item_data);
                result_items.push_back(std::move(body_item));
            } else if(std::holds_alternative<LocalAnimeSeason>(anime_item)) {
                const LocalAnimeSeason &season = std::get<LocalAnimeSeason>(anime_item);

                std::string title;
                if(has_finished_watching)
                    title = "[Finished watching] ";
                title += season.path.filename();

                auto body_item = BodyItem::create(std::move(title));
                if(has_finished_watching)
                    body_item->set_title_color(finished_watching_color);

                body_item->set_description("Updated " + seconds_to_relative_time_str(time_now - season.modified_time_seconds));
                body_item->set_description_color(get_theme().faded_text_color);

                body_item->url = season.path.data;

                body_item_data->anime_item = std::move(anime_item);
                body_item->extra = std::move(body_item_data);
                result_items.push_back(std::move(body_item));
            } else if(std::holds_alternative<LocalAnimeEpisode>(anime_item)) {
                const LocalAnimeEpisode &episode = std::get<LocalAnimeEpisode>(anime_item);

                std::string title;
                if(has_finished_watching)
                    title = "[Finished watching] ";
                title += episode.path.filename();

                auto body_item = BodyItem::create(std::move(title));
                if(has_finished_watching)
                    body_item->set_title_color(finished_watching_color);

                body_item->set_description("Updated " + seconds_to_relative_time_str(time_now - episode.modified_time_seconds));
                body_item->set_description_color(get_theme().faded_text_color);

                body_item->url = episode.path.data;
                body_item->thumbnail_is_local = true;
                body_item->thumbnail_url = episode.path.data;

                body_item_data->anime_item = std::move(anime_item);
                body_item->extra = std::move(body_item_data);
                result_items.push_back(std::move(body_item));
            }
        }

        return PluginResult::OK;
    }

    void LocalAnimeSearchPage::toggle_read(BodyItem *selected_item) {
        if(!selected_item)
            return;

        LocalAnimeBodyItemData *item_data = static_cast<LocalAnimeBodyItemData*>(selected_item->extra.get());

        Path latest_anime_path = get_latest_anime_item(item_data->anime_item)->path;
        std::string filename_relative_to_anime_dir = latest_anime_path.data.substr(get_config().local_anime.directory.size() + 1);

        FileAnalyzer file_analyzer;
        if(!file_analyzer.load_file(latest_anime_path.data.c_str(), true)) {
            show_notification("QuickMedia", "Failed to load " + filename_relative_to_anime_dir + " to set watch progress", Urgency::CRITICAL);
            return;
        }

        if(!file_analyzer.get_duration_seconds()) {
            show_notification("QuickMedia", "Failed to get duration of " + filename_relative_to_anime_dir + " to set watch progress", Urgency::CRITICAL);
            return;
        }

        WatchedStatus watch_status;
        if(!toggle_watched_for_plugin_save_to_file("local-anime", filename_relative_to_anime_dir, *file_analyzer.get_duration_seconds(), latest_anime_path.data, watch_status))
            return;

        mgl::Color color = get_theme().text_color;
        std::string title;
        if(watch_status == WatchedStatus::WATCHED) {
            title = "[Finished watching] ";
            color = finished_watching_color;

            item_data->watch_progress.time_pos_sec = *file_analyzer.get_duration_seconds();
            item_data->watch_progress.duration_sec = *file_analyzer.get_duration_seconds();
        } else {
            item_data->watch_progress.time_pos_sec = 0;
            item_data->watch_progress.duration_sec = *file_analyzer.get_duration_seconds();
        }
        title += Path(selected_item->url).filename();

        selected_item->set_title(std::move(title));
        selected_item->set_title_color(color);
    }

    std::string LocalAnimeVideoPage::get_video_url(int, bool &has_embedded_audio, std::string &ext) {
        ext = Path(url).ext();
        has_embedded_audio = true;
        return url;
    }

    std::string LocalAnimeVideoPage::get_url_timestamp() {
        // If we are very close to the end then start from the beginning.
        // This is the same behavior as mpv.
        // This is better because we dont want the video player to stop immediately after we start playing and we dont get any chance to seek.
        if(watch_progress.time_pos_sec + 10.0 >= watch_progress.duration_sec)
            return "0";
        else
            return std::to_string(watch_progress.time_pos_sec);
    }

    void LocalAnimeVideoPage::set_watch_progress(int64_t time_pos_sec) {
        std::string filename_relative_to_anime_dir = url.substr(get_config().local_anime.directory.size() + 1);

        FileAnalyzer file_analyzer;
        if(!file_analyzer.load_file(url.c_str(), true)) {
            show_notification("QuickMedia", "Failed to load " + filename_relative_to_anime_dir + " to set watch progress", Urgency::CRITICAL);
            return;
        }

        if(!file_analyzer.get_duration_seconds()) {
            show_notification("QuickMedia", "Failed to get duration of " + filename_relative_to_anime_dir + " to set watch progress", Urgency::CRITICAL);
            return;
        }

        watch_progress.duration_sec = *file_analyzer.get_duration_seconds();
        set_watch_progress_for_plugin("local-anime", filename_relative_to_anime_dir, time_pos_sec, *file_analyzer.get_duration_seconds(), url);
    }
}