]> git.sur5r.net Git - minitube/blob - src/yt3.cpp
Imported Upstream version 2.5.1
[minitube] / src / yt3.cpp
1 #include "yt3.h"
2
3 #include <algorithm>
4 #include <ctime>
5
6 #include "jsfunctions.h"
7 #include "networkaccess.h"
8 #include "constants.h"
9 #include "compatibility/qurlqueryhelper.h"
10
11 #ifdef APP_EXTRA
12 #include "extra.h"
13 #endif
14
15 #define STR(x) #x
16 #define STRINGIFY(x) STR(x)
17
18 namespace The {
19 NetworkAccess* http();
20 }
21
22 YT3 &YT3::instance() {
23     static YT3 *i = new YT3();
24     return *i;
25 }
26
27 YT3::YT3() {
28     QByteArray customApiKey = qgetenv("GOOGLE_API_KEY");
29     if (!customApiKey.isEmpty()) {
30         keys << QString::fromUtf8(customApiKey);
31         qDebug() << "API key from environment" << keys;
32     }
33
34     if (keys.isEmpty()) {
35         QSettings settings;
36         if (settings.contains("googleApiKey")) {
37             keys << settings.value("googleApiKey").toString();
38             qDebug() << "API key from settings" << keys;
39         }
40     }
41
42 #ifdef APP_GOOGLE_API_KEY
43     if (keys.isEmpty()) {
44         keys << STRINGIFY(APP_GOOGLE_API_KEY);
45         qDebug() << "built-in API key" << keys;
46     }
47 #endif
48
49 #ifdef APP_EXTRA
50     if (keys.isEmpty())
51         keys << Extra::apiKeys();
52 #endif
53
54     if (keys.isEmpty()) {
55         qWarning() << "No available API keys";
56     } else {
57         key = keys.takeFirst();
58         if (!keys.isEmpty()) testApiKey();
59     }
60 }
61
62 const QString &YT3::baseUrl() {
63     static const QString base = "https://www.googleapis.com/youtube/v3/";
64     return base;
65 }
66
67 void YT3::testApiKey() {
68     QUrl url = method("videos");
69     {
70         QUrlQueryHelper urlHelper(url);
71         urlHelper.addQueryItem("part", "id");
72         urlHelper.addQueryItem("chart", "mostPopular");
73         urlHelper.addQueryItem("maxResults", "1");
74     }
75     QObject *reply = The::http()->get(url);
76     connect(reply, SIGNAL(finished(QNetworkReply*)), SLOT(testResponse(QNetworkReply*)));
77 }
78
79 void YT3::addApiKey(QUrl &url) {
80     if (key.isEmpty()) {
81         qDebug() << __PRETTY_FUNCTION__ << "empty key";
82         return;
83     }
84
85     QUrlQueryHelper urlHelper(url);
86     urlHelper.addQueryItem("key", key);
87 }
88
89 QUrl YT3::method(const QString &name) {
90     QUrl url(baseUrl() + name);
91     addApiKey(url);
92     return url;
93 }
94
95 void YT3::testResponse(QNetworkReply *reply) {
96     int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
97     if (status != 200) {
98         if (keys.isEmpty()) {
99             qWarning() << "Fatal error: No working API keys!";
100             return;
101         }
102         key = keys.takeFirst();
103         testApiKey();
104     } else {
105         qDebug() << "Using key" << key;
106     }
107 }