summaryrefslogtreecommitdiff
path: root/src/tracker/grl-tracker-source-notif.c
blob: 4b35e0e502ab95cae25b199f644164f6034d3d30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*
 * Copyright (C) 2011-2012 Igalia S.L.
 * Copyright (C) 2011 Intel Corporation.
 * Copyright (C) 2015 Collabora Ltd.
 *
 * Contact: Iago Toral Quiroga <itoral@igalia.com>
 *
 * Authors: Lionel Landwerlin <lionel.g.landwerlin@linux.intel.com>
 *          Juan A. Suarez Romero <jasuarez@igalia.com>
 *          Xavier Claessens <xavier.claessens@collabora.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <tracker-sparql.h>

#include "grl-tracker.h"
#include "grl-tracker-source-notif.h"
#include "grl-tracker-source-priv.h"
#include "grl-tracker-utils.h"

#define GRL_LOG_DOMAIN_DEFAULT tracker_notif_log_domain
GRL_LOG_DOMAIN_STATIC(tracker_notif_log_domain);

#define GRL_TRACKER_TYPE_SOURCE_NOTIFY grl_tracker_source_notify_get_type ()
G_DECLARE_FINAL_TYPE (GrlTrackerSourceNotify, grl_tracker_source_notify, GRL_TRACKER, SOURCE_NOTIFY, GObject)

struct _GrlTrackerSourceNotify {
  GObject parent;

  GDBusConnection *conn;

  /* subject id -> GrlSourceChangeType */
  GHashTable *updates;
  /* Number of updates being queried */
  guint updates_count;
  /* subject id -> MediaInfo (NULL means it's being queried) */
  GHashTable *cache;

  guint graph_updated_id;
  gint rdf_type_id;
  gint nfo_filedataobject_id;
};

static void grl_tracker_source_notify_initable_iface_init (GInitableIface *iface);

G_DEFINE_TYPE_WITH_CODE (GrlTrackerSourceNotify, grl_tracker_source_notify, G_TYPE_OBJECT,
    G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, grl_tracker_source_notify_initable_iface_init))

static GrlTrackerSourceNotify *singleton = NULL;

typedef struct {
  gchar *type;
  gchar *datasource;
  gchar *url;
} MediaInfo;

static MediaInfo *
media_info_new (const gchar *type,
                const gchar *datasource,
                const gchar *url)
{
  MediaInfo *info;

  info = g_slice_new (MediaInfo);
  info->type = g_strdup (type);
  info->datasource = g_strdup (datasource);
  info->url = g_strdup (url);

  return info;
}

static void
media_info_free (MediaInfo *info)
{
  if (info == NULL)
    return;

  g_free (info->type);
  g_free (info->datasource);
  g_free (info->url);

  g_slice_free (MediaInfo, info);
}

static void
notify_change (GrlTrackerSourceNotify *self,
               gint                    id,
               GrlSourceChangeType     change_type)
{
  GrlTrackerSource *source = NULL;
  gchar *id_str = NULL;
  GrlMedia *media = NULL;
  MediaInfo *info;

  info = g_hash_table_lookup (self->cache, GINT_TO_POINTER (id));
  if (info == NULL)
    goto out;

  if (!grl_tracker_per_device_source)
    source = grl_tracker_source_find ("");

  if (!source && info->datasource)
    source = grl_tracker_source_find (info->datasource);

  if (!source || !GRL_IS_TRACKER_SOURCE (source) ||
      !grl_tracker_source_can_notify (source))
    goto out;

  id_str = g_strdup_printf ("%i", id);
  media = grl_tracker_build_grilo_media (info->type);
  grl_media_set_id (media, id_str);
  grl_media_set_url (media, info->url);

  GRL_DEBUG ("Notify: source=%s, change_type=%d, url=%s",
             grl_source_get_name (GRL_SOURCE (source)),
             change_type, info->url);

  grl_source_notify_change (GRL_SOURCE (source), media, change_type, FALSE);

out:
  if (change_type == GRL_CONTENT_REMOVED)
    g_hash_table_remove (self->cache, GINT_TO_POINTER (id));
  g_clear_object (&media);
  g_free (id_str);
}

static void
update_query_done (GrlTrackerSourceNotify *self)
{
  GHashTableIter iter;
  gpointer key, value;

  /* If more updates came while we were querying, wait for them so we can
   * aggregate notifications. */
  self->updates_count--;
  if (self->updates_count > 0)
    return;

  g_hash_table_iter_init (&iter, self->updates);
  while (g_hash_table_iter_next (&iter, &key, &value)) {
    gint id = GPOINTER_TO_INT (key);
    GrlSourceChangeType change_type = GPOINTER_TO_INT (value);

    notify_change (self, id, change_type);
  }

  g_hash_table_remove_all (self->updates);
}

