File: telepathy-observer.vala

package info (click to toggle)
zeitgeist 0.9.14-2.2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 10,500 kB
  • ctags: 4,031
  • sloc: ansic: 16,835; sh: 11,484; xml: 8,822; python: 8,196; cpp: 2,970; sql: 1,192; makefile: 941
file content (525 lines) | stat: -rw-r--r-- 20,029 bytes parent folder | download | duplicates (5)
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*
 * Zeitgeist
 *
 * Copyright (C) 2012 Collabora Ltd.
 *               Authored by: Seif Lotfy <seif.lotfy@collabora.co.uk>
 * Copyright (C) 2012 Eslam Mostafa <cseslam@gmail.com>
 *
 * This program 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, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

using Zeitgeist;
using TelepathyGLib;
using Json;

public class TelepathyObserver : DataProvider
{

  private const string actor = "dbus://org.freedesktop.Telepathy.Logger.service";
  private const string tp_account_path = "x-telepathy-account-path:%s";
  private const string tp_identifier = "x-telepathy-identifier:%s";
  private const string ft_json_domain = "http://zeitgeist-project.com/1.0/telepathy/filetransfer";
  private const string call_json_domain = "http://zeitgeist-project.com/1.0/telepathy/call";

  private TelepathyGLib.DBusDaemon dbus = null;
  private TelepathyGLib.AutomaticClientFactory factory = null;
  private TelepathyGLib.SimpleObserver observer = null;
  private HashTable<string, Timer> call_timers = null;

  public TelepathyObserver (DataHub datahub) throws GLib.Error
  {
    GLib.Object (unique_id: "com.zeitgeist-project,datahub,telepathy-observer",
                 name: "Telepathy Observer",
                 description: "Logs IM, call and filetransfer from telepathy",
                 datahub: datahub);
  }

  construct
  {
    call_timers = new HashTable<string, Timer> (str_hash, str_equal);
    try {
      dbus = TelepathyGLib.DBusDaemon.dup ();
    }
    catch (GLib.Error err)
    {
      warning ("Couldn't dup DBusDaemon: %s", err.message);
      return;
    }
    factory = new TelepathyGLib.AutomaticClientFactory (dbus);

    Quark[] channel_quark = {TelepathyGLib.Channel.get_feature_quark_contacts ()};
    TelepathyGLib.ContactFeature[] contact_quark = {TelepathyGLib.ContactFeature.ALIAS};

    factory.add_channel_features (channel_quark);
    factory.add_contact_features (contact_quark);
  }

  // if vala didn't have bug in construct-only properties, the properties
  // would be construct-only
  public override string unique_id { get; construct set; }
  public override string name { get; construct set; }
  public override string description { get; construct set; }

  public override DataHub datahub { get; construct set; }
  public override bool enabled { get; set; default = true; }
  public override bool register { get; construct set; default = true; }

  private void push_event (Event event)
  {
    GenericArray<Event> events = new GenericArray<Event> ();
    events.add (event);
    items_available (events);
  }

  /*
   * Create a standard template for text channel based events
   */
  private Event create_text_event (Account account, Channel channel)
  {
    var target = channel.get_target_contact ();
    var obj_path = account.get_object_path ();
    obj_path = tp_account_path.printf(obj_path[
      TelepathyGLib.ACCOUNT_OBJECT_PATH_BASE.length : obj_path.length]);
    Event event_template = new Event.full (
                              ZG.ACCESS_EVENT,
                              "",
                              actor,
                              null,
                              obj_path);

    /*
     * Whether user initiated the chat or not
     */
    if (!channel.requested)
      event_template.manifestation = ZG.WORLD_ACTIVITY;
    else
      event_template.manifestation = ZG.USER_ACTIVITY;

    /*
     * Create IM subject for the event
     */
    event_template.add_subject (
      new Subject.full (
        "",
        NMO.IMMESSAGE,
        NFO.SOFTWARE_SERVICE,
        "plain/text",
        tp_identifier.printf (target.get_identifier ()),
        "",
        "net")
      );

    /*
     * Create Contact subject for the event
     */
    event_template.add_subject (
      new Subject.full (
        tp_identifier.printf (target.get_identifier ()),
        NCO.CONTACT,
        NCO.CONTACT_LIST_DATA_OBJECT,
        "",
        obj_path,
        target.get_alias (),
        "net")
    );
    return event_template;
  }

