3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
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.
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.
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/>.
22 #include "networkaccess.h"
24 #include "videodefinition.h"
25 #include "jsfunctions.h"
28 NetworkAccess* http();
32 static const QString jsNameChars = "a-zA-Z0-9\\$_";
35 Video::Video() : m_duration(0),
40 m_license(LicenseYouTube),
41 loadingStreamUrl(false),
42 loadingThumbnail(false)
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;
65 void Video::setWebpage(QUrl webpage) {
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;
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)));
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);
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)));
103 void Video::loadStreamUrl() {
104 if (loadingStreamUrl) {
105 qDebug() << "Already loading stream URL for" << this->title();
108 loadingStreamUrl = true;
115 void Video::getVideoInfo() {
116 static const QStringList elTypes = QStringList() << "&el=embedded" << "&el=detailpage" << "&el=vevo" << "";
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");
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)));
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*)));
146 // see you in gotVideoInfo...
149 void Video::gotVideoInfo(QByteArray data) {
150 QString videoInfo = QString::fromUtf8(data);
151 // qDebug() << "videoInfo" << videoInfo;
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
165 QString videoToken = re.cap(1);
166 while (videoToken.contains('%'))
167 videoToken = QByteArray::fromPercentEncoding(videoToken.toAscii());
168 // qDebug() << "videoToken" << videoToken;
169 this->videoToken = videoToken;
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
183 // qDebug() << "Got token and urlMap" << elIndex;
185 QString fmtUrlMap = re.cap(1);
186 fmtUrlMap = QByteArray::fromPercentEncoding(fmtUrlMap.toUtf8());
187 parseFmtUrlMap(fmtUrlMap);
190 void Video::parseFmtUrlMap(const QString &fmtUrlMap, bool fromWebPage) {
192 QString definitionName = settings.value("definition", "360p").toString();
193 int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
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;
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());
225 sig = JsFunctions::instance()->decryptAgeSignature(sig);
227 sig = decryptSignature(sig);
229 sig = JsFunctions::instance()->decryptSignature(sig);
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)
246 if (format == -1 || url.isNull()) continue;
248 url += "&signature=" + sig;
250 if (!url.contains("ratebypass"))
251 url += "&ratebypass=yes";
253 // qWarning() << url;
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;
265 urlMap.insert(format, url);
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;
288 emit errorStreamUrl(tr("Cannot get video stream for %1").arg(m_webpage.toString()));
291 void Video::foundVideoUrl(QString videoToken, int definitionCode) {
292 // qDebug() << "foundVideoUrl" << videoToken << definitionCode;
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)));
298 m_streamUrl = videoUrl;
299 loadingStreamUrl = false;
300 emit gotStreamUrl(videoUrl);
303 void Video::errorVideoInfo(QNetworkReply *reply) {
304 loadingStreamUrl = false;
305 emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
308 void Video::scrapeWebPage(QByteArray data) {
309 QString html = QString::fromUtf8(data);
310 // qWarning() << html;
312 if (html.contains("player-age-gate-content\"")) {
313 // qDebug() << "Found ageGate";
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;
331 fmtUrlMap = re.cap(1);
332 fmtUrlMap.replace("\\u0026", "&");
333 // parseFmtUrlMap(fmtUrlMap, true);
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;
342 QRegExp jsPlayerIdRe("-(.+)\\.js");
343 jsPlayerIdRe.indexIn(jsPlayerUrl);
344 QString jsPlayerId = jsPlayerRe.cap(1);
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*)));
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);
359 // try next (lower quality) definition
361 QStringList definitionNames = VideoDefinition::getDefinitionNames();
362 int currentIndex = definitionNames.indexOf(currentDefinition);
363 int previousIndex = 0;
364 if (currentIndex > 0) {
365 previousIndex = currentIndex - 1;
367 if (previousIndex > 0) {
368 QString nextDefinitionName = definitionNames.at(previousIndex);
369 findVideoUrl(nextDefinitionName);
371 foundVideoUrl(videoToken, 18);
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);
385 findVideoUrl(definitionCode);
389 foundVideoUrl(videoToken, 18);
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";
402 sigFuncName = funcNameRe.cap(1);
403 captureFunction(sigFuncName, js);
404 // qWarning() << sigFunctions;
406 parseFmtUrlMap(fmtUrlMap, true);
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;
415 QString func = funcRe.cap(0);
416 sigFunctions.insert(name, func);
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();
429 QString Video::decryptSignature(const QString &s) {
430 if (sigFuncName.isEmpty()) return QString();
431 QScriptEngine engine;
432 foreach (QString f, sigFunctions.values()) {
433 QScriptValue value = engine.evaluate(f);
435 qWarning() << "Error in" << f << value.toString();
437 QString js = sigFuncName + "('" + s + "');";
438 QScriptValue value = engine.evaluate(js);
439 if (value.isUndefined()) {
440 qWarning() << "Undefined result for" << js;
443 if (value.isError()) {
444 qWarning() << "Error in" << js << value.toString();
447 return value.toString();
450 void Video::findVideoUrl(int definitionCode) {
451 this->definitionCode = definitionCode;
453 QUrl videoUrl = QUrl(QString(
454 "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=&ps=&asv=&fmt=%3"
455 ).arg(videoId, videoToken, QString::number(definitionCode)));
457 QObject *reply = The::http()->head(videoUrl);
458 connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(gotHeadHeaders(QNetworkReply*)));
459 // connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
461 // see you in gotHeadHeaders()
464 QString Video::formattedDuration() const {
465 QString format = m_duration > 3600 ? "h:mm:ss" : "m:ss";
466 return QTime().addSecs(m_duration).toString(format);