3 This file is part of Minitube.
4 Copyright 2009, Flavio Tordini <flavio.tordini@gmail.com>
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.
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.
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/>.
22 #include "networkaccess.h"
27 NetworkAccess* http();
30 YTUser::YTUser(QString userId, QObject *parent) : QObject(parent),
33 loadingThumbnail(false),
40 QHash<QString, YTUser*> YTUser::cache;
42 YTUser* YTUser::forId(QString userId) {
43 if (userId.isEmpty()) return 0;
45 if (cache.contains(userId))
46 return cache.value(userId);
48 QSqlDatabase db = Database::instance().getConnection();
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();
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);
75 void YTUser::maybeLoadfromAPI() {
77 if (userId.isEmpty()) return;
79 uint now = QDateTime::currentDateTime().toTime_t();
80 static const int refreshInterval = 60 * 60 * 24 * 10;
81 if (loaded > now - refreshInterval) return;
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*)));
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();
110 if (xml.hasError()) {
111 emit error(xml.errorString());
112 qWarning() << xml.errorString();
120 void YTUser::loadThumbnail() {
121 if (loadingThumbnail) return;
122 if (thumbnailUrl.isEmpty()) return;
123 loadingThumbnail = true;
126 thumbnailUrl.replace(QLatin1String("https://"), QLatin1String("http://"));
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*)));
135 const QString & YTUser::getThumbnailDir() {
136 static const QString thumbDir = QDesktopServices::storageLocation(
137 QDesktopServices::DataLocation) + "/channels/";
141 QString YTUser::getThumbnailLocation() {
142 return getThumbnailDir() + userId;
145 void YTUser::storeThumbnail(QByteArray bytes) {
146 thumbnail.loadFromData(bytes);
147 static const int maxWidth = 88;
150 dir.mkpath(getThumbnailDir());
152 if (thumbnail.width() > maxWidth) {
153 thumbnail = thumbnail.scaledToWidth(maxWidth, Qt::SmoothTransformation);
154 thumbnail.save(getThumbnailLocation(), "JPG");
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());
163 emit thumbnailLoaded();
164 loadingThumbnail = false;
167 void YTUser::requestError(QNetworkReply *reply) {
168 emit error(reply->errorString());
169 qWarning() << reply->errorString();
171 loadingThumbnail = false;
174 void YTUser::storeInfo() {
175 if (userId.isEmpty()) return;
176 QSqlDatabase db = Database::instance().getConnection();
178 query.prepare("update subscriptions set "
179 "user_name=?, name=?, description=?, thumb_url=?, loaded=? "
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();
194 void YTUser::subscribe(QString userId) {
195 if (userId.isEmpty()) return;
197 uint now = QDateTime::currentDateTime().toTime_t();
199 QSqlDatabase db = Database::instance().getConnection();
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();
210 // This will call maybeLoadFromApi
211 YTUser::forId(userId);
214 void YTUser::unsubscribe(QString userId) {
215 if (userId.isEmpty()) return;
216 QSqlDatabase db = Database::instance().getConnection();
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();
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();
229 YTUser *user = cache.take(userId);
230 if (user) user->deleteLater();
233 bool YTUser::isSubscribed(QString userId) {
234 if (!Database::exists()) return false;
235 if (userId.isEmpty()) return false;
236 QSqlDatabase db = Database::instance().getConnection();
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();
243 return query.value(0).toInt() > 0;
247 void YTUser::updateChecked() {
248 if (userId.isEmpty()) return;
250 uint now = QDateTime::currentDateTime().toTime_t();
253 QSqlDatabase db = Database::instance().getConnection();
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();
262 void YTUser::updateWatched() {
263 if (userId.isEmpty()) return;
265 uint now = QDateTime::currentDateTime().toTime_t();
269 QSqlDatabase db = Database::instance().getConnection();
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();
278 void YTUser::storeNotifyCount(int count) {
281 QSqlDatabase db = Database::instance().getConnection();
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();
290 bool YTUser::updateNotifyCount() {
291 QSqlDatabase db = Database::instance().getConnection();
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();
301 qWarning() << __PRETTY_FUNCTION__ << "Count failed";
304 int count = query.value(0).toInt();
305 storeNotifyCount(count);
306 return count != notifyCount;