]> git.sur5r.net Git - minitube/blob - src/video.cpp
Imported Upstream version 1.2
[minitube] / src / video.cpp
1 #include "video.h"
2 #include "networkaccess.h"
3 #include <QtNetwork>
4 #include "videodefinition.h"
5
6 namespace The {
7     NetworkAccess* http();
8 }
9
10 Video::Video() : m_duration(0),
11 m_viewCount(-1),
12 definitionCode(0),
13 elIndex(0),
14 loadingStreamUrl(false)
15 { }
16
17 Video* Video::clone() {
18     Video* cloneVideo = new Video();
19     cloneVideo->m_title = m_title;
20     cloneVideo->m_description = m_description;
21     cloneVideo->m_author = m_author;
22     cloneVideo->m_webpage = m_webpage;
23     cloneVideo->m_streamUrl = m_streamUrl;
24     cloneVideo->m_thumbnail = m_thumbnail;
25     cloneVideo->m_thumbnailUrls = m_thumbnailUrls;
26     cloneVideo->m_duration = m_duration;
27     cloneVideo->m_published = m_published;
28     cloneVideo->m_viewCount = m_viewCount;
29     cloneVideo->videoId = videoId;
30     cloneVideo->videoToken = videoToken;
31     cloneVideo->definitionCode = definitionCode;
32     return cloneVideo;
33 }
34
35 void Video::preloadThumbnail() {
36     if (m_thumbnailUrls.isEmpty()) return;
37     QObject *reply = The::http()->get(m_thumbnailUrls.first());
38     connect(reply, SIGNAL(data(QByteArray)), SLOT(setThumbnail(QByteArray)));
39 }
40
41 void Video::setThumbnail(QByteArray bytes) {
42     m_thumbnail = QImage::fromData(bytes);
43     emit gotThumbnail();
44 }
45
46 const QImage Video::thumbnail() const {
47     return m_thumbnail;
48 }
49
50 void Video::loadStreamUrl() {
51     if (loadingStreamUrl) {
52         qDebug() << "Already loading stream URL for" << this->title();
53         return;
54     }
55     loadingStreamUrl = true;
56
57     // https://develop.participatoryculture.org/trac/democracy/browser/trunk/tv/portable/flashscraper.py
58
59     // Get Video ID
60     // youtube-dl line 428
61     // QRegExp re("^((?:http://)?(?:\\w+\\.)?youtube\\.com/(?:(?:v/)|(?:(?:watch(?:\\.php)?)?\\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$");
62     QRegExp re("^http://www\\.youtube\\.com/watch\\?v=([0-9A-Za-z_-]+).*");
63     bool match = re.exactMatch(m_webpage.toString());
64     if (!match || re.numCaptures() < 1) {
65         emit errorStreamUrl(QString("Cannot get video id for %1").arg(m_webpage.toString()));
66         loadingStreamUrl = false;
67         return;
68     }
69     videoId = re.cap(1);
70
71     getVideoInfo();
72
73 }
74
75 void  Video::getVideoInfo() {
76     static const QStringList elTypes = QStringList() << "&el=embedded" << "&el=vevo" << "&el=detailpage" << "";
77
78     if (elIndex > elTypes.size() - 1) {
79         // Don't panic! We have a plan B.
80         // get the youtube video webpage
81         qDebug() << "Scraping" << webpage().toString();
82         QObject *reply = The::http()->get(webpage().toString());
83         connect(reply, SIGNAL(data(QByteArray)), SLOT(scrapeWebPage(QByteArray)));
84         connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
85         // see you in scrapWebPage(QByteArray)
86         return;
87     }
88
89     // Get Video Token
90     QUrl videoInfoUrl = QUrl(QString(
91             "http://www.youtube.com/get_video_info?video_id=%1%2&ps=default&eurl=&gl=US&hl=en"
92             ).arg(videoId, elTypes.at(elIndex)));
93
94     QObject *reply = The::http()->get(videoInfoUrl);
95     connect(reply, SIGNAL(data(QByteArray)), SLOT(gotVideoInfo(QByteArray)));
96     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
97
98     // see you in gotVideoInfo...
99
100 }
101
102 void  Video::gotVideoInfo(QByteArray data) {
103     QString videoInfo = QString::fromUtf8(data);
104
105     // get video token
106     QRegExp re = QRegExp("^.*&token=([^&]+).*$");
107     bool match = re.exactMatch(videoInfo);
108     // handle regexp failure
109     if (!match || re.numCaptures() < 1) {
110         // Don't panic! We're gonna try another magic "el" param
111         elIndex++;
112         getVideoInfo();
113         return;
114     }
115     QString videoToken = re.cap(1);
116     while (videoToken.contains('%'))
117         videoToken = QByteArray::fromPercentEncoding(videoToken.toAscii());
118     // qDebug() << "videoToken" << videoToken;
119     this->videoToken = videoToken;
120
121     /*
122     // get fmt_url_map
123     re = QRegExp("^.*&fmt_url_map=([^&]+).*$");
124     match = re.exactMatch(videoInfo);
125     // handle regexp failure
126     if (!match || re.numCaptures() < 1) {
127         // Don't panic! We're gonna try another magic "el" param
128         elIndex++;
129         getVideoInfo();
130         return;
131     }
132     QString fmtUrlMap = re.cap(1);
133
134     while (fmtUrlMap.contains('%'))
135         fmtUrlMap = QByteArray::fromPercentEncoding(fmtUrlMap.toAscii());
136
137     qDebug() << "fmtUrlMap" << fmtUrlMap;
138     QStringList formatUrls = fmtUrlMap.split(",", QString::SkipEmptyParts);
139     foreach(QString formatUrl, formatUrls) {
140         int separator = formatUrl.indexOf("|");
141         if (separator == -1) continue;
142         int format = formatUrl.left(separator).toInt();
143         QString url = formatUrl.mid(separator + 1);
144         qDebug() << format << url;
145     }
146     */
147
148     QSettings settings;
149     QString definitionName = settings.value("definition").toString();
150     int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
151     if (definitionCode == 18) {
152         // This is assumed always available
153         foundVideoUrl(videoToken, 18);
154     } else {
155         findVideoUrl(definitionCode);
156     }
157
158 }
159
160 void Video::foundVideoUrl(QString videoToken, int definitionCode) {
161     // qDebug() << "foundVideoUrl" << videoToken << definitionCode;
162
163     QUrl videoUrl = QUrl(QString(
164             "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
165             ).arg(videoId, videoToken, QString::number(definitionCode)));
166
167     m_streamUrl = videoUrl;
168     emit gotStreamUrl(videoUrl);
169     loadingStreamUrl = false;
170 }
171
172 void Video::errorVideoInfo(QNetworkReply *reply) {
173     emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
174     loadingStreamUrl = false;
175 }
176
177 void Video::scrapeWebPage(QByteArray data) {
178
179     QString videoHTML = QString::fromUtf8(data);
180     QRegExp re(".*, \"t\": \"([^\"]+)\".*");
181     bool match = re.exactMatch(videoHTML);
182
183     // on regexp failure, stop and report error
184     if (!match || re.numCaptures() < 1) {
185         emit errorStreamUrl("Error parsing video page");
186         loadingStreamUrl = false;
187         return;
188     }
189
190     QString videoToken = re.cap(1);
191     // FIXME proper decode
192     videoToken = videoToken.replace("%3D", "=");
193
194     // we'll need this in gotHeadHeaders()
195     this->videoToken = videoToken;
196
197     // qDebug() << "token" << videoToken;
198
199     QSettings settings;
200     QString definitionName = settings.value("definition").toString();
201     int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
202     if (definitionCode == 18) {
203         // This is assumed always available
204         foundVideoUrl(videoToken, 18);
205     } else {
206         findVideoUrl(definitionCode);
207     }
208
209 }
210
211 void Video::gotHeadHeaders(QNetworkReply* reply) {
212     int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
213     // qDebug() << "gotHeaders" << statusCode;
214     if (statusCode == 200) {
215         foundVideoUrl(videoToken, definitionCode);
216     } else {
217
218         // try next (lower quality) definition
219         /*
220         QStringList definitionNames = VideoDefinition::getDefinitionNames();
221         int currentIndex = definitionNames.indexOf(currentDefinition);
222         int previousIndex = 0;
223         if (currentIndex > 0) {
224             previousIndex = currentIndex - 1;
225         }
226         if (previousIndex > 0) {
227             QString nextDefinitionName = definitionNames.at(previousIndex);
228             findVideoUrl(nextDefinitionName);
229         } else {
230             foundVideoUrl(videoToken, 18);
231         }*/
232
233
234         QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
235         int currentIndex = definitionCodes.indexOf(definitionCode);
236         int previousIndex = 0;
237         if (currentIndex > 0) {
238             previousIndex = currentIndex - 1;
239             int definitionCode = definitionCodes.at(previousIndex);
240             if (definitionCode == 18) {
241                 // This is assumed always available
242                 foundVideoUrl(videoToken, 18);
243             } else {
244                 findVideoUrl(definitionCode);
245             }
246
247         } else {
248             foundVideoUrl(videoToken, 18);
249         }
250
251     }
252 }
253
254 void Video::findVideoUrl(int definitionCode) {
255     this->definitionCode = definitionCode;
256
257     QUrl videoUrl = QUrl(QString(
258             "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
259             ).arg(videoId, videoToken, QString::number(definitionCode)));
260
261     QObject *reply = The::http()->head(videoUrl);
262     connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(gotHeadHeaders(QNetworkReply*)));
263     // connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
264
265     // see you in gotHeadHeaders()
266
267 }