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();
31 Video::Video() : m_duration(0),
36 m_license(LicenseYouTube),
37 loadingStreamUrl(false),
38 loadingThumbnail(false)
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;
61 void Video::setWebpage(QUrl webpage) {
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;
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)));
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);
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)));
99 void Video::loadStreamUrl() {
100 if (loadingStreamUrl) {
101 qDebug() << "Already loading stream URL for" << this->title();
104 loadingStreamUrl = true;
111 void Video::getVideoInfo() {
112 static const QStringList elTypes = QStringList() << "&el=embedded" << "&el=detailpage" << "&el=vevo" << "";
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");
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)));
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*)));
142 // see you in gotVideoInfo...
145 void Video::gotVideoInfo(QByteArray data) {
146 QString videoInfo = QString::fromUtf8(data);
147 // qDebug() << "videoInfo" << videoInfo;
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
161 QString videoToken = re.cap(1);
162 while (videoToken.contains('%'))
163 videoToken = QByteArray::fromPercentEncoding(videoToken.toAscii());
164 // qDebug() << "videoToken" << videoToken;
165 this->videoToken = videoToken;
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
179 // qDebug() << "Got token and urlMap" << elIndex;
181 QString fmtUrlMap = re.cap(1);
182 fmtUrlMap = QByteArray::fromPercentEncoding(fmtUrlMap.toUtf8());
183 parseFmtUrlMap(fmtUrlMap);
186 void Video::parseFmtUrlMap(QString fmtUrlMap, bool fromWebPage) {
188 QString definitionName = settings.value("definition", "360p").toString();
189 int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
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;
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());
221 sig = JsFunctions::instance()->decryptAgeSignature(sig);
223 sig = JsFunctions::instance()->decryptSignature(sig);
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)
239 if (format == -1 || url.isNull()) continue;
241 url += "&signature=" + sig;
243 if (!url.contains("ratebypass"))
244 url += "&ratebypass=yes";
246 // qWarning() << url;
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;
258 urlMap.insert(format, url);
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;
281 emit errorStreamUrl(tr("Cannot get video stream for %1").arg(m_webpage.toString()));
284 void Video::foundVideoUrl(QString videoToken, int definitionCode) {
285 // qDebug() << "foundVideoUrl" << videoToken << definitionCode;
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)));
291 m_streamUrl = videoUrl;
292 loadingStreamUrl = false;
293 emit gotStreamUrl(videoUrl);
296 void Video::errorVideoInfo(QNetworkReply *reply) {
297 loadingStreamUrl = false;
298 emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
301 void Video::scrapeWebPage(QByteArray data) {
302 QString html = QString::fromUtf8(data);
303 // qWarning() << html;
305 if (html.contains("player-age-gate-content\"")) {
306 // qDebug() << "Found ageGate";
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;
324 QString fmtUrlMap = re.cap(1);
325 fmtUrlMap.replace("\\u0026", "&");
326 parseFmtUrlMap(fmtUrlMap, true);
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);
336 // try next (lower quality) definition
338 QStringList definitionNames = VideoDefinition::getDefinitionNames();
339 int currentIndex = definitionNames.indexOf(currentDefinition);
340 int previousIndex = 0;
341 if (currentIndex > 0) {
342 previousIndex = currentIndex - 1;
344 if (previousIndex > 0) {
345 QString nextDefinitionName = definitionNames.at(previousIndex);
346 findVideoUrl(nextDefinitionName);
348 foundVideoUrl(videoToken, 18);
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);
362 findVideoUrl(definitionCode);
366 foundVideoUrl(videoToken, 18);
372 void Video::findVideoUrl(int definitionCode) {
373 this->definitionCode = definitionCode;
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)));
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*)));
383 // see you in gotHeadHeaders()
387 QString Video::formattedDuration() const {
388 QString format = m_duration > 3600 ? "h:mm:ss" : "m:ss";
389 return QTime().addSecs(m_duration).toString(format);