static void
update_cursor_next_cb (GObject      *source_object,
                       GAsyncResult *result,
                       gpointer      user_data)
{
  GrlTrackerSourceNotify *self = user_data;
  TrackerSparqlCursor *cursor = (TrackerSparqlCursor *) source_object;
  const gchar *type;
  const gchar *datasource;
  const gchar *url;
  gint id;
  GError *error = NULL;

  if (!tracker_sparql_cursor_next_finish (cursor, result, &error)) {
    if (error != NULL) {
      GRL_WARNING ("Error: %s", error->message);
      g_clear_error (&error);
    }
    update_query_done (self);
    g_object_unref (self);
    return;
  }

  type = tracker_sparql_cursor_get_string (cursor, 0, NULL);
  id = tracker_sparql_cursor_get_integer (cursor, 1);
  datasource = tracker_sparql_cursor_get_string (cursor, 2, NULL);
  url = tracker_sparql_cursor_get_string (cursor, 3, NULL);

  g_hash_table_insert (self->cache,
                       GINT_TO_POINTER (id),
                       media_info_new (type, datasource, url));

  tracker_sparql_cursor_next_async (cursor,
                                    NULL,
                                    update_cursor_next_cb,
                                    self);
}

static void
update_query_cb (GObject      *source,
                 GAsyncResult *result,
                 gpointer      user_data)
{
  GrlTrackerSourceNotify *self = user_data;
  TrackerSparqlCursor *cursor;
  GError *error = NULL;

  cursor = tracker_sparql_connection_query_finish (grl_tracker_connection,
                                                   result,
                                                   &error);
  if (cursor == NULL) {
    if (error != NULL) {
      GRL_WARNING ("Error: %s", error->message);
      g_clear_error (&error);
    }
    update_query_done (self);
    g_object_unref (self);
    return;
  }

  tracker_sparql_cursor_next_async (cursor,
                                    NULL,
                                    update_cursor_next_cb,
                                    self);
}

#define CHANGED GINT_TO_POINTER (GRL_CONTENT_CHANGED)
#define ADDED   GINT_TO_POINTER (GRL_CONTENT_ADDED)
#define REMOVED GINT_TO_POINTER (GRL_CONTENT_REMOVED)

static void
graph_updated_cb (GDBusConnection *connection,
                  const gchar     *sender_name,
                  const gchar     *object_path,
                  const gchar     *interface_name,
                  const gchar     *signal_name,
                  GVariant        *parameters,
                  gpointer         user_data)

{
  GrlTrackerSourceNotify *self = user_data;
  const gchar *class_name;
  GVariantIter *iter1, *iter2;
  gint graph, subject, predicate, object;
  GString *query;

  g_variant_get (parameters, "(&sa(iiii)a(iiii))", &class_name, &iter1, &iter2);

  GRL_DEBUG ("Tracker update event for class=%s ins=%"G_GSIZE_FORMAT" del=%"G_GSIZE_FORMAT,
             class_name,
             g_variant_iter_n_children (iter2),
             g_variant_iter_n_children (iter1));

  query = g_string_new (NULL);

  /* DELETE */
  while (g_variant_iter_loop (iter1, "(iiii)", &graph, &subject, &predicate, &object)) {
    gpointer key = GINT_TO_POINTER (subject);

    /* If a rdf:type is removed, it probably means everything is going to be
     * removed. The media has been deleted. If some other property is deleted
     * it means the media already existed but changed.
     */

    if (predicate == self->rdf_type_id && object == self->nfo_filedataobject_id) {
      g_hash_table_insert (self->updates, key, REMOVED);
    } else if (g_hash_table_lookup (self->updates, key) != REMOVED) {
      g_hash_table_insert (self->updates, key, CHANGED);
    }
  }

  /* UPDATE */
  while (g_variant_iter_loop (iter2, "(iiii)", &graph, &subject, &predicate, &object)) {
    gpointer key = GINT_TO_POINTER (subject);

    /* If a rdf:type is added it means it's a new media, otherwise it's an
     * update of an existing media
     */

    if (predicate == self->rdf_type_id && object == self->nfo_filedataobject_id) {
      g_hash_table_insert (self->updates, key, ADDED);
    } else if (g_hash_table_lookup (self->updates, key) != ADDED) {
      g_hash_table_insert (self->updates, key, CHANGED);
    }

    /* If we don't yet have info about this subject query it and add NULL in
     * the table so we won't query it twice. */
    if (!g_hash_table_contains (self->cache, key)) {
      g_string_append_printf (query, "%d,", subject);
      g_hash_table_insert (self->cache, key, NULL);
    }
  }

  self->updates_count++;

  if (query->len > 0) {
    /* Remove trailing coma */
    g_string_truncate (query, query->len - 1);

    g_string_prepend (query,
      "SELECT rdf:type(?urn) tracker:id(?urn) nie:dataSource(?urn) nie:url(?urn) "
      "WHERE { ?urn a nfo:FileDataObject . "
      "FILTER (tracker:id(?urn) IN (");
    g_string_append (query, "))}");

    GRL_DEBUG ("Query: %s", query->str);
    tracker_sparql_connection_query_async (grl_tracker_connection,
                                           query->str,
                                           NULL,
                                           update_query_cb,
                                           g_object_ref (self));
  } else {
    update_query_done (self);
  }

  g_variant_iter_free (iter1);
  g_variant_iter_free (iter2);
  g_string_free (query, TRUE);
}