  private void observe_text_channel (SimpleObserver observer, Account account,
                                 Connection connection, Channel b_channel,
                                 ChannelDispatchOperation? dispatch_operation,
                                 List<ChannelRequest> requests,
                                 ObserveChannelsContext context)
  {
    /*
     * Channel has been created
     */
    TextChannel channel = (TextChannel) b_channel;
    var target = channel.get_target_contact ();
    if (target != null)
    {
      /*
       * Create an event representing conversation start
       */
      var event_template = this.create_text_event (account, channel);
      this.push_event (event_template);
      /*
       * Process pending messages
       */
      foreach (var message in channel.get_pending_messages ())
      {
        if (!message.is_delivery_report ())
        {
          event_template = this.create_text_event (account, channel);
          event_template.interpretation = ZG.RECEIVE_EVENT;
          event_template.manifestation = ZG.WORLD_ACTIVITY;
          this.push_event (event_template);
        }
        // FIXME: what about sent messages? what happens with them?
      }
      /*
       * Connect to the signal representing conversation end
       */
      channel.invalidated.connect (() => {
        event_template = this.create_text_event (account, channel);
        // manifestation depends on the chat creator, unless we can
        // get a better value.
        event_template.interpretation = ZG.LEAVE_EVENT;
        this.push_event (event_template);
      });
      /*
       * Connect to receive message signals of the channel
       */
      channel.message_received.connect (() => {
        event_template = this.create_text_event (account, channel);
        event_template.interpretation = ZG.RECEIVE_EVENT;
        event_template.manifestation = ZG.WORLD_ACTIVITY;
        this.push_event (event_template);
      });
      /*
       * Connect to send message signals of the channel
       */
      channel.message_sent.connect (() => {
        event_template = this.create_text_event (account, channel);
        event_template.interpretation = ZG.SEND_EVENT;
        event_template.manifestation = ZG.USER_ACTIVITY;
        this.push_event (event_template);
      });
    }
  }

  /*
   * Create a standard template for call channel based events
   */
  private Event? create_call_event (Account account, CallChannel channel)
  {
    var targets = channel.get_members ();
    if (targets == null)
      return null;
    weak TelepathyGLib.Contact? target = targets.get_keys ().data;

    var obj_path = account.get_object_path ();
    obj_path = tp_account_path.printf(obj_path[
      TelepathyGLib.ACCOUNT_OBJECT_PATH_BASE.length : obj_path.length]);
    Event event_template = new Event.full (
                              ZG.ACCESS_EVENT,
                              ZG.USER_ACTIVITY,
                              actor,
                              null,
                              obj_path);
    if (!channel.requested)
      event_template.manifestation = ZG.WORLD_ACTIVITY;
    /*
     * Create Call subject for the event
     */
    event_template.add_subject (
      new Subject.full (
        "",
        NFO.AUDIO,
        NFO.MEDIA_STREAM,
        "x-telepathy/call",
        tp_identifier.printf (target.get_identifier ()),
        target.get_alias (),
        "net")
    );
    /*
     * Create Contact subject for the event
     */
    event_template.add_subject (
      new Subject.full (
        tp_identifier.printf(target.get_identifier ()),
        NCO.CONTACT,
        NCO.CONTACT_LIST_DATA_OBJECT,
        "",
        obj_path,
        target.get_alias (),
        "net")
    );
    return event_template;
  }

