9 #include "jsfunctions.h"
10 #include "mainwindow.h"
11 #include "videodefinition.h"
18 #define STRINGIFY(x) STR(x)
20 YT3 &YT3::instance() {
21 static YT3 *i = new YT3();
25 const QString &YT3::baseUrl() {
26 static const QString base = "https://www.googleapis.com/youtube/v3/";
34 void YT3::initApiKeys() {
37 QByteArray customApiKey = qgetenv("GOOGLE_API_KEY");
38 if (!customApiKey.isEmpty()) {
39 keys << QString::fromUtf8(customApiKey);
40 qDebug() << "API key from environment" << keys;
45 if (settings.contains("googleApiKey")) {
46 keys << settings.value("googleApiKey").toString();
47 qDebug() << "API key from settings" << keys;
51 #ifdef APP_GOOGLE_API_KEY
53 keys << STRINGIFY(APP_GOOGLE_API_KEY);
54 qDebug() << "built-in API key" << keys;
59 if (keys.isEmpty()) keys << Extra::apiKeys();
63 qWarning() << "No available API keys";
65 QMetaObject::invokeMethod(MainWindow::instance(), "missingKeyWarning",
66 Qt::QueuedConnection);
69 key = keys.takeFirst();
70 if (!keys.isEmpty()) testApiKey();
74 void YT3::testApiKey() {
75 QUrl url = method("videos");
77 q.addQueryItem("part", "id");
78 q.addQueryItem("chart", "mostPopular");
79 q.addQueryItem("maxResults", "1");
81 QObject *reply = HttpUtils::stealthAndNotCached().get(url);
82 connect(reply, SIGNAL(finished(HttpReply)), SLOT(testResponse(HttpReply)));
85 void YT3::addApiKey(QUrl &url) {
87 qDebug() << __PRETTY_FUNCTION__ << "empty key";
93 q.addQueryItem("key", key);
97 QUrl YT3::method(const QString &name) {
98 QUrl url(baseUrl() + name);
103 const VideoDefinition &YT3::maxVideoDefinition() {
104 const QString name = QSettings().value("definition", "720p").toString();
105 const VideoDefinition &definition = VideoDefinition::forName(name);
109 void YT3::setMaxVideoDefinition(const QString &name) {
111 settings.setValue("definition", name);
112 emit maxVideoDefinitionChanged(name);
115 void YT3::testResponse(const HttpReply &reply) {
116 int status = reply.statusCode();
118 if (keys.isEmpty()) {
119 qWarning() << "Fatal error: No working API keys!";
122 key = keys.takeFirst();
125 qDebug() << "Using key" << key;