]> git.sur5r.net Git - minitube/blob - src/yt/invidious/ivsinglevideosource.cpp
New upstream version 3.8
[minitube] / src / yt / invidious / ivsinglevideosource.cpp
1 #include "ivsinglevideosource.h"
2
3 #include "http.h"
4 #include "httputils.h"
5 #include "video.h"
6
7 #include "invidious.h"
8 #include "ivlistparser.h"
9
10 IVSingleVideoSource::IVSingleVideoSource(QObject *parent)
11     : IVVideoSource(parent), video(nullptr), startIndex(0), max(0) {}
12
13 void IVSingleVideoSource::reallyLoadVideos(int max, int startIndex) {
14     aborted = false;
15     this->startIndex = startIndex;
16     this->max = max;
17
18     QUrl url;
19
20     if (startIndex == 1) {
21         if (video) {
22             QVector<Video *> videos;
23             videos << video->clone();
24             if (name.isEmpty()) {
25                 name = videos.at(0)->getTitle();
26                 qDebug() << "Emitting name changed" << name;
27                 emit nameChanged(name);
28             }
29             emit gotVideos(videos);
30             loadVideos(max - 1, 2);
31             return;
32         }
33
34         url = Invidious::instance().method("videos/");
35         if (url.isEmpty()) {
36             QTimer::singleShot(500, this, [this] { handleError("No baseUrl"); });
37             return;
38         }
39         url.setPath(url.path() + videoId);
40
41     } else {
42         url = Invidious::instance().method("videos");
43         if (url.isEmpty()) {
44             QTimer::singleShot(500, this, [this] { handleError("No baseUrl"); });
45             return;
46         }
47         url.setPath(url.path() + "/" + videoId);
48     }
49
50     auto reply = Invidious::cachedHttp().get(url);
51     connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResults(QByteArray)));
52     connect(reply, &HttpReply::error, this, &IVSingleVideoSource::handleError);
53 }
54
55 void IVSingleVideoSource::parseResults(QByteArray data) {
56     if (aborted) return;
57
58     QJsonDocument doc = QJsonDocument::fromJson(data);
59     const QJsonArray items = doc.object()["recommendedVideos"].toArray();
60
61     IVListParser parser(items);
62     auto videos = parser.getVideos();
63
64     emit gotVideos(videos);
65     if (startIndex == 1)
66         loadVideos(max - 1, 2);
67     else if (startIndex == 2)
68         emit finished(videos.size() + 1);
69     else
70         emit finished(videos.size());
71
72     // fake more videos by loading videos related to the last one
73     video = nullptr;
74     if (!videos.isEmpty()) videoId = videos.last()->getId();
75 }
76
77 QString IVSingleVideoSource::getName() {
78     return name;
79 }
80
81 void IVSingleVideoSource::setVideo(Video *video) {
82     this->video = video;
83     videoId = video->getId();
84 }