6 #include "jsfunctions.h"
7 #include "networkaccess.h"
9 #include "compatibility/qurlqueryhelper.h"
16 #define STRINGIFY(x) STR(x)
19 NetworkAccess* http();
22 YT3 &YT3::instance() {
23 static YT3 *i = new YT3();
28 QByteArray customApiKey = qgetenv("GOOGLE_API_KEY");
29 if (!customApiKey.isEmpty()) {
30 keys << QString::fromUtf8(customApiKey);
31 qDebug() << "API key from environment" << keys;
36 if (settings.contains("googleApiKey")) {
37 keys << settings.value("googleApiKey").toString();
38 qDebug() << "API key from settings" << keys;
42 #ifdef APP_GOOGLE_API_KEY
44 keys << STRINGIFY(APP_GOOGLE_API_KEY);
45 qDebug() << "built-in API key" << keys;
51 keys << Extra::apiKeys();
55 qWarning() << "No available API keys";
57 key = keys.takeFirst();
58 if (!keys.isEmpty()) testApiKey();
62 const QString &YT3::baseUrl() {
63 static const QString base = "https://www.googleapis.com/youtube/v3/";
67 void YT3::testApiKey() {
68 QUrl url = method("videos");
70 QUrlQueryHelper urlHelper(url);
71 urlHelper.addQueryItem("part", "id");
72 urlHelper.addQueryItem("chart", "mostPopular");
73 urlHelper.addQueryItem("maxResults", "1");
75 QObject *reply = The::http()->get(url);
76 connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(testResponse(QNetworkReply*)));
79 void YT3::addApiKey(QUrl &url) {
81 qDebug() << __PRETTY_FUNCTION__ << "empty key";
85 QUrlQueryHelper urlHelper(url);
86 urlHelper.addQueryItem("key", key);
89 QUrl YT3::method(const QString &name) {
90 QUrl url(baseUrl() + name);
95 void YT3::testResponse(QNetworkReply *reply) {
96 int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
99 qWarning() << "Fatal error: No working API keys!";
102 key = keys.takeFirst();
105 qDebug() << "Using key" << key;