+/* $BEGIN_LICENSE
+
+This file is part of Minitube.
+Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
+
+Minitube is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Minitube is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with Minitube. If not, see <http://www.gnu.org/licenses/>.
+
+$END_LICENSE */
+
#include "video.h"
-#include "networkaccess.h"
-#include <QtNetwork>
+#include "datautils.h"
+#include "http.h"
+#include "httputils.h"
+#include "jsfunctions.h"
+#include "playlistitemdelegate.h"
#include "videodefinition.h"
-namespace The {
- NetworkAccess* http();
-}
+#include "ytjsvideo.h"
+#include "ytvideo.h"
-Video::Video() : m_duration(0),
-m_viewCount(-1),
-definitionCode(0),
-elIndex(0) { }
+#include "variantpromise.h"
-void Video::preloadThumbnail() {
- if (m_thumbnailUrls.isEmpty()) return;
- QObject *reply = The::http()->get(m_thumbnailUrls.first());
- connect(reply, SIGNAL(data(QByteArray)), SLOT(setThumbnail(QByteArray)));
-}
+Video::Video()
+ : duration(0), viewCount(-1), license(LicenseYouTube), definitionCode(0), ytVideo(nullptr),
+ ytjsVideo(nullptr) {}
-void Video::setThumbnail(QByteArray bytes) {
- m_thumbnail = QImage::fromData(bytes);
- emit gotThumbnail();
+Video::~Video() {
+ qDebug() << "Deleting" << id;
}
-const QImage Video::thumbnail() const {
- return m_thumbnail;
+Video *Video::clone() {
+ Video *clone = new Video();
+ clone->title = title;
+ clone->description = description;
+ clone->channelTitle = channelTitle;
+ clone->channelId = channelId;
+ clone->webpage = webpage;
+ clone->streamUrl = streamUrl;
+ clone->thumbs = thumbs;
+ clone->thumbsNeedSorting = thumbsNeedSorting;
+ clone->duration = duration;
+ clone->formattedDuration = formattedDuration;
+ clone->published = published;
+ clone->formattedPublished = formattedPublished;
+ clone->viewCount = viewCount;
+ clone->formattedViewCount = formattedViewCount;
+ clone->id = id;
+ clone->definitionCode = definitionCode;
+ return clone;
}
-static const QStringList elTypes = QStringList() << "embedded" << "vevo" << "detailpage";
-
-void Video::loadStreamUrl() {
+const QString &Video::getWebpage() {
+ if (webpage.isEmpty() && !id.isEmpty())
+ webpage.append("https://www.youtube.com/watch?v=").append(id);
+ return webpage;
+}
- // https://develop.participatoryculture.org/trac/democracy/browser/trunk/tv/portable/flashscraper.py
+void Video::setWebpage(const QString &value) {
+ webpage = value;
// Get Video ID
- // youtube-dl line 428
- // QRegExp re("^((?:http://)?(?:\\w+\\.)?youtube\\.com/(?:(?:v/)|(?:(?:watch(?:\\.php)?)?\\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$");
- QRegExp re("^http://www\\.youtube\\.com/watch\\?v=([0-9A-Za-z_-]+).*");
- bool match = re.exactMatch(m_webpage.toString());
- if (!match || re.numCaptures() < 1) {
- emit errorStreamUrl(QString("Cannot get video id for %1").arg(m_webpage.toString()));
- return;
+ if (id.isEmpty()) {
+ QRegExp re(JsFunctions::instance()->videoIdRE());
+ if (re.indexIn(webpage) == -1) {
+ qWarning() << QString("Cannot get video id for %1").arg(webpage);
+ // emit errorStreamUrl(QString("Cannot get video id for %1").arg(m_webpage.toString()));
+ // loadingStreamUrl = false;
+ return;
+ }
+ id = re.cap(1);
}
- videoId = re.cap(1);
+}
- getVideoInfo();
+void Video::setDuration(int value) {
+ duration = value;
+ formattedDuration = DataUtils::formatDuration(duration);
+}
+void Video::setViewCount(int value) {
+ viewCount = value;
+ formattedViewCount = DataUtils::formatCount(viewCount);
}
-void Video::getVideoInfo() {
+void Video::setPublished(const QDateTime &value) {
+ published = value;
+ formattedPublished = DataUtils::formatDateTime(published);
+}
- if (elIndex > elTypes.size() - 1) {
- // Don't panic! We have a plan B.
- // get the youtube video webpage
- QObject *reply = The::http()->get(webpage().toString());
- connect(reply, SIGNAL(data(QByteArray)), SLOT(scrapeWebPage(QByteArray)));
- connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
- // see you in scrapWebPage(QByteArray)
- return;
+void Video::streamUrlLoaded(const QString &streamUrl, const QString &audioUrl) {
+ qDebug() << "Streams loaded";
+ this->streamUrl = streamUrl;
+ emit gotStreamUrl(streamUrl, audioUrl);
+ if (ytVideo) {
+ definitionCode = ytVideo->getDefinitionCode();
+ ytVideo->deleteLater();
+ ytVideo = nullptr;
+ }
+ if (ytjsVideo) {
+ definitionCode = ytjsVideo->getDefinitionCode();
+ ytjsVideo->deleteLater();
+ ytjsVideo = nullptr;
}
-
- // Get Video Token
- QUrl videoInfoUrl = QUrl(QString(
- "http://www.youtube.com/get_video_info?video_id=%1&el=%2&ps=default&eurl="
- ).arg(videoId, elTypes.at(elIndex)));
-
- QObject *reply = The::http()->get(videoInfoUrl);
- connect(reply, SIGNAL(data(QByteArray)), SLOT(gotVideoInfo(QByteArray)));
- connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
-
- // see you in gotVideoInfo...
-
}
-void Video::gotVideoInfo(QByteArray data) {
- QString videoInfo = QString::fromUtf8(data);
-
- QRegExp re = QRegExp("^.*&token=([^&]+).*$");
- bool match = re.exactMatch(videoInfo);
-
- // handle regexp failure
- if (!match || re.numCaptures() < 1) {
- // Don't panic! We're gonna try another magic "el" param
- elIndex++;
- getVideoInfo();
+void Video::loadStreamUrlJS() {
+ if (ytjsVideo) {
+ qDebug() << "Already loading" << id;
return;
}
+ ytjsVideo = new YTJSVideo(id, this);
+ connect(ytjsVideo, &YTJSVideo::gotStreamUrl, this, &Video::streamUrlLoaded);
+ connect(ytjsVideo, &YTJSVideo::errorStreamUrl, this, [this](const QString &msg) {
+ qDebug() << msg;
+ ytjsVideo->deleteLater();
+ ytjsVideo = nullptr;
+ // loadStreamUrlYT();
+ emit errorStreamUrl(msg);
+ });
+ ytjsVideo->loadStreamUrl();
+}
- QString videoToken = re.cap(1);
- // FIXME proper decode
- videoToken = videoToken.replace("%3D", "=");
- // we'll need this in gotHeadHeaders()
- this->videoToken = videoToken;
-
- // qDebug() << "token" << videoToken;
-
- QSettings settings;
- QString definitionName = settings.value("definition").toString();
- int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
- if (definitionCode == 18) {
- // This is assumed always available
- foundVideoUrl(videoToken, 18);
- } else {
- findVideoUrl(definitionCode);
+void Video::loadStreamUrlYT() {
+ if (ytVideo) {
+ qDebug() << "Already loading" << id;
+ return;
}
-
+ ytVideo = new YTVideo(id, this);
+ connect(ytVideo, &YTVideo::gotStreamUrl, this, &Video::streamUrlLoaded);
+ connect(ytVideo, &YTVideo::errorStreamUrl, this, [this](const QString &msg) {
+ qDebug() << msg;
+ emit errorStreamUrl(msg);
+ ytVideo->deleteLater();
+ ytVideo = nullptr;
+ });
+ ytVideo->loadStreamUrl();
}
-void Video::foundVideoUrl(QString videoToken, int definitionCode) {
-
- QUrl videoUrl = QUrl(QString(
- "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=embedded&ps=default&fmt=%3"
- ).arg(videoId, videoToken, QString::number(definitionCode)));
-
- m_streamUrl = videoUrl;
- emit gotStreamUrl(videoUrl);
+void Video::loadStreamUrl() {
+ loadStreamUrlJS();
}
-void Video::errorVideoInfo(QNetworkReply *reply) {
- emit errorStreamUrl(tr("Network error: %1 for %2").arg(reply->errorString(), reply->url().toString()));
+bool Video::isLoadingStreamUrl() const {
+ return ytVideo != nullptr || ytjsVideo != nullptr;
}
-void Video::scrapeWebPage(QByteArray data) {
-
- QString videoHTML = QString::fromUtf8(data);
- QRegExp re(".*, \"t\": \"([^\"]+)\".*");
- bool match = re.exactMatch(videoHTML);
-
- // on regexp failure, stop and report error
- if (!match || re.numCaptures() < 1) {
- emit errorStreamUrl("Error parsing video page");
- return;
+void Video::abortLoadStreamUrl() {
+ if (ytVideo) {
+ ytVideo->disconnect(this);
+ ytVideo->deleteLater();
+ ytVideo = nullptr;
}
+ if (ytjsVideo) {
+ ytjsVideo->disconnect(this);
+ ytjsVideo->deleteLater();
+ ytjsVideo = nullptr;
+ }
+}
- QString videoToken = re.cap(1);
- // FIXME proper decode
- videoToken = videoToken.replace("%3D", "=");
-
- // we'll need this in gotHeadHeaders()
- this->videoToken = videoToken;
-
- // qDebug() << "token" << videoToken;
+void Video::addThumb(int width, int height, QString url) {
+ thumbs << YTThumb(width, height, url);
+ thumbsNeedSorting = true;
+}
- QSettings settings;
- QString definitionName = settings.value("definition").toString();
- int definitionCode = VideoDefinition::getDefinitionCode(definitionName);
- if (definitionCode == 18) {
- // This is assumed always available
- foundVideoUrl(videoToken, 18);
- } else {
- findVideoUrl(definitionCode);
+VariantPromise &Video::loadThumb(QSize size, qreal pixelRatio) {
+ if (thumbsNeedSorting) {
+ std::sort(thumbs.begin(), thumbs.end(),
+ [](auto a, auto b) { return a.getWidth() < b.getWidth(); });
+ thumbsNeedSorting = false;
}
-}
+ auto promise = new VariantPromise(this);
+ if (thumbs.isEmpty()) {
+ QTimer::singleShot(0, promise, [promise] { promise->reject("Empty thumbs"); });
+ return *promise;
+ }
-void Video::gotHeadHeaders(QNetworkReply* reply) {
- int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- // qDebug() << "gotHeaders" << statusCode;
- if (statusCode == 200) {
- foundVideoUrl(videoToken, definitionCode);
- } else {
-
- // try next (lower quality) definition
- /*
- QStringList definitionNames = VideoDefinition::getDefinitionNames();
- int currentIndex = definitionNames.indexOf(currentDefinition);
- int previousIndex = 0;
- if (currentIndex > 0) {
- previousIndex = currentIndex - 1;
- }
- if (previousIndex > 0) {
- QString nextDefinitionName = definitionNames.at(previousIndex);
- findVideoUrl(nextDefinitionName);
- } else {
- foundVideoUrl(videoToken, 18);
- }*/
-
-
- QList<int> definitionCodes = VideoDefinition::getDefinitionCodes();
- int currentIndex = definitionCodes.indexOf(definitionCode);
- int previousIndex = 0;
- if (currentIndex > 0) {
- previousIndex = currentIndex - 1;
- int definitionCode = definitionCodes.at(previousIndex);
- if (definitionCode == 18) {
- // This is assumed always available
- foundVideoUrl(videoToken, 18);
- } else {
- findVideoUrl(definitionCode);
+ auto reallyLoad = [this, promise, size, pixelRatio](auto &&self,
+ YTThumb *previous = nullptr) -> void {
+ YTThumb *selected = nullptr;
+
+ static bool fallback = false;
+ if (fallback) {
+ qDebug() << "Doing fallback loop";
+ bool skip = previous != nullptr;
+ for (int i = thumbs.size() - 1; i >= 0; --i) {
+ auto &thumb = thumbs.at(i);
+ if (!skip) {
+ selected = (YTThumb *)&thumb;
+ qDebug() << "selected" << selected->getUrl();
+ break;
+ }
+ if (&thumb == previous) skip = false;
}
-
} else {
- foundVideoUrl(videoToken, 18);
+ bool skip = previous != nullptr;
+ for (auto &thumb : qAsConst(thumbs)) {
+ if (!skip && thumb.getWidth() * pixelRatio >= size.width() &&
+ thumb.getHeight() * pixelRatio >= size.height()) {
+ selected = (YTThumb *)&thumb;
+ qDebug() << "selected" << selected->getUrl();
+ break;
+ }
+ if (&thumb == previous) skip = false;
+ }
}
-
- }
-}
-
-void Video::findVideoUrl(int definitionCode) {
- this->definitionCode = definitionCode;
-
- QUrl videoUrl = QUrl(QString(
- "http://www.youtube.com/get_video?video_id=%1&t=%2&eurl=&el=embedded&ps=default&fmt=%3"
- ).arg(videoId, videoToken, QString::number(definitionCode)));
-
- QObject *reply = The::http()->head(videoUrl);
- connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(gotHeadHeaders(QNetworkReply*)));
- // connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(errorVideoInfo(QNetworkReply*)));
-
- // see you in gotHeadHeaders()
-
+ if (!selected && !fallback) {
+ qDebug() << "Falling back";
+ fallback = true;
+ self(self);
+ return;
+ }
+ if (selected) {
+ qDebug() << "Loading" << selected->getUrl();
+ selected->load(promise)
+ .then([promise](auto variant) { promise->resolve(variant); })
+ .onFailed([self, selected] { self(self, selected); });
+ } else
+ promise->reject("No thumb");
+ };
+ reallyLoad(reallyLoad);
+
+ return *promise;
}