aboutsummaryrefslogtreecommitdiff
path: root/src/plugins/Lbry.cpp
blob: 38b62386786e7a0726baa8ee2520b5d67e22b146 (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#include "../../plugins/Lbry.hpp"
#include "../../include/Notification.hpp"
#include "../../include/StringUtils.hpp"
#include "../../include/Theme.hpp"
#include <json/value.h>
#include <json/writer.h>

// TODO: Images, music, regular files

namespace QuickMedia {
    class LbryBodyItemData : public BodyItemExtra {
    public:
        std::string streaming_url;
    };

    static void *search_type_video = (void*)0;
    static void *search_type_channel = (void*)1;

    static bool handle_error(const Json::Value &json_root, std::string &err_str) {
        const Json::Value &error_json = json_root["error"];
        if(!error_json.isObject())
            return false;

        const Json::Value &code_json = error_json["code"];
        const Json::Value &message_json = error_json["message"];
        if(message_json.isString())
            err_str += "message: " + message_json.asString();
        if(code_json.isString())
            err_str += " (code: " + code_json.asString() + ")";
        return true;
    }

    static bool extract_youtube_video_id(const std::string &url, std::string &video_id) {
        size_t start_index = url.find("ytimg.com/vi/");
        if(start_index == std::string::npos)
            return false;

        start_index += 13;
        size_t end_index = url.find('/', start_index);
        if(end_index == std::string::npos)
            end_index = url.size();

        video_id = url.substr(start_index, end_index - start_index);
        return true;
    }

    static std::shared_ptr<BodyItem> resolve_claim(const Json::Value &result_json, time_t time_now) {
        if(!result_json.isObject())
            return nullptr;

        const Json::Value &canonical_url_json = result_json["canonical_url"];
        const Json::Value &claim_id_json = result_json["claim_id"];
        const Json::Value &value_type_json = result_json["value_type"];
        if(!canonical_url_json.isString() || !claim_id_json.isString() || !value_type_json.isString())
            return nullptr;

        const Json::Value &value_json = result_json["value"];
        if(!value_json.isObject())
            return nullptr;

        std::string name;
        const Json::Value &title_json = value_json["title"];
        const Json::Value &name_json = result_json["name"];
        if(title_json.isString())
            name = title_json.asString();
        else if(name_json.isString())
            name = name_json.asString();

        auto body_item = BodyItem::create(std::move(name));

        bool is_channel = false;
        // TODO: Support other types than stream and channel
        if(strcmp(value_type_json.asCString(), "channel") == 0) {
            body_item->url = claim_id_json.asString();
            body_item->userdata = search_type_channel;
            is_channel = true;
        } else if(strcmp(value_type_json.asCString(), "stream") == 0) {
            // Skip livestreams for now as they are pretty broken on lbry.
            // Livestream requests work by doing GET https://api.live.odysee.com/v1/odysee/live/<claim_id>
            // then get stream url with .data.url. If that is missing then there is no livestream going on. What to do then?
            // TODO: Add livestreams when lbry fixes them.
            const Json::Value &stream_type_json = value_json["stream_type"];
            if(!stream_type_json.isString() || strcmp(stream_type_json.asCString(), "video") != 0)
                return nullptr;

            if(!name_json.isString())
                return nullptr;

            const Json::Value &video_source_json = value_json["source"];
            if(!video_source_json.isObject())
                return nullptr;

            const Json::Value &media_type_json = video_source_json["media_type"];
            if(!media_type_json.isString() || !strstr(media_type_json.asCString(), "video/"))
                return nullptr;

            const Json::Value &hash_json = video_source_json["hash"];
            const Json::Value &sd_hash_json = video_source_json["sd_hash"];
            if(!hash_json.isString() || !sd_hash_json.isString())
                return nullptr;

            auto extra = std::make_shared<LbryBodyItemData>();
            extra->streaming_url = canonical_url_json.asString();
            body_item->extra = std::move(extra);
            body_item->url = "https://player.odycdn.com/api/v4/streams/tc/" + name_json.asString() + "/" + hash_json.asString() + "/" + sd_hash_json.asString() + "/master.m3u8";
            body_item->userdata = search_type_video;
        }
        body_item->thumbnail_size = { 220, 130 };

        const Json::Value &thumbnail_json = value_json["thumbnail"];
        if(thumbnail_json.isObject()) {
            const Json::Value &url_json = thumbnail_json["url"];
            if(url_json.isString()) {
                std::string url = url_json.asString();
                std::string youtube_video_id;
                if(extract_youtube_video_id(url, youtube_video_id))
                    body_item->thumbnail_url = "https://thumbnails.odycdn.com/optimize/s:220:130/quality:85/plain/https://thumbnails.lbry.com/" + youtube_video_id;
                else
                    body_item->thumbnail_url = "https://thumbnails.odycdn.com/optimize/s:220:130/quality:85/plain/" + url;
            }
        }

        std::string description;

        if(is_channel) {
            // TODO: Followers

            const Json::Value &meta_json = result_json["meta"];
            if(meta_json.isObject()) {
                const Json::Value &claims_in_channel_json = meta_json["claims_in_channel"];
                if(claims_in_channel_json.isInt()) {
                    const int claims_in_channel = claims_in_channel_json.asInt();
                    description = std::to_string(claims_in_channel) + " upload" + (claims_in_channel == 0 ? "" : "s");
                }
            }

            if(name_json.isString()) {
                if(!description.empty())
                    description += '\n';
                description += name_json.asString();
            }
        } else {
            // TODO: Views

            const Json::Value &timestamp_json = result_json["timestamp"];
            if(timestamp_json.isInt64())
                description = seconds_to_relative_time_str(time_now - timestamp_json.asInt64());
        }

        const Json::Value &video_json = value_json["video"];
        if(video_json.isObject()) {
            const Json::Value duration_json = video_json["duration"];
            if(duration_json.isInt()) {
                if(!description.empty())
                    description += '\n';
                description += seconds_to_duration(duration_json.asInt());
            }
        }

        const Json::Value &signing_channel_json = result_json["signing_channel"];
        if(signing_channel_json.isObject()) {
            const Json::Value &name_json = signing_channel_json["name"];
            if(name_json.isString()) {
                if(!description.empty())
                    description += '\n';
                description += name_json.asString();
            }
        }

        if(!description.empty()) {
            body_item->set_description(std::move(description));
            body_item->set_description_color(get_theme().faded_text_color);
        }

        return body_item;
    }

    static std::shared_ptr<BodyItem> resolve_claim_parse_result(const Json::Value &result_json, time_t time_now) {
        if(!result_json.isObject())
            return nullptr;

        const Json::Value &resposted_claim_json = result_json["reposted_claim"];
        if(resposted_claim_json.isObject())
            return resolve_claim(resposted_claim_json, time_now);
        else
            return resolve_claim(result_json, time_now);
    }

    static PluginResult resolve_claims(Page *page, const Json::Value &request_json, BodyItems &result_items) {
        if(!request_json.isObject())
            return PluginResult::ERR;

        const Json::Value &method_json = request_json["method"];
        if(!method_json.isString())
            return PluginResult::ERR;

        std::string url = "https://api.na-backend.odysee.com/api/v1/proxy?m=" + method_json.asString();

        Json::StreamWriterBuilder json_builder;
        json_builder["commentStyle"] = "None";
        json_builder["indentation"] = "";

        std::vector<CommandArg> additional_args = {
            { "-X", "POST" },
            { "-H", "content-type: application/json" },
            { "--data-binary", Json::writeString(json_builder, request_json) }
        };

        Json::Value json_root;
        DownloadResult download_result = page->download_json(json_root, url, std::move(additional_args), true);
        if(download_result != DownloadResult::OK) return download_result_to_plugin_result(download_result);

        if(!json_root.isObject())
            return PluginResult::ERR;

        std::string err_str;
        if(handle_error(json_root, err_str)) {
            show_notification("QuickMedia", "Lbry search failed, error: " + err_str, Urgency::CRITICAL);
            return PluginResult::ERR;
        }

        const Json::Value &result_json = json_root["result"];
        if(!result_json.isObject())
            return PluginResult::ERR;

        const time_t time_now = time(nullptr);
        const Json::Value &items_json = result_json["items"];
        if(items_json.isArray()) {
            // Channel search
            for(const Json::Value &result_json : items_json) {
                auto body_item = resolve_claim_parse_result(result_json, time_now);
                if(body_item)
                    result_items.push_back(std::move(body_item));
            }
        } else {
            // Global search
            for(Json::Value::const_iterator it = result_json.begin(); it != result_json.end(); ++it) {
                auto body_item = resolve_claim_parse_result(*it, time_now);
                if(body_item)
                    result_items.push_back(std::move(body_item));
            }
        }

        return PluginResult::OK;
    }

    SearchResult LbrySearchPage::search(const std::string &str, BodyItems &result_items) {
        return plugin_result_to_search_result(get_page(str, 0, result_items));
    }

    PluginResult LbrySearchPage::get_page(const std::string &str, int page, BodyItems &result_items) {
        if(str.empty())
            return PluginResult::OK;

        // TODO: Support other types than stream and channel
        std::string url = "https://lighthouse.odysee.com/search?s=" + url_param_encode(str) + "&size=20&from=" + std::to_string(page * 20) + "&nsfw=false&claimType=stream,channel";
        if(!channel_id.empty())
            url += "&channel_id=" + channel_id;

        Json::Value json_root;
        DownloadResult download_result = download_json(json_root, url, {}, true);
        if(download_result != DownloadResult::OK) return download_result_to_plugin_result(download_result);

        if(!json_root.isArray())
            return PluginResult::ERR;

        Json::Value request_json(Json::objectValue);
        request_json["id"] = (int64_t)time(nullptr) * 1000;
        request_json["jsonrpc"] = "2.0";
        request_json["method"] = "resolve";
        
        Json::Value request_params_json(Json::objectValue);
        request_params_json["include_purchase_receipt"] = true;

        Json::Value urls_json(Json::arrayValue);

        for(const Json::Value &claim_json : json_root) {
            if(!claim_json.isObject())
                continue;

            const Json::Value &claim_id_json = claim_json["claimId"];
            const Json::Value &name_json = claim_json["name"];
            if(!claim_id_json.isString() || !name_json.isString())
                continue;

            urls_json.append("lbry://" + name_json.asString() + "#" + claim_id_json.asString());
        }

        request_params_json["urls"] = std::move(urls_json);
        request_json["params"] = std::move(request_params_json);
        return resolve_claims(this, request_json, result_items);
    }

    PluginResult LbrySearchPage::submit(const SubmitArgs &args, std::vector<Tab> &result_tabs) {
        if(args.userdata == search_type_video) {
            const LbryBodyItemData *body_item_data = static_cast<const LbryBodyItemData*>(args.extra.get());
            result_tabs.push_back(Tab{ nullptr, std::make_unique<LbryVideoPage>(program, args.title, args.url, body_item_data->streaming_url), nullptr });
        } else if(args.userdata == search_type_channel) {
            result_tabs.push_back(Tab{ create_body(false, true), std::make_unique<LbryChannelPage>(program, args.title, args.url), create_search_bar("Search...", 500) });
        }
        return PluginResult::OK;
    }

    SearchResult LbryChannelPage::search(const std::string &str, BodyItems &result_items) {
        return plugin_result_to_search_result(get_page(str, 0, result_items));
    }

    PluginResult LbryChannelPage::get_page(const std::string &str, int page, BodyItems &result_items) {
        if(!str.empty())
            return search_page.get_page(str, page, result_items);

        const int64_t time_now = time(nullptr);

        Json::Value channel_ids_json(Json::arrayValue);
        channel_ids_json.append(channel_id);

        Json::Value claim_type_json(Json::arrayValue);
        claim_type_json.append("stream");
        claim_type_json.append("repost");

        Json::Value not_tags_json(Json::arrayValue);
        not_tags_json.append("porn");
        not_tags_json.append("porno");
        not_tags_json.append("nsfw");
        not_tags_json.append("mature");
        not_tags_json.append("xxx");
        not_tags_json.append("sex");
        not_tags_json.append("creampie");
        not_tags_json.append("blowjob");
        not_tags_json.append("handjob");
        not_tags_json.append("vagina");
        not_tags_json.append("boobs");
        not_tags_json.append("big boobs");
        not_tags_json.append("big dick");
        not_tags_json.append("pussy");
        not_tags_json.append("cumshot");
        not_tags_json.append("anal");
        not_tags_json.append("hard fucking");
        not_tags_json.append("ass");
        not_tags_json.append("fuck");
        not_tags_json.append("hentai");

        Json::Value order_by_json(Json::arrayValue);
        order_by_json.append("release_time");
        
        Json::Value request_params_json(Json::objectValue);
        request_params_json["channel_ids"] = std::move(channel_ids_json);
        request_params_json["claim_type"] = std::move(claim_type_json);
        request_params_json["fee_amount"] = ">=0";
        request_params_json["has_source"] = true;
        request_params_json["include_purchase_receipt"] = true;
        request_params_json["no_totals"] = true;
        request_params_json["not_tags"] = std::move(not_tags_json);
        request_params_json["order_by"] = std::move(order_by_json);
        request_params_json["page"] = 1 + page;
        request_params_json["page_size"] = 20;
        request_params_json["release_time"] = "<" + std::to_string(time_now);

        Json::Value request_json(Json::objectValue);
        request_json["id"] = time_now * 1000;
        request_json["jsonrpc"] = "2.0";
        request_json["method"] = "claim_search";
        request_json["params"] = std::move(request_params_json);
        return resolve_claims(this, request_json, result_items);
    }

    PluginResult LbryChannelPage::submit(const SubmitArgs &args, std::vector<Tab> &result_tabs) {
        const LbryBodyItemData *body_item_data = static_cast<const LbryBodyItemData*>(args.extra.get());
        result_tabs.push_back(Tab{ nullptr, std::make_unique<LbryVideoPage>(program, args.title, args.url, body_item_data->streaming_url), nullptr });
        return PluginResult::OK;
    }

    PluginResult LbryChannelPage::lazy_fetch(BodyItems &result_items) {
        return get_page("", 0, result_items);
    }

    static PluginResult video_get_stream_url(Page *page, const std::string &streaming_url, const std::string &video_url, std::vector<M3U8Stream> &streams, std::string &direct_video_url, std::string &err_str) {
        std::string website_data;
        DownloadResult result = download_to_string(video_url.c_str(), website_data, {}, true);
        if(result == DownloadResult::OK) {
            streams = m3u8_get_streams(website_data);
            return PluginResult::OK;
        }

        std::string url = "https://api.na-backend.odysee.com/api/v1/proxy?m=get";

        Json::Value request_params_json(Json::objectValue);
        request_params_json["save_file"] = false;
        request_params_json["uri"] = streaming_url;

        Json::Value request_json(Json::objectValue);
        request_json["id"] = (int64_t)time(nullptr) * 1000;
        request_json["jsonrpc"] = "2.0";
        request_json["method"] = "get";
        request_json["params"] = std::move(request_params_json);

        Json::StreamWriterBuilder json_builder;
        json_builder["commentStyle"] = "None";
        json_builder["indentation"] = "";

        std::vector<CommandArg> additional_args = {
            { "-X", "POST" },
            { "-H", "content-type: application/json" },
            { "--data-binary", Json::writeString(json_builder, request_json) }
        };

        Json::Value json_root;
        DownloadResult download_result = page->download_json(json_root, url, std::move(additional_args), true);
        if(download_result != DownloadResult::OK) return download_result_to_plugin_result(download_result);

        if(!json_root.isObject())
            return PluginResult::ERR;

        err_str.clear();
        if(handle_error(json_root, err_str))
            return PluginResult::ERR;

        const Json::Value &result_json = json_root["result"];
        if(!result_json.isObject())
            return PluginResult::ERR;

        const Json::Value &streaming_url_json = result_json["streaming_url"];
        if(!streaming_url_json.isString())
            return PluginResult::ERR;

        direct_video_url = streaming_url_json.asString();
        return PluginResult::OK;
    }

    // TODO: Support |max_height|. This can be done by gettin video source hash and checking for sd_hash and then resolution.
    // If max_height is below max resolution height then choose the sd_hash version (replace hash in video stream with sd hash for the lower quality version)
    std::string LbryVideoPage::get_download_url(int max_height) {
        bool has_embedded_audio;
        std::string ext;
        return get_video_url(max_height, has_embedded_audio, ext);
    }

    std::string LbryVideoPage::get_video_url(int max_height, bool &has_embedded_audio, std::string &ext) {
        has_embedded_audio = true;
        ext = ".mp4"; // TODO: Check if this is always correct

        if(!direct_video_url.empty())
            return direct_video_url;

        if(streams.empty())
            return url;

        std::sort(streams.begin(), streams.end(), [](const M3U8Stream &a, const M3U8Stream &b) {
            return a.height > b.height;
        });

        size_t selected_stream = 0;
        for(size_t i = 0; i < streams.size(); ++i) {
            if(streams[i].height <= max_height) {
                selected_stream = i;
                break;
            }
        }

        std::string video_url = url;
        size_t end_section = video_url.rfind('/');
        if(end_section != std::string::npos && end_section > 0 && end_section != video_url.size() - 1) {
            end_section += 1;
            video_url.replace(end_section, video_url.size() - end_section, streams[selected_stream].url);
        }

        return video_url;
    }

    std::string LbryVideoPage::get_audio_url(std::string&) {
        return "";
    }

    PluginResult LbryVideoPage::load(const SubmitArgs &args, VideoInfo &video_info, std::string &err_str) {
        streams.clear();
        direct_video_url.clear();
        video_info.title = args.title;
        //title = this->title;
        video_info.duration = 0.0;
        video_info.referer = "https://odysee.com/";
        return video_get_stream_url(this, streaming_url, url, streams, direct_video_url, err_str);
    }
}