  private void observe_call_channel (SimpleObserver observer, Account account,
                                     Connection connection, Channel b_channel,
                                     ChannelDispatchOperation? dispatch_operation,
                                     List<ChannelRequest> requests,
                                     ObserveChannelsContext context)
  {
    CallChannel channel = (CallChannel) b_channel;

    channel.state_changed.connect (() =>
      {
        CallFlags flags;
        TelepathyGLib.CallStateReason reason;
        CallState state = channel.get_state (out flags, null, out reason);

        /*
         * Create an Event template for call events
         */
        var event_template = this.create_call_event (account, channel);

        /*
         * Start operating once the call state is initialized
         */
        if (state == TelepathyGLib.CallState.INITIALISED)
        {
          event_template.interpretation = ZG.CREATE_EVENT;
          Timer t = new Timer ();
          t.stop ();
          call_timers.insert (channel.get_object_path (), (owned) t);
          this.push_event (event_template);
        }
        /*
         * Act only on call active or call end
         */
        else if ((state == TelepathyGLib.CallState.ACTIVE || state == TelepathyGLib.CallState.ENDED)
                  && call_timers.contains (channel.get_object_path ()))
        {
          if (state == TelepathyGLib.CallState.ACTIVE)
          {
            event_template.interpretation = ZG.ACCESS_EVENT;
            call_timers.lookup (channel.get_object_path ()).start();
            this.push_event (event_template);
          }
          else if (state == TelepathyGLib.CallState.ENDED)
          {
            event_template.interpretation = ZG.LEAVE_EVENT;

            /* Call was created by user but was rejected or not answered */
            if (reason.reason == TelepathyGLib.CallStateChangeReason.REJECTED
                || reason.reason == TelepathyGLib.CallStateChangeReason.NO_ANSWER)
            {
              if (channel.requested)
                event_template.manifestation = ZG.WORLD_ACTIVITY;
              else
                event_template.interpretation = ZG.USER_ACTIVITY;

              if (reason.reason == TelepathyGLib.CallStateChangeReason.NO_ANSWER)
                event_template.interpretation = ZG.EXPIRE_EVENT;
              else
                event_template.interpretation = ZG.DENY_EVENT;
            }

            var duration  = call_timers.lookup (channel.get_object_path ()).elapsed ();
            call_timers.lookup (channel.get_object_path ()).stop;
            call_timers.remove (channel.get_object_path ());
            /*
             * Create JSON payload representing the call metadata including
             * duration and termination reasons of the call.
             */
            var gen = new Generator();
            var root = new Json.Node(NodeType.OBJECT);
            var object = new Json.Object();
            root.set_object(object);
            gen.set_root(root);
            gen.pretty = true;

            var details_obj = new Json.Object ();
            details_obj.set_int_member ("state", state);
            details_obj.set_int_member ("reason", reason.reason);
            details_obj.set_boolean_member ("requested", channel.requested);
            details_obj.set_double_member ("duration", duration);
            size_t length;
            object.set_object_member (call_json_domain, details_obj);
            string payload_string = gen.to_data(out length);
            event_template.payload = new GLib.ByteArray.take (payload_string.data);
            this.push_event (event_template);
          }
        }
      });
  }

  private async void handle_ftchannel_change (SimpleObserver observer,
                                              Account account,
                                              Connection connection,
                                              FileTransferChannel channel,
                                              ChannelDispatchOperation? dispatch_operation,
                                              List<ChannelRequest> requests,
                                              ObserveChannelsContext context)
  {
    if (channel.state == TelepathyGLib.FileTransferState.COMPLETED
        || channel.state == TelepathyGLib.FileTransferState.CANCELLED)
      {
        var target = channel.get_target_contact ();
        var attr = "%s, %s, %s".printf (FileAttribute.STANDARD_DISPLAY_NAME,
          FileAttribute.STANDARD_CONTENT_TYPE, FileAttribute.STANDARD_SIZE);
        FileInfo info = null;
        try
        {
          info = yield channel.file.query_info_async (attr, 0);
        }
        catch (GLib.Error err)
        {
          warning ("Couldn't process %s: %s", channel.file.get_path (), err.message);
          return;
        }
        var obj_path = account.get_object_path ();
        obj_path = tp_account_path.printf("%s",
                   obj_path [TelepathyGLib.ACCOUNT_OBJECT_PATH_BASE.length:
                   obj_path.length]);
        /* Create Event template */
        var event_template = new Event ();
        if (channel.requested)
        {
          event_template.interpretation = ZG.SEND_EVENT;
          event_template.manifestation = ZG.USER_ACTIVITY;
        }
        else
        {
          event_template.interpretation = ZG.RECEIVE_EVENT;
          event_template.manifestation = ZG.WORLD_ACTIVITY;
        }
        event_template.actor = actor;
        /*
         * Create Subject representing the sent/received file
         */
        var subj = new Subject ();
        subj.uri = channel.file.get_uri ();
        subj.interpretation = interpretation_for_mimetype (info.get_content_type ());
        subj.manifestation = NFO.FILE_DATA_OBJECT;
        subj.text = info.get_display_name ();
        subj.mimetype = info.get_content_type ();
        if (channel.requested == true)
        {
          var split_uri = channel.file.get_uri ().split ("/");
          var uri = "%s/".printf(string.join ("/", split_uri[0:split_uri.length-1]));
          subj.origin = uri;
        }
        else
          subj.origin = tp_identifier.printf (target.get_identifier ());
        event_template.add_subject (subj);

        /*
         * Create Subject representing contact received from or sent to
         */
        event_template.add_subject (
          new Subject.full (tp_identifier.printf(target.get_identifier ()),
            NCO.CONTACT,
            NCO.CONTACT_LIST_DATA_OBJECT,
            "",
            obj_path,
            target.get_alias (),
            "net"));
        /*
         * Create Payload
         */
        var gen = new Generator();
        var root = new Json.Node(NodeType.OBJECT);
        var object = new Json.Object();
        root.set_object(object);
        gen.set_root(root);
        gen.pretty = true;
        var details_obj = new Json.Object ();
        TelepathyGLib.FileTransferStateChangeReason reason;
        var state = channel.get_state (out reason);
        details_obj.set_int_member ("state", state);
        details_obj.set_int_member ("reason", reason);
        details_obj.set_boolean_member ("requested", channel.requested);
        details_obj.set_string_member ("description", channel.get_description ());
        details_obj.set_double_member ("size", (int64)channel.get_size ());
        details_obj.set_string_member ("service", channel.get_service_name ());
        size_t length;
        object.set_object_member (ft_json_domain, details_obj);
        string payload_string = gen.to_data (out length);
        event_template.payload = new GLib.ByteArray.take (payload_string.data);
        this.push_event (event_template);
      }
  }

