9 #include "jsfunctions.h"
10 #include "mainwindow.h"
11 #include "videodefinition.h"
18 #define STRINGIFY(x) STR(x)
20 YT3 &YT3::instance() {
25 const QString &YT3::baseUrl() {
26 static const QString base = "https://www.googleapis.com/youtube/v3/";
33 void YT3::initApiKeys() {
36 QByteArray customApiKey = qgetenv("GOOGLE_API_KEY");
37 if (!customApiKey.isEmpty()) {
38 keys << QString::fromUtf8(customApiKey);
39 qDebug() << "API key from environment" << keys;
44 if (settings.contains("googleApiKey")) {
45 keys << settings.value("googleApiKey").toString();
46 qDebug() << "API key from settings" << keys;
50 #ifdef APP_GOOGLE_API_KEY
52 keys << STRINGIFY(APP_GOOGLE_API_KEY);
53 qDebug() << "built-in API key" << keys;
58 if (keys.isEmpty()) keys << Extra::apiKeys();
62 qWarning() << "No available API keys";
64 QMetaObject::invokeMethod(MainWindow::instance(), "missingKeyWarning",
65 Qt::QueuedConnection);
68 key = keys.takeFirst();
69 if (!keys.isEmpty()) testApiKey();
73 void YT3::testApiKey() {
74 QUrl url = method("videos");
76 q.addQueryItem("part", "id");
77 q.addQueryItem("chart", "mostPopular");
78 q.addQueryItem("maxResults", "1");
80 QObject *reply = HttpUtils::stealthAndNotCached().get(url);
81 connect(reply, SIGNAL(finished(HttpReply)), SLOT(testResponse(HttpReply)));
84 void YT3::addApiKey(QUrl &url) {
86 qDebug() << __PRETTY_FUNCTION__ << "empty key";
92 q.addQueryItem("key", key);
96 QUrl YT3::method(const QString &name) {
97 QUrl url(baseUrl() + name);
102 const VideoDefinition &YT3::maxVideoDefinition() {
103 const QString name = QSettings().value("definition", "720p").toString();
104 const VideoDefinition &definition = VideoDefinition::forName(name);
108 void YT3::setMaxVideoDefinition(const QString &name) {
110 settings.setValue("definition", name);
111 emit maxVideoDefinitionChanged(name);
114 void YT3::testResponse(const HttpReply &reply) {
115 int status = reply.statusCode();
117 if (keys.isEmpty()) {
118 qWarning() << "Fatal error: No working API keys!";
121 key = keys.takeFirst();
124 qDebug() << "Using key" << key;