]> git.sur5r.net Git - minitube/blob - src/ytuser.cpp
9dc633adcb8bac2531a17f6e2a4c257acf6298ba
[minitube] / src / ytuser.cpp
1 /* $BEGIN_LICENSE
2
3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
5
6 Minitube is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Minitube is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Minitube.  If not, see <http://www.gnu.org/licenses/>.
18
19 $END_LICENSE */
20
21 #include "ytuser.h"
22 #include "networkaccess.h"
23 #include "database.h"
24 #include <QtSql>
25
26 namespace The {
27 NetworkAccess* http();
28 }
29
30 YTUser::YTUser(QString userId, QObject *parent) : QObject(parent),
31     id(0),
32     userId(userId),
33     loadingThumbnail(false),
34     notifyCount(0),
35     checked(0),
36     watched(0),
37     loaded(0),
38     loading(false) { }
39
40 QHash<QString, YTUser*> YTUser::cache;
41
42 YTUser* YTUser::forId(QString userId) {
43     if (userId.isEmpty()) return 0;
44
45     if (cache.contains(userId))
46         return cache.value(userId);
47
48     QSqlDatabase db = Database::instance().getConnection();
49     QSqlQuery query(db);
50     query.prepare("select id,name,description,thumb_url,notify_count,watched,checked,loaded "
51                   "from subscriptions where user_id=?");
52     query.bindValue(0, userId);
53     bool success = query.exec();
54     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
55
56     YTUser* user = 0;
57     if (query.next()) {
58         user = new YTUser(userId);
59         user->id = query.value(0).toInt();
60         user->displayName = query.value(1).toString();
61         user->description = query.value(2).toString();
62         user->thumbnailUrl = query.value(3).toString();
63         user->notifyCount = query.value(4).toInt();
64         user->watched = query.value(5).toUInt();
65         user->checked = query.value(6).toUInt();
66         user->loaded = query.value(7).toUInt();
67         user->thumbnail = QPixmap(user->getThumbnailLocation());
68         user->maybeLoadfromAPI();
69         cache.insert(userId, user);
70     }
71
72     return user;
73 }
74
75 void YTUser::maybeLoadfromAPI() {
76     if (loading) return;
77     if (userId.isEmpty()) return;
78
79     uint now = QDateTime::currentDateTime().toTime_t();
80     static const int refreshInterval = 60 * 60 * 24 * 10;
81     if (loaded > now - refreshInterval) return;
82
83     loading = true;
84
85     QUrl url("http://gdata.youtube.com/feeds/api/users/" + userId);
86     url.addQueryItem("v", "2");
87     QObject *reply = The::http()->get(url);
88     connect(reply, SIGNAL(data(QByteArray)), SLOT(parseResponse(QByteArray)));
89     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(requestError(QNetworkReply*)));
90 }
91
92 void YTUser::parseResponse(QByteArray bytes) {
93     QXmlStreamReader xml(bytes);
94     xml.readNextStartElement();
95     if (xml.name() == QLatin1String("entry"))
96         while(xml.readNextStartElement()) {
97             const QStringRef n = xml.name();
98             if (n == QLatin1String("summary"))
99                 description = xml.readElementText().simplified();
100             else if (n == QLatin1String("title"))
101                 displayName = xml.readElementText();
102             else if (n == QLatin1String("thumbnail")) {
103                 thumbnailUrl = xml.attributes().value("url").toString();
104                 xml.skipCurrentElement();
105             } else if (n == QLatin1String("username"))
106                 userName = xml.readElementText();
107             else xml.skipCurrentElement();
108         }
109
110     if (xml.hasError()) {
111         emit error(xml.errorString());
112         qWarning() << xml.errorString();
113     }
114
115     emit infoLoaded();
116     storeInfo();
117     loading = false;
118 }
119
120 void YTUser::loadThumbnail() {
121     if (loadingThumbnail) return;
122     if (thumbnailUrl.isEmpty()) return;
123     loadingThumbnail = true;
124
125 #ifdef Q_WS_WIN
126     thumbnailUrl.replace(QLatin1String("https://"), QLatin1String("http://"));
127 #endif
128
129     QUrl url(thumbnailUrl);
130     QObject *reply = The::http()->get(url);
131     connect(reply, SIGNAL(data(QByteArray)), SLOT(storeThumbnail(QByteArray)));
132     connect(reply, SIGNAL(error(QNetworkReply*)), SLOT(requestError(QNetworkReply*)));
133 }
134
135 const QString & YTUser::getThumbnailDir() {
136     static const QString thumbDir = QDesktopServices::storageLocation(
137                 QDesktopServices::DataLocation) + "/channels/";
138     return thumbDir;
139 }
140
141 QString YTUser::getThumbnailLocation() {
142     return getThumbnailDir() + userId;
143 }
144
145 void YTUser::storeThumbnail(QByteArray bytes) {
146     thumbnail.loadFromData(bytes);
147     static const int maxWidth = 88;
148
149     QDir dir;
150     dir.mkpath(getThumbnailDir());
151
152     if (thumbnail.width() > maxWidth) {
153         thumbnail = thumbnail.scaledToWidth(maxWidth, Qt::SmoothTransformation);
154         thumbnail.save(getThumbnailLocation(), "JPG");
155     } else {
156         QFile file(getThumbnailLocation());
157         if (!file.open(QIODevice::WriteOnly))
158             qWarning() << "Error opening file for writing" << file.fileName();
159         QDataStream stream(&file);
160         stream.writeRawData(bytes.constData(), bytes.size());
161     }
162
163     emit thumbnailLoaded();
164     loadingThumbnail = false;
165 }
166
167 void YTUser::requestError(QNetworkReply *reply) {
168     emit error(reply->errorString());
169     qWarning() << reply->errorString();
170     loading = false;
171     loadingThumbnail = false;
172 }
173
174 void YTUser::storeInfo() {
175     if (userId.isEmpty()) return;
176     QSqlDatabase db = Database::instance().getConnection();
177     QSqlQuery query(db);
178     query.prepare("update subscriptions set "
179                   "user_name=?, name=?, description=?, thumb_url=?, loaded=? "
180                   "where user_id=?");
181     qDebug() << userName;
182     query.bindValue(0, userName);
183     query.bindValue(1, displayName);
184     query.bindValue(2, description);
185     query.bindValue(3, thumbnailUrl);
186     query.bindValue(4, QDateTime::currentDateTime().toTime_t());
187     query.bindValue(5, userId);
188     bool success = query.exec();
189     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
190
191     loadThumbnail();
192 }
193
194 void YTUser::subscribe(QString userId) {
195     if (userId.isEmpty()) return;
196
197     uint now = QDateTime::currentDateTime().toTime_t();
198
199     QSqlDatabase db = Database::instance().getConnection();
200     QSqlQuery query(db);
201     query.prepare("insert into subscriptions "
202                   "(user_id,added,watched,checked,views,notify_count)"
203                   " values (?,?,?,0,0,0)");
204     query.bindValue(0, userId);
205     query.bindValue(1, now);
206     query.bindValue(2, now);
207     bool success = query.exec();
208     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
209
210     // This will call maybeLoadFromApi
211     YTUser::forId(userId);
212 }
213
214 void YTUser::unsubscribe(QString userId) {
215     if (userId.isEmpty()) return;
216     QSqlDatabase db = Database::instance().getConnection();
217     QSqlQuery query(db);
218     query.prepare("delete from subscriptions where user_id=?");
219     query.bindValue(0, userId);
220     bool success = query.exec();
221     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
222
223     query = QSqlQuery(db);
224     query.prepare("delete from subscriptions_videos where user_id=?");
225     query.bindValue(0, userId);
226     success = query.exec();
227     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
228
229     YTUser *user = cache.take(userId);
230     if (user) user->deleteLater();
231 }
232
233 bool YTUser::isSubscribed(QString userId) {
234     if (!Database::exists()) return false;
235     if (userId.isEmpty()) return false;
236     QSqlDatabase db = Database::instance().getConnection();
237     QSqlQuery query(db);
238     query.prepare("select count(*) from subscriptions where user_id=?");
239     query.bindValue(0, userId);
240     bool success = query.exec();
241     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
242     if (query.next())
243         return query.value(0).toInt() > 0;
244     return false;
245 }
246
247 void YTUser::updateChecked() {
248     if (userId.isEmpty()) return;
249
250     uint now = QDateTime::currentDateTime().toTime_t();
251     checked = now;
252
253     QSqlDatabase db = Database::instance().getConnection();
254     QSqlQuery query(db);
255     query.prepare("update subscriptions set checked=? where user_id=?");
256     query.bindValue(0, QDateTime::currentDateTime().toTime_t());
257     query.bindValue(1, userId);
258     bool success = query.exec();
259     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
260 }
261
262 void YTUser::updateWatched() {
263     if (userId.isEmpty()) return;
264
265     uint now = QDateTime::currentDateTime().toTime_t();
266     watched = now;
267     notifyCount = 0;
268
269     QSqlDatabase db = Database::instance().getConnection();
270     QSqlQuery query(db);
271     query.prepare("update subscriptions set watched=?, notify_count=0, views=views+1 where user_id=?");
272     query.bindValue(0, now);
273     query.bindValue(1, userId);
274     bool success = query.exec();
275     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
276 }
277
278 void YTUser::storeNotifyCount(int count) {
279     notifyCount = count;
280
281     QSqlDatabase db = Database::instance().getConnection();
282     QSqlQuery query(db);
283     query.prepare("update subscriptions set notify_count=? where user_id=?");
284     query.bindValue(0, count);
285     query.bindValue(1, userId);
286     bool success = query.exec();
287     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
288 }
289
290 bool YTUser::updateNotifyCount() {
291     QSqlDatabase db = Database::instance().getConnection();
292     QSqlQuery query(db);
293     query.prepare("select count(*) from subscriptions_videos "
294                   "where channel_id=? and added>? and published>? and watched=0");
295     query.bindValue(0, id);
296     query.bindValue(1, watched);
297     query.bindValue(2, watched);
298     bool success = query.exec();
299     if (!success) qWarning() << query.lastQuery() << query.lastError().text();
300     if (!query.next()) {
301         qWarning() << __PRETTY_FUNCTION__ << "Count failed";
302         return false;
303     }
304     int count = query.value(0).toInt();
305     storeNotifyCount(count);
306     return count != notifyCount;
307 }