]> git.sur5r.net Git - minitube/blob - src/video.cpp
8cb1f97e03b309b00d2d1817f7f95c04801ac0f1
[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 Video::Video() : m_duration(0),
32     m_viewCount(-1),
33     definitionCode(0),
34     elIndex(0),
35     ageGate(false),
36     m_license(LicenseYouTube),
37     loadingStreamUrl(false),
38     loadingThumbnail(false)
39 { }
40
41 Video* Video::clone() {
42     Video* cloneVideo = new Video();
43     cloneVideo->m_title = m_title;
44     cloneVideo->m_description = m_description;
45     cloneVideo->m_author = m_author;
46     cloneVideo->m_userId = m_userId;
47     cloneVideo->m_webpage = m_webpage;
48     cloneVideo->m_streamUrl = m_streamUrl;
49     cloneVideo->m_thumbnail = m_thumbnail;
50     cloneVideo->m_thumbnailUrl = m_thumbnailUrl;
51     cloneVideo->m_mediumThumbnailUrl = m_mediumThumbnailUrl;
52     cloneVideo->m_duration = m_duration;
53     cloneVideo->m_published = m_published;
54     cloneVideo->m_viewCount = m_viewCount;
55     cloneVideo->videoId = videoId;
56     cloneVideo->videoToken = videoToken;
57     cloneVideo->definitionCode = definitionCode;
58     return cloneVideo;
59 }
60
61 void Video::setWebpage(QUrl webpage) {
62     m_webpage = webpage;
63
64     // Get Video ID
65     // youtube-dl line 428
66     // QRegExp re("^((?:http://)?(?:\\w+\\.)?youtube\\.com/(?:(?:v/)|(?:(?:watch(?:\\.php)?)?\\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$");
67     QRegExp re("^https?://www\\.youtube\\.com/watch\\?v=([0-9A-Za-z_-]+).*");
68     bool match = re.exactMatch(m_webpage.toString());
69     if (!match || re.numCaptures() < 1) {
70         qWarning() << QString("Cannot get video id for %1").arg(m_webpage.toString());
71         // emit errorStreamUrl(QString("Cannot get video id for %1").arg(m_webpage.toString()));
72         // loadingStreamUrl = false;
73         return;
74     }
75     videoId = re.cap(1);
76 }
77
78 void Video::loadThumbnail() {
79     if (m_thumbnailUrl.isEmpty() || loadingThumbnail) return;
80     loadingThumbnail = true;
81     QObject *reply = The::http()->get(m_thumbnailUrl);
82     connect(reply, SIGNAL(data(QByteArray)), SLOT(setThumbnail(QByteArray)));
83 }
84
85 void Video::setThumbnail(QByteArray bytes) {
86     loadingThumbnail = false;
87     m_thumbnail.loadFromData(bytes);
88     if (m_thumbnail.width() > 160)
89         m_thumbnail = m_thumbnail.scaledToWidth(160, Qt::SmoothTransformation);
90     emit gotThumbnail();
91 }
92
93 void Video::loadMediumThumbnail() {
94     if (m_mediumThumbnailUrl.isEmpty()) return;
95     QObject *reply = The::http()->get(m_mediumThumbnailUrl);
96     connect(reply, SIGNAL(data(QByteArray)), SIGNAL(gotMediumThumbnail(QByteArray)));
97 }
98
99 void Video::loadStreamUrl() {
100     if (loadingStreamUrl) {
101         qDebug() << "Already loading stream URL for" << this->title();
102         return;
103     }
104     loadingStreamUrl = true;
105     elIndex = 0;
106     ageGate = false;
107
108     getVideoInfo();
109 }
110
111 void  Video::getVideoInfo() {
112     static const QStringList elTypes = QStringList() << "&el=embedded" << "&el=detailpage" << "&el=vevo" << "";
113
114     QUrl videoInfoUrl;
115
116     if (elIndex == elTypes.size()) {
117         // qDebug() << "Trying special embedded el param";
118         videoInfoUrl = QUrl("http://www.youtube.com/get_video_info");
119         videoInfoUrl.addQueryItem("video_id", videoId);
120         videoInfoUrl.addQueryItem("el", "embedded");
121         videoInfoUrl.addQueryItem("gl", "US");
122         videoInfoUrl.addQueryItem("hl", "en");
123         videoInfoUrl.addQueryItem("eurl", "https://youtube.googleapis.com/v/" + videoId);
124         videoInfoUrl.addQueryItem("asv", "3");
125         videoInfoUrl.addQueryItem("sts", "1588");
126     } else if (elIndex > elTypes.size() - 1) {
127         qWarning() << "Cannot get video info";
128         loadingStreamUrl = false;
129         emit errorStreamUrl("Cannot get video info");
130         return;
131     } else {
132         // qDebug() << "Trying el param:" << elTypes.at(elIndex) << elIndex;
133         videoInfoUrl = QUrl(QString(
134                                 "http://www.youtube.com/get_video_info?video_id=%1%2&ps=default&eurl=&gl=US&hl=en"
135                                 ).arg(videoId, elTypes.at(elIndex)));
136     }
137
138     QObject *reply = The::http()->get(videoInfoUrl);
139     connect(reply, SIGNAL(data(QByteArray)), SLOT(gotVideoInfo(QByteArray)));
140     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
141
142     // see you in gotVideoInfo...
143 }
144
145 void  Video::gotVideoInfo(QByteArray data) {
146     QString videoInfo = QString::fromUtf8(data);
147     // qDebug() << "videoInfo" << videoInfo;
148
149     // get video token
150     QRegExp re = QRegExp("^.*&token=([^&]+).*$");
151     bool match = re.exactMatch(videoInfo);
152     // handle regexp failure
153     if (!match || re.numCaptures() < 1) {
154         // qDebug() << "Cannot get token. Trying next el param";
155         // Don't panic! We're gonna try another magic "el" param
156         elIndex++;
157         getVideoInfo();
158         return;
159     }
160
161     QString videoToken = re.cap(1);
162     while (videoToken.contains('%'))
163         videoToken = QByteArray::fromPercentEncoding(videoToken.toAscii());
164     // qDebug() << "videoToken" << videoToken;
165     this->videoToken = videoToken;
166
167     // get fmt_url_map
168     re = QRegExp("^.*&url_encoded_fmt_stream_map=([^&]+).*$");
169     match = re.exactMatch(videoInfo);
170     // handle regexp failure
171     if (!match || re.numCaptures() < 1) {
172         // qDebug() << "Cannot get urlMap. Trying next el param";
173         // Don't panic! We're gonna try another magic "el" param
174         elIndex++;
175         getVideoInfo();
176         return;
177     }
178
179     // qDebug() << "Got token and urlMap" << elIndex;
180
181     QString fmtUrlMap = re.cap(1);
182     fmtUrlMap = QByteArray::fromPercentEncoding(fmtUrlMap.toUtf8());
183     parseFmtUrlMap(fmtUrlMap);
184 }
185
186 void Video::parseFmtUrlMap(QString fmtUrlMap, bool fromWebPage) {
187     QSettings settings;
188     QString definitionName = settings.value("definition", "360p").toString();
189     int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
190
191     // qDebug() << "fmtUrlMap" << fmtUrlMap;
192     QStringList formatUrls = fmtUrlMap.split(',', QString::SkipEmptyParts);
193     QHash<int, QString> urlMap;
194     foreach(QString formatUrl, formatUrls) {
195         // qDebug() << "formatUrl" << formatUrl;
196         QStringList urlParams = formatUrl.split('&', QString::SkipEmptyParts);
197         // qDebug() << "urlParams" << urlParams;
198
199         int format = -1;
200         QString url;
201         QString sig;
202         foreach(QString urlParam, urlParams) {
203             // qDebug() << urlParam;
204             if (urlParam.startsWith("itag=")) {
205                 int separator = urlParam.indexOf("=");
206                 format = urlParam.mid(separator + 1).toInt();
207             } else if (urlParam.startsWith("url=")) {
208                 int separator = urlParam.indexOf("=");
209                 url = urlParam.mid(separator + 1);
210                 url = QByteArray::fromPercentEncoding(url.toUtf8());
211             } else if (urlParam.startsWith("sig=")) {
212                 int separator = urlParam.indexOf("=");
213                 sig = urlParam.mid(separator + 1);
214                 sig = QByteArray::fromPercentEncoding(sig.toUtf8());
215             } else if (urlParam.startsWith("s=")) {
216                 if (fromWebPage || ageGate) {
217                     int separator = urlParam.indexOf("=");
218                     sig = urlParam.mid(separator + 1);
219                     sig = QByteArray::fromPercentEncoding(sig.toUtf8());
220                     if (ageGate)
221                         sig = JsFunctions::instance()->decryptAgeSignature(sig);
222                     else
223                         sig = JsFunctions::instance()->decryptSignature(sig);
224                 } else {
225                     // qDebug() << "Loading webpage";
226                     QUrl url("http://www.youtube.com/watch");
227                     url.addQueryItem("v", videoId);
228                     url.addQueryItem("gl", "US");
229                     url.addQueryItem("hl", "en");
230                     url.addQueryItem("has_verified", "1");
231                     QObject *reply = The::http()->get(url);
232                     connect(reply, SIGNAL(data(QByteArray)), SLOT(scrapeWebPage(QByteArray)));
233                     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
234                     // see you in scrapWebPage(QByteArray)
235                     return;
236                 }
237             }
238         }
239         if (format == -1 || url.isNull()) continue;
240
241         url += "&signature=" + sig;
242
243         if (!url.contains("ratebypass"))
244             url += "&ratebypass=yes";
245
246         // qWarning() << url;
247
248         if (format == definitionCode) {
249             // qDebug() << "Found format" << definitionCode;
250             QUrl videoUrl = QUrl::fromEncoded(url.toUtf8(), QUrl::StrictMode);
251             m_streamUrl = videoUrl;
252             this->definitionCode = definitionCode;
253             emit gotStreamUrl(videoUrl);
254             loadingStreamUrl = false;
255             return;
256         }
257
258         urlMap.insert(format, url);
259     }
260
261     QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
262     int currentIndex = definitionCodes.indexOf(definitionCode);
263     int previousIndex = 0;
264     while (currentIndex >= 0) {
265         previousIndex = currentIndex - 1;
266         if (previousIndex < 0) previousIndex = 0;
267         int definitionCode = definitionCodes.at(previousIndex);
268         if (urlMap.contains(definitionCode)) {
269             // qDebug() << "Found format" << definitionCode;
270             QString url = urlMap.value(definitionCode);
271             QUrl videoUrl = QUrl::fromEncoded(url.toUtf8(), QUrl::StrictMode);
272             m_streamUrl = videoUrl;
273             this->definitionCode = definitionCode;
274             emit gotStreamUrl(videoUrl);
275             loadingStreamUrl = false;
276             return;
277         }
278         currentIndex--;
279     }
280
281     emit errorStreamUrl(tr("Cannot get video stream for %1").arg(m_webpage.toString()));
282 }
283
284 void Video::foundVideoUrl(QString videoToken, int definitionCode) {
285     // qDebug() << "foundVideoUrl" << videoToken << definitionCode;
286
287     QUrl videoUrl = QUrl(QString(
288                              "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
289                              ).arg(videoId, videoToken, QString::number(definitionCode)));
290
291     m_streamUrl = videoUrl;
292     loadingStreamUrl = false;
293     emit gotStreamUrl(videoUrl);
294 }
295
296 void Video::errorVideoInfo(QNetworkReply *reply) {
297     loadingStreamUrl = false;
298     emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
299 }
300
301 void Video::scrapeWebPage(QByteArray data) {
302     QString html = QString::fromUtf8(data);
303     // qWarning() << html;
304
305     if (html.contains("player-age-gate-content\"")) {
306         // qDebug() << "Found ageGate";
307         ageGate = true;
308         elIndex = 4;
309         getVideoInfo();
310         return;
311     }
312
313     QRegExp re(".*\"url_encoded_fmt_stream_map\":\\s+\"([^\"]+)\".*");
314     bool match = re.exactMatch(html);
315     // on regexp failure, stop and report error
316     if (!match || re.numCaptures() < 1) {
317         qWarning() << "Error parsing video page";
318         // emit errorStreamUrl("Error parsing video page");
319         // loadingStreamUrl = false;
320         elIndex++;
321         getVideoInfo();
322         return;
323     }
324     QString fmtUrlMap = re.cap(1);
325     fmtUrlMap.replace("\\u0026", "&");
326     parseFmtUrlMap(fmtUrlMap, true);
327 }
328
329 void Video::gotHeadHeaders(QNetworkReply* reply) {
330     int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
331     // qDebug() << "gotHeaders" << statusCode;
332     if (statusCode == 200) {
333         foundVideoUrl(videoToken, definitionCode);
334     } else {
335
336         // try next (lower quality) definition
337         /*
338         QStringList definitionNames = VideoDefinition::getDefinitionNames();
339         int currentIndex = definitionNames.indexOf(currentDefinition);
340         int previousIndex = 0;
341         if (currentIndex > 0) {
342             previousIndex = currentIndex - 1;
343         }
344         if (previousIndex > 0) {
345             QString nextDefinitionName = definitionNames.at(previousIndex);
346             findVideoUrl(nextDefinitionName);
347         } else {
348             foundVideoUrl(videoToken, 18);
349         }*/
350
351
352         QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
353         int currentIndex = definitionCodes.indexOf(definitionCode);
354         int previousIndex = 0;
355         if (currentIndex > 0) {
356             previousIndex = currentIndex - 1;
357             int definitionCode = definitionCodes.at(previousIndex);
358             if (definitionCode == 18) {
359                 // This is assumed always available
360                 foundVideoUrl(videoToken, 18);
361             } else {
362                 findVideoUrl(definitionCode);
363             }
364
365         } else {
366             foundVideoUrl(videoToken, 18);
367         }
368
369     }
370 }
371
372 void Video::findVideoUrl(int definitionCode) {
373     this->definitionCode = definitionCode;
374
375     QUrl videoUrl = QUrl(QString(
376                              "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
377                              ).arg(videoId, videoToken, QString::number(definitionCode)));
378
379     QObject *reply = The::http()->head(videoUrl);
380     connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(gotHeadHeaders(QNetworkReply*)));
381     // connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
382
383     // see you in gotHeadHeaders()
384
385 }
386
387 QString Video::formattedDuration() const {
388     QString format = m_duration > 3600 ? "h:mm:ss" : "m:ss";
389     return QTime().addSecs(m_duration).toString(format);
390 }