Added the ability to mark and unmark favorites from post capture page
[harmattan/cameraplus] / src / postcapturemodel.cpp
1 /*!
2  * This file is part of CameraPlus.
3  *
4  * Copyright (C) 2012 Mohammed Sameer <msameer@foolab.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19  */
20
21 #include "postcapturemodel.h"
22 #include <QSparqlConnection>
23 #include <QSparqlQuery>
24 #include <QSparqlResult>
25 #include <QSparqlError>
26 #include <QDeclarativeInfo>
27 #include <QDateTime>
28 #include <QDBusConnection>
29 #include <QStringList>
30 #include <QDBusMetaType>
31 #include <QDBusArgument>
32
33 #define DRIVER "QTRACKER_DIRECT"
34 #define QUERY "SELECT rdf:type(?urn) AS ?type nie:url(?urn) AS ?url nie:contentCreated(?urn) AS ?created nie:title(?urn) AS ?title nfo:fileName(?urn) AS ?filename nie:mimeType(?urn) AS ?mimetype tracker:available(?urn) AS ?available nfo:fileLastModified(?urn) as ?lastmod tracker:id(?urn) AS ?trackerid (EXISTS { ?urn nao:hasTag nao:predefined-tag-favorite }) AS ?favorite WHERE { ?urn nfo:equipment ?:equipment . {?urn a nfo:Video} UNION {?urn a nfo:Image}} ORDER BY DESC(?created)"
35
36 #define UPDATE_QUERY "SELECT rdf:type(?urn) AS ?type nie:url(?urn) AS ?url nie:contentCreated(?urn) AS ?created nie:title(?urn) AS ?title nfo:fileName(?urn) AS ?filename nie:mimeType(?urn) AS ?mimetype tracker:available(?urn) AS ?available nfo:fileLastModified(?urn) as ?lastmod tracker:id(?urn) AS ?trackerid (EXISTS { ?urn nao:hasTag nao:predefined-tag-favorite }) AS ?favorite WHERE {?urn a nfo:Visual . FILTER (tracker:id(?urn) IN (%1)) }"
37
38 #define TRACKER_SERVICE "org.freedesktop.Tracker1"
39 #define TRACKER_RESOURCE_PATH "/org/freedesktop/Tracker1/Resources"
40 #define TRACKER_RESOURCE_INTERFACE "org.freedesktop.Tracker1.Resources"
41 #define TRACKER_RESOURCE_SIGNAL "GraphUpdated"
42 #define PHOTO_CLASS "http://www.tracker-project.org/temp/nmm#Photo"
43 #define VIDEO_CLASS "http://www.tracker-project.org/temp/nmm#Video"
44 #define TRACKER_RESOURCE_SIGNAL_SIGNATURE "sa(iiii)a(iiii)"
45
46 class Quad {
47 public:
48   int graph;
49   int subject;
50   int predicate;
51   int object;
52 };
53
54 Q_DECLARE_METATYPE(Quad);
55 Q_DECLARE_METATYPE(QList<Quad>);
56
57 QDBusArgument& operator<<(QDBusArgument& argument, const Quad& t) {
58   argument.beginStructure();
59   argument << t.graph << t.subject << t.predicate << t.object;
60   argument.endStructure();
61   return argument;
62 }
63
64 const QDBusArgument& operator>>(const QDBusArgument& argument, Quad& t) {
65   argument.beginStructure();
66   argument >> t.graph >> t.subject >> t.predicate >> t.object;
67   argument.endStructure();
68   return argument;
69 }
70
71 PostCaptureModel::PostCaptureModel(QObject *parent) :
72   QAbstractListModel(parent),
73   m_connection(0) {
74
75   QHash<int, QByteArray> roles;
76   roles.insert(Item, "item");
77   setRoleNames(roles);
78
79   qDBusRegisterMetaType<Quad>();
80   qDBusRegisterMetaType<QList<Quad> >();
81 }
82
83 PostCaptureModel::~PostCaptureModel() {
84   qDeleteAll(m_items);
85   m_items.clear();
86
87   delete m_connection; m_connection = 0;
88 }
89
90 void PostCaptureModel::classBegin() {
91
92 }
93
94 void PostCaptureModel::componentComplete() {
95
96 }
97
98 void PostCaptureModel::reload() {
99   delete m_connection; m_connection = 0;
100
101   if (!m_items.isEmpty()) {
102     beginRemoveRows(QModelIndex(), 0, m_items.size() - 1);
103     qDeleteAll(m_items);
104     m_items.clear();
105     endRemoveRows();
106   }
107
108   m_connection = new QSparqlConnection(DRIVER, QSparqlConnectionOptions(), this);
109   if (!m_connection->isValid()) {
110     emit error(tr("Failed to create SPARQL connection"));
111     return;
112   }
113
114   QString equipment = QString("urn:equipment:%1:%2:").arg(m_manufacturer).arg(m_model);
115
116   QSparqlQuery q(QUERY, QSparqlQuery::SelectStatement);
117   q.bindValue("equipment", equipment);
118   exec(q);
119
120   QDBusConnection::sessionBus().connect(TRACKER_SERVICE, TRACKER_RESOURCE_PATH,
121                                         TRACKER_RESOURCE_INTERFACE, TRACKER_RESOURCE_SIGNAL,
122                                         TRACKER_RESOURCE_SIGNAL_SIGNATURE,
123                                         this, SLOT(graphUpdated(const QString&,
124                                                                 const QList<Quad>&,
125                                                                 const QList<Quad>&)));
126 }
127
128 void PostCaptureModel::exec(QSparqlQuery& query) {
129   if (!m_connection) {
130     qWarning() << "No connection to query";
131     return;
132   }
133
134   QSparqlResult *result = m_connection->exec(query);
135
136   if (result->hasError()) {
137     QSparqlError error = result->lastError();
138     qmlInfo(this) << "Error executing SPARQL query" << error.message();
139
140     delete result;
141
142     emit PostCaptureModel::error(tr("Failed to query tracker"));
143   }
144
145   if (result) {
146     QObject::connect(result, SIGNAL(dataReady(int)), this, SLOT(dataReady(int)));
147     QObject::connect(result, SIGNAL(finished()), result, SLOT(deleteLater()));
148   }
149 }
150
151 int PostCaptureModel::rowCount(const QModelIndex& parent) const {
152   if (parent.isValid()) {
153     return 0;
154   }
155
156   return m_items.size();
157 }
158
159 QVariant PostCaptureModel::data(const QModelIndex& index, int role) const {
160   if (!index.isValid() || index.row() < 0 || index.row() >= m_items.size()) {
161     return QVariant();
162   }
163
164   if (role == Item) {
165     return QVariant::fromValue(dynamic_cast<QObject *>(m_items[index.row()]));
166   }
167
168   return QVariant();
169 }
170
171 QString PostCaptureModel::manufacturer() const {
172   return m_manufacturer;
173 }
174
175 void PostCaptureModel::setManufacturer(const QString& manufacturer) {
176   if (m_manufacturer != manufacturer) {
177     m_manufacturer = manufacturer;
178     emit manufacturerChanged();
179   }
180 }
181
182 QString PostCaptureModel::model() const {
183   return m_model;
184 }
185
186 void PostCaptureModel::setModel(const QString& model) {
187   if (m_model != model) {
188     m_model = model;
189     emit modelChanged();
190   }
191 }
192
193 void PostCaptureModel::dataReady(int totalCount) {
194   Q_UNUSED(totalCount);
195
196   QSparqlResult *result = dynamic_cast<QSparqlResult *>(sender());
197   if (!result) {
198     return;
199   }
200
201   while (result->next()) {
202     addRow(new PostCaptureModelItem(result->current(), this));
203   }
204
205   result->previous();
206 }
207
208 void PostCaptureModel::addRow(PostCaptureModelItem *item) {
209   if (m_hash.contains(item->trackerId())) {
210     m_hash[item->trackerId()]->update(item);
211     delete item;
212     return;
213   }
214
215   beginInsertRows(QModelIndex(), m_items.size(), m_items.size());
216   m_items << item;
217   m_hash.insert(item->trackerId(), item);
218
219   endInsertRows();
220 }
221
222 void PostCaptureModel::remove(QObject *item) {
223   PostCaptureModelItem *i = dynamic_cast<PostCaptureModelItem *>(item);
224   if (!i) {
225     qmlInfo(this) << "Invalid item to remove";
226     return;
227   }
228
229   int index = m_items.indexOf(i);
230   if (index == -1) {
231     qmlInfo(this) << "Item" << i->trackerId() << "not found in model";
232     return;
233   }
234
235   beginRemoveRows(QModelIndex(), index, index);
236   m_items.takeAt(index);
237   m_hash.remove(i->trackerId());
238   endRemoveRows();
239
240   i->deleteLater();
241 }
242
243 void PostCaptureModel::graphUpdated(const QString& className, const QList<Quad>& deleted,
244                                     const QList<Quad>& inserted) {
245
246   // We will just assume tracker:available has changed and that's it.
247   // We are not really interested in the rest of properties.
248
249   if (!(className == QLatin1String(PHOTO_CLASS) || className == QLatin1String(VIDEO_CLASS))) {
250     return;
251   }
252
253   QList<int> items;
254
255   for (int x = 0; x < deleted.size(); x++) {
256     Quad q = deleted[x];
257     if (m_hash.contains(q.subject) && items.indexOf(q.subject) == -1) {
258       items << q.subject;
259     }
260   }
261
262   for (int x = 0; x < inserted.size(); x++) {
263     Quad q = inserted[x];
264     if (m_hash.contains(q.subject) && items.indexOf(q.subject) == -1) {
265       items << q.subject;
266     }
267   }
268
269   for (int x = 0; x < items.size(); x++) {
270     QString query = QString(UPDATE_QUERY).arg(items[x]);
271     QSparqlQuery q(query, QSparqlQuery::SelectStatement);
272
273     exec(q);
274   }
275 }
276
277 PostCaptureModelItem::PostCaptureModelItem(const QSparqlResultRow& row, QObject *parent) :
278   QObject(parent) {
279
280   for (int x = 0; x < row.count(); x++) {
281     QSparqlBinding b = row.binding(x);
282     m_data.insert(b.name(), b.value());
283   }
284 }
285
286 QString PostCaptureModelItem::type() const {
287   return value("type").toString();
288 }
289
290 QUrl PostCaptureModelItem::url() const {
291   return value("url").toUrl();
292 }
293
294 QString PostCaptureModelItem::created() const {
295   return formatDateTime(value("created").toDateTime());
296 }
297
298 QString PostCaptureModelItem::title() const {
299   return value("title").toString();
300 }
301
302 QString PostCaptureModelItem::fileName() const {
303   return value("filename").toString();
304 }
305
306 QString PostCaptureModelItem::mimeType() const {
307   return value("mimetype").toString();
308 }
309
310 bool PostCaptureModelItem::available() const {
311   return value("available", false).toBool();
312 }
313
314 QString PostCaptureModelItem::lastModified() const {
315   return formatDateTime(value("lastmod").toDateTime());
316 }
317
318 unsigned PostCaptureModelItem::trackerId() const {
319   return value("trackerid").toUInt();
320 }
321
322 bool PostCaptureModelItem::favorite() const {
323   return value("favorite", false).toBool();
324 }
325
326 void PostCaptureModelItem::setFavorite(bool add) {
327   if (favorite() != add) {
328     m_data["favorite"] = add;
329
330     emit favoriteChanged();
331   }
332 }
333
334 QString PostCaptureModelItem::formatDateTime(const QDateTime& dt) const {
335   return dt.toString();
336 }
337
338 void PostCaptureModelItem::update(PostCaptureModelItem *other) {
339   // We will only update available, favorite and title:
340 #if 0
341   qDebug() << "i" << trackerId() << other->trackerId()  << "\n"
342            << "a" << available() << other->available() << "\n"
343            << "t" << title() << other->title() << "\n"
344            << "f" << favorite() << other->favorite();
345 #endif
346
347   if (available() != other->available()) {
348     m_data["available"] = other->available();
349     emit availableChanged();
350   }
351
352   if (title() != other->title()) {
353     m_data["title"] = other->title();
354     emit titleChanged();
355   }
356
357   if (favorite() != other->favorite()) {
358     m_data["favorite"] = other->favorite();
359     emit favoriteChanged();
360   }
361 }
362
363 QVariant PostCaptureModelItem::value(const QString& id, const QVariant& def) const {
364   return m_data.contains(id) ? m_data[id] : def;
365 }