static gboolean
grl_tracker_source_notify_initable_init (GInitable    *initable,
                                         GCancellable *cancellable,
                                         GError      **error)
{
  GrlTrackerSourceNotify *self = GRL_TRACKER_SOURCE_NOTIFY (initable);
  TrackerSparqlCursor *cursor;

  self->conn = g_bus_get_sync (G_BUS_TYPE_SESSION, cancellable, error);
  if (self->conn == NULL)
    return FALSE;

  self->graph_updated_id = g_dbus_connection_signal_subscribe (
      self->conn,
      TRACKER_DBUS_SERVICE,
      TRACKER_DBUS_INTERFACE_RESOURCES,
      "GraphUpdated",
      TRACKER_DBUS_OBJECT_RESOURCES,
      NULL,
      G_DBUS_SIGNAL_FLAGS_NONE,
      graph_updated_cb,
      self, NULL);

  /* Query tracker to know the id of the rdf:type predicate so we can easily
   * identify them in graph_updated_cb(). */
  cursor = tracker_sparql_connection_query (grl_tracker_connection,
      "select tracker:id(rdf:type) tracker:id(nfo:FileDataObject) {}",
      NULL, error);
  if (cursor == NULL)
    return FALSE;

  if (!tracker_sparql_cursor_next (cursor, NULL, error)) {
    g_object_unref (cursor);
    return FALSE;
  }

  self->rdf_type_id = tracker_sparql_cursor_get_integer (cursor, 0);
  self->nfo_filedataobject_id = tracker_sparql_cursor_get_integer (cursor, 1);

  g_object_unref (cursor);

  return TRUE;
}

static void
grl_tracker_source_notify_finalize (GObject *object)
{
  GrlTrackerSourceNotify *self = GRL_TRACKER_SOURCE_NOTIFY (object);

  if (self->conn && self->graph_updated_id)
    g_dbus_connection_signal_unsubscribe (self->conn, self->graph_updated_id);

  g_clear_object (&self->conn);
  g_clear_pointer (&self->updates, g_hash_table_unref);
  g_clear_pointer (&self->cache, g_hash_table_unref);

  G_OBJECT_CLASS (grl_tracker_source_notify_parent_class)->finalize (object);
}

static void
grl_tracker_source_notify_class_init (GrlTrackerSourceNotifyClass *klass)
{
  GObjectClass *object_class = (GObjectClass *) klass;

  GRL_LOG_DOMAIN_INIT (tracker_notif_log_domain, "tracker-notif");
  object_class->finalize = grl_tracker_source_notify_finalize;
}

static void
grl_tracker_source_notify_init (GrlTrackerSourceNotify *self)
{
  self->updates = g_hash_table_new (NULL, NULL);
  self->cache = g_hash_table_new_full (NULL, NULL,
      NULL,
      (GDestroyNotify) media_info_free);
}

static void
grl_tracker_source_notify_initable_iface_init (GInitableIface *iface)
{
  iface->init = grl_tracker_source_notify_initable_init;
}

void
grl_tracker_source_dbus_start_watch (void)
{
  GError *error = NULL;

  if (singleton != NULL)
    return;

  singleton = g_initable_new (GRL_TRACKER_TYPE_SOURCE_NOTIFY, NULL, &error, NULL);
  if (singleton == NULL) {
    GRL_WARNING ("Error: %s", error->message);
    g_clear_error (&error);
  }
}

void
grl_tracker_source_dbus_stop_watch (void)
{
  g_clear_object (&singleton);
}