  private void observe_ft_channel (SimpleObserver observer, Account account,
                                   Connection connection, Channel b_channel,
                                   ChannelDispatchOperation? dispatch_operation,
                                   List<ChannelRequest> requests,
                                   ObserveChannelsContext context)
  {
    FileTransferChannel channel = (FileTransferChannel) b_channel;
    channel.notify["state"].connect (() => {
        this.handle_ftchannel_change.begin (observer, account, connection, channel,
          dispatch_operation, requests, context);
      });
  }

  private void observe_channels (SimpleObserver observer, Account account,
                                 Connection connection, List<Channel> channels,
                                 ChannelDispatchOperation? dispatch_operation,
                                 List<ChannelRequest> requests,
                                 ObserveChannelsContext context)
  {
    try
    {
      foreach (var channel in channels)
      {
        if (channel is TelepathyGLib.TextChannel)
          this.observe_text_channel (observer, account, connection, channel,
                            dispatch_operation, requests, context);
        else if (channel is TelepathyGLib.CallChannel)
          this.observe_call_channel (observer, account, connection, channel,
                            dispatch_operation, requests, context);
        else if (channel is TelepathyGLib.FileTransferChannel)
          this.observe_ft_channel (observer, account, connection, channel,
                            dispatch_operation, requests, context);
      }
    }
    finally
    {
      context.accept ();
    }
  }

  public override void start ()
  {
    observer = new TelepathyGLib.SimpleObserver.with_factory (factory,
                                                              true,
                                                              "Zeitgeist",
                                                              false,
                                                              observe_channels);
    /*
     * Add Call Channel Filters
     */
    HashTable<string,Value?> call_filter = new HashTable<string,Value?> (str_hash, str_equal);
    call_filter.insert (TelepathyGLib.PROP_CHANNEL_CHANNEL_TYPE,
                        TelepathyGLib.IFACE_CHANNEL_TYPE_CALL);
    call_filter.insert (TelepathyGLib.PROP_CHANNEL_TARGET_HANDLE_TYPE, 1); // 1 => TP_HANDLE_TYPE_CONTACT, somehow vala fails to compile when using the constant
    observer.add_observer_filter (call_filter);
    /*
     * Add Text Channel Filters
     */
    HashTable<string,Value?> text_filter = new HashTable<string,Value?> (str_hash, str_equal);
    text_filter.insert (TelepathyGLib.PROP_CHANNEL_CHANNEL_TYPE,
                        TelepathyGLib.IFACE_CHANNEL_TYPE_TEXT);
    text_filter.insert (TelepathyGLib.PROP_CHANNEL_TARGET_HANDLE_TYPE, 1); // 1 => TP_HANDLE_TYPE_CONTACT, somehow vala fails to compile when using the constant
    observer.add_observer_filter (text_filter);
    /*
     * Add FileTransfer Channel Filters
     */
    HashTable<string,Value?> ft_filter = new HashTable<string,Value?> (str_hash, str_equal);
    ft_filter.insert (TelepathyGLib.PROP_CHANNEL_CHANNEL_TYPE,
                      TelepathyGLib.IFACE_CHANNEL_TYPE_FILE_TRANSFER);
    ft_filter.insert (TelepathyGLib.PROP_CHANNEL_TARGET_HANDLE_TYPE, 1); // 1 => TP_HANDLE_TYPE_CONTACT, somehow vala fails to compile when using the constant
    observer.add_observer_filter (ft_filter);
    try
    {
      observer.register ();
    }
    catch (GLib.Error err)
    {
      warning ("Couldn't register observer: %s", err.message);
    }
  }

  public override void stop ()
  {
    observer.unregister ();
  }
}