summaryrefslogtreecommitdiff
path: root/telepathy/zeitgeist-telepathy-observer
blob: 623dce3add26d0918c1785b5eb9bea616ab24ee8 (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
#!/usr/bin/env python

# Copyright (C) 2012 Collabora Ltd
# Copyright (C) 2012 Intel Corporation
#
# 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; either
# version 2 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., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# Written by: Seif Lotfy <seif.lotfy@collabora.co.uk>

from gi.repository import TelepathyGLib as Tp
from gi.repository import GObject, Gio
from zeitgeist.client import ZeitgeistClient
from zeitgeist.datamodel import Event, Subject, Interpretation, Manifestation
from zeitgeist.mimetypes import get_interpretation_for_mimetype

import json

GObject.threads_init ()

ZG_ACTOR = "dbus://org.freedesktop.Telepathy.Logger.service"
TP_ACCOUNT_PATH = "x-telepathy-account-path:%s"
TP_IDENTIFIER = "x-telepathy-identifier:%s"

dbus = Tp.DBusDaemon.dup ()
zg_client = ZeitgeistClient ()

def callback (ids):
    print ids
  
def error_handler (error):
    print error

def create_event (account, channel):
    target = channel.get_target_contact ()
    event_template = Event.new_for_values (
        actor = ZG_ACTOR,
        interpretation = Interpretation.ACCESS_EVENT,
        manifestation = Manifestation.USER_ACTIVITY \
            if channel.get_properties ("requested") else Manifestation.WORLD_ACTIVITY,
        origin = TP_ACCOUNT_PATH % account.get_object_path ()[len (Tp.ACCOUNT_OBJECT_PATH_BASE):])
    event_template.subjects.append (
        Subject.new_for_values (
            uri = "",
            interpretation = Interpretation.IMMESSAGE,
            manifestation = Manifestation.SOFTWARE_SERVICE,
            mimetype = "plain/text",
            origin = TP_IDENTIFIER % target.get_identifier (),
            text = target.get_alias (),
            storage = "net"))
    event_template.subjects.append (
        Subject.new_for_values (
            uri = TP_IDENTIFIER % target.get_identifier (),
            interpretation = Interpretation.CONTACT,
            manifestation = Manifestation.CONTACT_LIST_DATA_OBJECT,
            origin = TP_IDENTIFIER % target.get_identifier (),
            text = target.get_alias (),
            storage = "net"))
    return event_template

def print_channel (event):
    print "Event:"
    print "    - timestamp:", event.timestamp
    print "    - actor", event.actor
    print "    - interpretation:", event.interpretation
    print "    - manifestation:", event.manifestation
    print "    - origin:", event.origin
    print "    - subjects:", len (event.subjects)
    for i, subject in enumerate (event.subjects):
        print "            - subject %i:" % (i+1)
        print "                 - uri:", subject.uri
        print "                 - interpretation:", subject.interpretation
        print "                 - manifestation:", subject.manifestation
        print "                 - mimetype:", subject.mimetype
        print "                 - origin:", subject.origin
        print "                 - text:", subject.text
        print "                 - storage:", subject.storage
    print "    -payload:", event.payload
    zg_client.insert_events ([event], callback, error_handler)

"""
Handling of text based events
"""

def msg_recv_callback (channel, message, account):
    if message.is_delivery_report ():
        return
    print "=== RECEIVED MSG ==="
    event_template = create_event (account, channel)
    event_template.interpretation = Interpretation.RECEIVE_EVENT
    event_template.manifestation = Manifestation.WORLD_ACTIVITY
    print_channel (event_template)

def msg_sent_callback (channel, message, flags, token, account):
    print "=== SENT MSG ==="
    event_template = create_event (account, channel)
    event_template.interpretation = Interpretation.SEND_EVENT
    event_template.manifestation = Manifestation.USER_ACTIVITY
    print_channel (event_template)

def channel_closed_callback (channel, domain, code, message, account):
    print "=== CLOSED CHANNEL ==="
    event_template = create_event (account, channel)
    event_template.interpretation = Interpretation.LEAVE_EVENT
    print_channel (event_template)

def observe_textchannel (observer, account, connection, channel,
                         dispatch_op, requests, context, user_data):
    target = channel.get_target_contact ()
    if target:
      event_template = create_event (account, channel)
      print "=== CREATED CHANNEL ==="
      print_channel (event_template)
      for message in channel.get_pending_messages ():
          msg_recv_callback (channel, message, account)
          event_template = create_event (account, channel)
      channel.connect ('invalidated', channel_closed_callback, account)
      channel.connect ('message-received', msg_recv_callback, account)
      channel.connect ('message-sent', msg_sent_callback, account)


"""
Handling of call based events
"""

call_timers = {}

def create_call_event (account, channel):
    targets = channel.get_members ()
    if not targets:
        return
    event_template = Event.new_for_values (
        actor = ZG_ACTOR,
        interpretation = Interpretation.ACCESS_EVENT,
        manifestation = Manifestation.USER_ACTIVITY \
            if channel.get_property ("requested") else Manifestation.WORLD_ACTIVITY,
        origin = TP_ACCOUNT_PATH % account.get_object_path ()[len (Tp.ACCOUNT_OBJECT_PATH_BASE):])
    for i, target in enumerate (targets):
        if i == 0:
            event_template.subjects.append (
                Subject.new_for_values (
                    uri = "",
                    interpretation = Interpretation.MEDIA.AUDIO,
                    manifestation = Manifestation.MEDIA_STREAM,
                    mimetype = "x-telepathy/call",
                    origin = TP_IDENTIFIER % target.get_identifier (),
                    text = target.get_alias (),
                    storage = "net"))
            event_template.subjects.append (
                Subject.new_for_values (
                    uri = TP_IDENTIFIER % target.get_identifier (),
                    interpretation = Interpretation.CONTACT,
                    manifestation = Manifestation.CONTACT_LIST_DATA_OBJECT,
                    origin = TP_IDENTIFIER % target.get_identifier (),
                    text = target.get_alias (),
                    storage = "net"))
    return event_template


def call_state_changed (channel, state, flags, reason, details, account):
    #FIXME: Something breaks this
    made_by_user = False
    if reason.actor == channel.get_property ("connection").get_self_handle ():
        made_by_user = True
    #print "User Data:", user_data
    #print "Event Template: ", event_template
    if state in (3, 5, 6):
        event_template = create_call_event (account, channel)
        event_template.manifestation = Manifestation.USER_ACTIVITY if made_by_user \
            else Manifestation.WORLD_ACTIVITY

        if state == Tp.CallState.INITIALISED:
            event_template.interpretation = Interpretation.CREATE_EVENT
            call_timers[channel] = 0
            print_channel (event_template)

        elif state == Tp.CallState.ACTIVE:
            event_template.interpretation = Interpretation.ACCESS_EVENT
            call_timers[channel] = int (event_template.timestamp)
            print_channel (event_template)

        elif state == Tp.CallState.ENDED:
            if call_timers.has_key (channel):
                event_template.interpretation = Interpretation.LEAVE_EVENT
                if reason.reason.numerator == Tp.CallStateChangeReason.REJECTED:
                    event_template.interpretation = Interpretation.DENY_EVENT 
                elif reason.reason.numerator == Tp.CallStateChangeReason.NO_ANSWER:
                    event_template.interpretation = Interpretation.EXPIRE_EVENT 
                    
                duration = 0 if not call_timers.has_key (channel) \
                    else int (event_template.timestamp) - call_timers[channel]
                details = {"http://zeitgeist-project.com/1.0/telepathy/call": {
                    "state": channel.get_state ()[0].numerator,
                    "reason": channel.get_state ()[1].numerator,
                    "requested": channel.get_property ("requested"),
                    "host": TP_ACCOUNT_PATH % account.get_object_path ()[len (Tp.ACCOUNT_OBJECT_PATH_BASE):] \
                        if channel.get_property ("requested") else event_template.subjects[1].uri,
                    "receiver": TP_IDENTIFIER % event_template.subjects[1].uri \
                        if channel.get_property ("requested") \
                        else TP_ACCOUNT_PATH % account.get_object_path ()[len (Tp.ACCOUNT_OBJECT_PATH_BASE):],
                    "duration": duration
                    }}
                details = json.dumps (details)
                event_template.payload = details.encode ("utf-8")
                del call_timers[channel]
                print_channel (event_template)

def observe_callchannel (observer, account, connection, channel,
                         dispatch_op, requests, context, user_data):
    if channel.get_state () == Tp.CallState.INITIALISED:
        event_template.interpretation = Interpretation.CREATE_EVENT
        call_timers[channel] = 0
        print_channel (event_template)
    channel.connect ("state-changed", call_state_changed, account)


"""
Handling of file transfer based events
"""

def ft_state_changed (channel, state, account):
    state = channel.get_state ()[0]
    target = channel.get_target_contact ()
    print state, ZG_ACTOR
    if state in (4,5):
        # get attributes of the file being sent or received
        attr = (Gio.FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
            Gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
            Gio.FILE_ATTRIBUTE_STANDARD_SIZE )
        info = channel.get_property ("file").query_info (",".join (attr),
        Gio.FileQueryInfoFlags.NONE, None)
    # setup new event to be sent to zeitgeist
    event = Event.new_for_values (
        interpretation = Interpretation.SEND_EVENT \
            if channel.get_property ("requested") else Interpretation.RECEIVE_EVENT,
        manifestation = Manifestation.USER_ACTIVITY \
            if channel.get_property ("requested") else Manifestation.WORLD_ACTIVITY,
        actor = ZG_ACTOR,
        origin = TP_ACCOUNT_PATH % account.get_object_path ()[35:])
    subject = Subject.new_for_values (
        uri = channel.get_property ("file").get_uri (),
        interpretation =  get_interpretation_for_mimetype (info.get_content_type ()),
        manifestation = Manifestation.FILE_DATA_OBJECT \
            if channel.get_property ("requested") else Manifestation.FILE_DATA_OBJECT.REMOTE_DATA_OBJECT,
        text = info.get_display_name (),
        mimetype = info.get_content_type (),
        origin = "/".join (channel.get_property ("file").get_uri ().split ("/")[:-1])+"/" \
            if channel.get_property ("requested") else TP_IDENTIFIER % target.get_identifier ())
    event.subjects.append (subject)
    subject = Subject.new_for_values (
        uri = TP_IDENTIFIER % target.get_identifier (),
        interpretation = Interpretation.CONTACT.PERSON_CONTACT,
        manifestation = Manifestation.CONTACT_LIST_DATA_OBJECT,
        origin = TP_IDENTIFIER % target.get_identifier (),
        text = target.get_alias (),
        storage = "net")
    event.subjects.append (subject)
    details = {"http://zeitgeist-project.com/1.0/telepathy/filetransfer": {
        "state": channel.get_state ()[0].numerator,
        "reason": channel.get_state ()[1].numerator,
        "requested": channel.get_property ("requested"),
        "sender": TP_ACCOUNT_PATH % account.get_object_path ()[35:] \
            if channel.get_property ("requested") else TP_IDENTIFIER % target.get_identifier (),
        "receiver": TP_IDENTIFIER % target.get_identifier () \
            if channel.get_property ("requested") else TP_ACCOUNT_PATH % account.get_object_path ()[35:],
        "mimetype": info.get_content_type (),
        "date": channel.get_date ().to_unix (),
        "description": channel.get_description (),
        "size": channel.get_size (),
        "service": channel.get_service_name (),
        "uri": channel.get_property ("file").get_uri ()
        }}
    details = json.dumps (details)
    event.payload = details.encode ("utf-8")
    print_channel (event)

def observe_ftchannel (observer, account, connection, channel,
                     dispatch_op, requests, context, user_data):
    channel.connect ("notify::state", ft_state_changed, account)

"""
Set up observer
"""

def observe_channels (observer, account, connection, channels,
                     dispatch_op, requests, context, user_data):
    try:
      for channel in channels:
        args = (observer, account, connection, channel,
            dispatch_op, requests, context, user_data)
        if isinstance(channel, Tp.TextChannel):
          observe_textchannel (*args)
        elif isinstance(channel, Tp.CallChannel):
          observe_callchannel (*args)
        elif isinstance(channel, Tp.FTChannel):
          observe_ftchannel (*args)
    finally:
        context.accept ()


factory = Tp.AutomaticClientFactory.new (dbus)
factory.add_channel_features ([Tp.Channel.get_feature_quark_contacts ()])
factory.add_contact_features ([Tp.ContactFeature.ALIAS])

observer = Tp.SimpleObserver.new_with_factory (factory, True,
    'Zeitgeist', False, observe_channels, None)

# Add call observer properties
observer.add_observer_filter ({
    Tp.PROP_CHANNEL_CHANNEL_TYPE: Tp.IFACE_CHANNEL_TYPE_CALL,
    Tp.PROP_CHANNEL_TARGET_HANDLE_TYPE: int (Tp.HandleType.CONTACT),
})

# Add text observer properties
observer.add_observer_filter ({
    Tp.PROP_CHANNEL_CHANNEL_TYPE: Tp.IFACE_CHANNEL_TYPE_TEXT,
    Tp.PROP_CHANNEL_TARGET_HANDLE_TYPE: int (Tp.HandleType.CONTACT),
})

# Add filetransfer observer properties
observer.add_observer_filter ({
    Tp.PROP_CHANNEL_CHANNEL_TYPE: Tp.IFACE_CHANNEL_TYPE_FILE_TRANSFER,
})

observer.register ()

"""
Start the mainloop
"""

main_loop = GObject.MainLoop ()
main_loop.run ()