]> git.sur5r.net Git - minitube/blob - src/video.cpp
Imported Upstream version 2.2
[minitube] / src / video.cpp
1 /* $BEGIN_LICENSE
2
3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
5
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Minitube.  If not, see <http://www.gnu.org/licenses/>.
18
19 $END_LICENSE */
20
21 #include "video.h"
22 #include "networkaccess.h"
23 #include <QtNetwork>
24 #include "videodefinition.h"
25 #include "jsfunctions.h"
26
27 namespace The {
28 NetworkAccess* http();
29 }
30
31 namespace {
32     static const QString jsNameChars = "a-zA-Z0-9\\$_";
33 }
34
35 Video::Video() : m_duration(0),
36     m_viewCount(-1),
37     definitionCode(0),
38     elIndex(0),
39     ageGate(false),
40     m_license(LicenseYouTube),
41     loadingStreamUrl(false),
42     loadingThumbnail(false)
43 { }
44
45 Video* Video::clone() {
46     Video* cloneVideo = new Video();
47     cloneVideo->m_title = m_title;
48     cloneVideo->m_description = m_description;
49     cloneVideo->m_author = m_author;
50     cloneVideo->m_userId = m_userId;
51     cloneVideo->m_webpage = m_webpage;
52     cloneVideo->m_streamUrl = m_streamUrl;
53     cloneVideo->m_thumbnail = m_thumbnail;
54     cloneVideo->m_thumbnailUrl = m_thumbnailUrl;
55     cloneVideo->m_mediumThumbnailUrl = m_mediumThumbnailUrl;
56     cloneVideo->m_duration = m_duration;
57     cloneVideo->m_published = m_published;
58     cloneVideo->m_viewCount = m_viewCount;
59     cloneVideo->videoId = videoId;
60     cloneVideo->videoToken = videoToken;
61     cloneVideo->definitionCode = definitionCode;
62     return cloneVideo;
63 }
64
65 void Video::setWebpage(QUrl webpage) {
66     m_webpage = webpage;
67
68     // Get Video ID
69     // youtube-dl line 428
70     // QRegExp re("^((?:http://)?(?:\\w+\\.)?youtube\\.com/(?:(?:v/)|(?:(?:watch(?:\\.php)?)?\\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$");
71     QRegExp re("^https?://www\\.youtube\\.com/watch\\?v=([0-9A-Za-z_-]+).*");
72     bool match = re.exactMatch(m_webpage.toString());
73     if (!match || re.numCaptures() < 1) {
74         qWarning() << QString("Cannot get video id for %1").arg(m_webpage.toString());
75         // emit errorStreamUrl(QString("Cannot get video id for %1").arg(m_webpage.toString()));
76         // loadingStreamUrl = false;
77         return;
78     }
79     videoId = re.cap(1);
80 }
81
82 void Video::loadThumbnail() {
83     if (m_thumbnailUrl.isEmpty() || loadingThumbnail) return;
84     loadingThumbnail = true;
85     QObject *reply = The::http()->get(m_thumbnailUrl);
86     connect(reply, SIGNAL(data(QByteArray)), SLOT(setThumbnail(QByteArray)));
87 }
88
89 void Video::setThumbnail(QByteArray bytes) {
90     loadingThumbnail = false;
91     m_thumbnail.loadFromData(bytes);
92     if (m_thumbnail.width() > 160)
93         m_thumbnail = m_thumbnail.scaledToWidth(160, Qt::SmoothTransformation);
94     emit gotThumbnail();
95 }
96
97 void Video::loadMediumThumbnail() {
98     if (m_mediumThumbnailUrl.isEmpty()) return;
99     QObject *reply = The::http()->get(m_mediumThumbnailUrl);
100     connect(reply, SIGNAL(data(QByteArray)), SIGNAL(gotMediumThumbnail(QByteArray)));
101 }
102
103 void Video::loadStreamUrl() {
104     if (loadingStreamUrl) {
105         qDebug() << "Already loading stream URL for" << this->title();
106         return;
107     }
108     loadingStreamUrl = true;
109     elIndex = 0;
110     ageGate = false;
111
112     getVideoInfo();
113 }
114
115 void  Video::getVideoInfo() {
116     static const QStringList elTypes = QStringList() << "&el=embedded" << "&el=detailpage" << "&el=vevo" << "";
117
118     QUrl videoInfoUrl;
119
120     if (elIndex == elTypes.size()) {
121         // qDebug() << "Trying special embedded el param";
122         videoInfoUrl = QUrl("http://www.youtube.com/get_video_info");
123         videoInfoUrl.addQueryItem("video_id", videoId);
124         videoInfoUrl.addQueryItem("el", "embedded");
125         videoInfoUrl.addQueryItem("gl", "US");
126         videoInfoUrl.addQueryItem("hl", "en");
127         videoInfoUrl.addQueryItem("eurl", "https://youtube.googleapis.com/v/" + videoId);
128         videoInfoUrl.addQueryItem("asv", "3");
129         videoInfoUrl.addQueryItem("sts", "1588");
130     } else if (elIndex > elTypes.size() - 1) {
131         qWarning() << "Cannot get video info";
132         loadingStreamUrl = false;
133         emit errorStreamUrl("Cannot get video info");
134         return;
135     } else {
136         // qDebug() << "Trying el param:" << elTypes.at(elIndex) << elIndex;
137         videoInfoUrl = QUrl(QString(
138                                 "http://www.youtube.com/get_video_info?video_id=%1%2&ps=default&eurl=&gl=US&hl=en"
139                                 ).arg(videoId, elTypes.at(elIndex)));
140     }
141
142     QObject *reply = The::http()->get(videoInfoUrl);
143     connect(reply, SIGNAL(data(QByteArray)), SLOT(gotVideoInfo(QByteArray)));
144     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
145
146     // see you in gotVideoInfo...
147 }
148
149 void  Video::gotVideoInfo(QByteArray data) {
150     QString videoInfo = QString::fromUtf8(data);
151     // qDebug() << "videoInfo" << videoInfo;
152
153     // get video token
154     QRegExp re = QRegExp("^.*&token=([^&]+).*$");
155     bool match = re.exactMatch(videoInfo);
156     // handle regexp failure
157     if (!match || re.numCaptures() < 1) {
158         // qDebug() << "Cannot get token. Trying next el param";
159         // Don't panic! We're gonna try another magic "el" param
160         elIndex++;
161         getVideoInfo();
162         return;
163     }
164
165     QString videoToken = re.cap(1);
166     while (videoToken.contains('%'))
167         videoToken = QByteArray::fromPercentEncoding(videoToken.toAscii());
168     // qDebug() << "videoToken" << videoToken;
169     this->videoToken = videoToken;
170
171     // get fmt_url_map
172     re = QRegExp("^.*&url_encoded_fmt_stream_map=([^&]+).*$");
173     match = re.exactMatch(videoInfo);
174     // handle regexp failure
175     if (!match || re.numCaptures() < 1) {
176         // qDebug() << "Cannot get urlMap. Trying next el param";
177         // Don't panic! We're gonna try another magic "el" param
178         elIndex++;
179         getVideoInfo();
180         return;
181     }
182
183     // qDebug() << "Got token and urlMap" << elIndex;
184
185     QString fmtUrlMap = re.cap(1);
186     fmtUrlMap = QByteArray::fromPercentEncoding(fmtUrlMap.toUtf8());
187     parseFmtUrlMap(fmtUrlMap);
188 }
189
190 void Video::parseFmtUrlMap(const QString &fmtUrlMap, bool fromWebPage) {
191     QSettings settings;
192     QString definitionName = settings.value("definition", "360p").toString();
193     int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
194
195     // qDebug() << "fmtUrlMap" << fmtUrlMap;
196     QStringList formatUrls = fmtUrlMap.split(',', QString::SkipEmptyParts);
197     QHash<int, QString> urlMap;
198     foreach(QString formatUrl, formatUrls) {
199         // qDebug() << "formatUrl" << formatUrl;
200         QStringList urlParams = formatUrl.split('&', QString::SkipEmptyParts);
201         // qDebug() << "urlParams" << urlParams;
202
203         int format = -1;
204         QString url;
205         QString sig;
206         foreach(QString urlParam, urlParams) {
207             // qWarning() << urlParam;
208             if (urlParam.startsWith("itag=")) {
209                 int separator = urlParam.indexOf("=");
210                 format = urlParam.mid(separator + 1).toInt();
211             } else if (urlParam.startsWith("url=")) {
212                 int separator = urlParam.indexOf("=");
213                 url = urlParam.mid(separator + 1);
214                 url = QByteArray::fromPercentEncoding(url.toUtf8());
215             } else if (urlParam.startsWith("sig=")) {
216                 int separator = urlParam.indexOf("=");
217                 sig = urlParam.mid(separator + 1);
218                 sig = QByteArray::fromPercentEncoding(sig.toUtf8());
219             } else if (urlParam.startsWith("s=")) {
220                 if (fromWebPage || ageGate) {
221                     int separator = urlParam.indexOf("=");
222                     sig = urlParam.mid(separator + 1);
223                     sig = QByteArray::fromPercentEncoding(sig.toUtf8());
224                     if (ageGate)
225                         sig = JsFunctions::instance()->decryptAgeSignature(sig);
226                     else {
227                         sig = decryptSignature(sig);
228                         if (sig.isEmpty())
229                             sig = JsFunctions::instance()->decryptSignature(sig);
230                     }
231                 } else {
232                     // qDebug() << "Loading webpage";
233                     QUrl url("http://www.youtube.com/watch");
234                     url.addQueryItem("v", videoId);
235                     url.addQueryItem("gl", "US");
236                     url.addQueryItem("hl", "en");
237                     url.addQueryItem("has_verified", "1");
238                     QObject *reply = The::http()->get(url);
239                     connect(reply, SIGNAL(data(QByteArray)), SLOT(scrapeWebPage(QByteArray)));
240                     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
241                     // see you in scrapWebPage(QByteArray)
242                     return;
243                 }
244             }
245         }
246         if (format == -1 || url.isNull()) continue;
247
248         url += "&signature=" + sig;
249
250         if (!url.contains("ratebypass"))
251             url += "&ratebypass=yes";
252
253         // qWarning() << url;
254
255         if (format == definitionCode) {
256             qDebug() << "Found format" << definitionCode;
257             QUrl videoUrl = QUrl::fromEncoded(url.toUtf8(), QUrl::StrictMode);
258             m_streamUrl = videoUrl;
259             this->definitionCode = definitionCode;
260             emit gotStreamUrl(videoUrl);
261             loadingStreamUrl = false;
262             return;
263         }
264
265         urlMap.insert(format, url);
266     }
267
268     QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
269     int currentIndex = definitionCodes.indexOf(definitionCode);
270     int previousIndex = 0;
271     while (currentIndex >= 0) {
272         previousIndex = currentIndex - 1;
273         if (previousIndex < 0) previousIndex = 0;
274         int definitionCode = definitionCodes.at(previousIndex);
275         if (urlMap.contains(definitionCode)) {
276             qDebug() << "Found format" << definitionCode;
277             QString url = urlMap.value(definitionCode);
278             QUrl videoUrl = QUrl::fromEncoded(url.toUtf8(), QUrl::StrictMode);
279             m_streamUrl = videoUrl;
280             this->definitionCode = definitionCode;
281             emit gotStreamUrl(videoUrl);
282             loadingStreamUrl = false;
283             return;
284         }
285         currentIndex--;
286     }
287
288     emit errorStreamUrl(tr("Cannot get video stream for %1").arg(m_webpage.toString()));
289 }
290
291 void Video::foundVideoUrl(QString videoToken, int definitionCode) {
292     // qDebug() << "foundVideoUrl" << videoToken << definitionCode;
293
294     QUrl videoUrl = QUrl(QString(
295                              "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
296                              ).arg(videoId, videoToken, QString::number(definitionCode)));
297
298     m_streamUrl = videoUrl;
299     loadingStreamUrl = false;
300     emit gotStreamUrl(videoUrl);
301 }
302
303 void Video::errorVideoInfo(QNetworkReply *reply) {
304     loadingStreamUrl = false;
305     emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
306 }
307
308 void Video::scrapeWebPage(QByteArray data) {
309     QString html = QString::fromUtf8(data);
310     // qWarning() << html;
311
312     if (html.contains("player-age-gate-content\"")) {
313         // qDebug() << "Found ageGate";
314         ageGate = true;
315         elIndex = 4;
316         getVideoInfo();
317         return;
318     }
319
320     QRegExp re(".*\"url_encoded_fmt_stream_map\":\\s+\"([^\"]+)\".*");
321     bool match = re.exactMatch(html);
322     // on regexp failure, stop and report error
323     if (!match || re.numCaptures() < 1) {
324         qWarning() << "Error parsing video page";
325         // emit errorStreamUrl("Error parsing video page");
326         // loadingStreamUrl = false;
327         elIndex++;
328         getVideoInfo();
329         return;
330     }
331     fmtUrlMap = re.cap(1);
332     fmtUrlMap.replace("\\u0026", "&");
333     // parseFmtUrlMap(fmtUrlMap, true);
334
335     QRegExp jsPlayerRe("\"assets\":.+\"js\":\\s*\"([^\"]+)\"");
336     if (jsPlayerRe.indexIn(html) != -1) {
337         QString jsPlayerUrl = jsPlayerRe.cap(1);
338         jsPlayerUrl.remove('\\');
339         jsPlayerUrl = "http:" + jsPlayerUrl;
340         // qDebug() << "jsPlayerUrl" << jsPlayerUrl;
341         /*
342         QRegExp jsPlayerIdRe("-(.+)\\.js");
343         jsPlayerIdRe.indexIn(jsPlayerUrl);
344         QString jsPlayerId = jsPlayerRe.cap(1);
345         */
346         QObject *reply = The::http()->get(jsPlayerUrl);
347         connect(reply, SIGNAL(data(QByteArray)), SLOT(parseJsPlayer(QByteArray)));
348         connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
349     }
350 }
351
352 void Video::gotHeadHeaders(QNetworkReply* reply) {
353     int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
354     // qDebug() << "gotHeaders" << statusCode;
355     if (statusCode == 200) {
356         foundVideoUrl(videoToken, definitionCode);
357     } else {
358
359         // try next (lower quality) definition
360         /*
361         QStringList definitionNames = VideoDefinition::getDefinitionNames();
362         int currentIndex = definitionNames.indexOf(currentDefinition);
363         int previousIndex = 0;
364         if (currentIndex > 0) {
365             previousIndex = currentIndex - 1;
366         }
367         if (previousIndex > 0) {
368             QString nextDefinitionName = definitionNames.at(previousIndex);
369             findVideoUrl(nextDefinitionName);
370         } else {
371             foundVideoUrl(videoToken, 18);
372         }*/
373
374
375         QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
376         int currentIndex = definitionCodes.indexOf(definitionCode);
377         int previousIndex = 0;
378         if (currentIndex > 0) {
379             previousIndex = currentIndex - 1;
380             int definitionCode = definitionCodes.at(previousIndex);
381             if (definitionCode == 18) {
382                 // This is assumed always available
383                 foundVideoUrl(videoToken, 18);
384             } else {
385                 findVideoUrl(definitionCode);
386             }
387
388         } else {
389             foundVideoUrl(videoToken, 18);
390         }
391
392     }
393 }
394
395 void Video::parseJsPlayer(QByteArray bytes) {
396     QString js = QString::fromUtf8(bytes);
397     // qWarning() << "jsPlayer" << js;
398     QRegExp funcNameRe("signature=([" + jsNameChars + "]+)");
399     if (funcNameRe.indexIn(js) == -1) {
400         qWarning() << "Cannot capture signature function name";
401     } else {
402         sigFuncName = funcNameRe.cap(1);
403         captureFunction(sigFuncName, js);
404         // qWarning() << sigFunctions;
405     }
406     parseFmtUrlMap(fmtUrlMap, true);
407 }
408
409 void Video::captureFunction(const QString &name, const QString &js) {
410     QRegExp funcRe("function\\s+" + QRegExp::escape(name) + "\\s*\\([" + jsNameChars + ",\\s]*\\)\\s*\\{[^\\}]+\\}");
411     if (funcRe.indexIn(js) == -1) {
412         qWarning() << "Cannot capture function" << name;
413         return;
414     }
415     QString func = funcRe.cap(0);
416     sigFunctions.insert(name, func);
417
418     // capture inner functions
419     QRegExp invokedFuncRe("[\\s=;\\(]([" + jsNameChars + "]+)\\s*\\([" + jsNameChars + ",\\s]+\\)");
420     int pos = name.length() + 9;
421     while ((pos = invokedFuncRe.indexIn(func, pos)) != -1) {
422         QString funcName = invokedFuncRe.cap(1);
423         if (!sigFunctions.contains(funcName))
424             captureFunction(funcName, js);
425         pos += invokedFuncRe.matchedLength();
426     }
427
428     // capture referenced objects
429     QRegExp objRe("[\\s=;\\(]([" + jsNameChars + "]+)\\.[" + jsNameChars + "]+");
430     pos = name.length() + 9;
431     while ((pos = objRe.indexIn(func, pos)) != -1) {
432         QString objName = objRe.cap(1);
433         if (!sigObjects.contains(objName))
434             captureObject(objName, js);
435         pos += objRe.matchedLength();
436     }
437 }
438
439 void Video::captureObject(const QString &name, const QString &js) {
440     QRegExp re("var\\s+" + QRegExp::escape(name) + "\\s*=\\s*\\{.+\\}\\s*;");
441     re.setMinimal(true);
442     if (re.indexIn(js) == -1) {
443         qWarning() << "Cannot capture object" << name;
444         return;
445     }
446     QString obj = re.cap(0);
447     sigObjects.insert(name, obj);
448 }
449
450 QString Video::decryptSignature(const QString &s) {
451     if (sigFuncName.isEmpty()) return QString();
452     QScriptEngine engine;
453     foreach (QString f, sigObjects.values()) {
454         QScriptValue value = engine.evaluate(f);
455         if (value.isError())
456             qWarning() << "Error in" << f << value.toString();
457     }
458     foreach (QString f, sigFunctions.values()) {
459         QScriptValue value = engine.evaluate(f);
460         if (value.isError())
461             qWarning() << "Error in" << f << value.toString();
462     }
463     QString js = sigFuncName + "('" + s + "');";
464     QScriptValue value = engine.evaluate(js);
465     if (value.isUndefined()) {
466         qWarning() << "Undefined result for" << js;
467         return QString();
468     }
469     if (value.isError()) {
470         qWarning() << "Error in" << js << value.toString();
471         return QString();
472     }
473     return value.toString();
474 }
475
476 void Video::findVideoUrl(int definitionCode) {
477     this->definitionCode = definitionCode;
478
479     QUrl videoUrl = QUrl(QString(
480                              "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
481                              ).arg(videoId, videoToken, QString::number(definitionCode)));
482
483     QObject *reply = The::http()->head(videoUrl);
484     connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(gotHeadHeaders(QNetworkReply*)));
485     // connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
486
487     // see you in gotHeadHeaders()
488 }
489
490 QString Video::formattedDuration() const {
491     QString format = m_duration > 3600 ? "h:mm:ss" : "m:ss";
492     return QTime().addSecs(m_duration).toString(format);
493 }