Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/services/presence/activity.py
blob: e9c3c05ce9dc920b93546c829aa678582c03abb1 (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
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
# Copyright (C) 2007, Red Hat, Inc.
# Copyright (C) 2007, Collabora Ltd.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import gobject
import dbus, dbus.service
from sugar import util
import logging

from telepathy.interfaces import (CHANNEL_INTERFACE)

_ACTIVITY_PATH = "/org/laptop/Sugar/Presence/Activities/"
_ACTIVITY_INTERFACE = "org.laptop.Sugar.Presence.Activity"

class DBusGObjectMetaclass(dbus.service.InterfaceType, gobject.GObjectMeta): pass
class DBusGObject(dbus.service.Object, gobject.GObject): __metaclass__ = DBusGObjectMetaclass


class Activity(DBusGObject):
    """Represents a potentially shareable activity on the network.
    """
    
    __gtype_name__ = "Activity"

    __gsignals__ = {
        'validity-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                            ([gobject.TYPE_BOOLEAN]))
    }

    __gproperties__ = {
        'id'     : (str, None, None, None,
                    gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT_ONLY),
        'name'   : (str, None, None, None, gobject.PARAM_READWRITE),
        'color'  : (str, None, None, None, gobject.PARAM_READWRITE),
        'type'   : (str, None, None, None, gobject.PARAM_READWRITE),
        'valid'  : (bool, None, None, False, gobject.PARAM_READABLE),
        'local'  : (bool, None, None, False,
                    gobject.PARAM_READWRITE | gobject.PARAM_CONSTRUCT_ONLY),
        'joined' : (bool, None, None, False, gobject.PARAM_READABLE)
    }

    def __init__(self, bus_name, object_id, tp, **kwargs):
        """Initializes the activity and sets its properties to default values.
        
        bus_name -- DBUS name for lookup on local host
        object_id -- The unique worldwide ID for this activity
        tp -- The server plugin object (stands for "telepathy plugin")
        kwargs -- Keyword arguments for the GObject properties
    
        """
        
        if not bus_name:
            raise ValueError("DBus bus name must be valid")
        if not object_id or not isinstance(object_id, int):
            raise ValueError("object id must be a valid number")
        if not tp:
            raise ValueError("telepathy CM must be valid")

        self._object_id = object_id
        self._object_path = _ACTIVITY_PATH + str(self._object_id)
        dbus.service.Object.__init__(self, bus_name, self._object_path)

        self._buddies = []
        self._joined = False

        # the telepathy client
        self._tp = tp
        self._text_channel = None

        self._valid = False
        self._id = None
        self._color = None
        self._local = False
        self._type = None

        if not kwargs.get("id"):
            raise ValueError("activity id is required")
        if not util.validate_activity_id(kwargs['id']):
            raise ValueError("Invalid activity id '%s'" % kwargs['id'])

        gobject.GObject.__init__(self, **kwargs)
        if self.props.local and not self.props.valid:
            raise RuntimeError("local activities require color, type, and name")

        # If not yet valid, query activity properties
        if not self.props.valid:
            tp.update_activity_properties(self._id)

    def do_get_property(self, pspec):
        """Gets the value of a property associated with this activity.
        
        pspec -- Property specifier

        returns The value of the given property.
        """
        
        if pspec.name == "id":
            return self._id
        elif pspec.name == "name":
            return self._name
        elif pspec.name == "color":
            return self._color
        elif pspec.name == "type":
            return self._type
        elif pspec.name == "valid":
            return self._valid
        elif pspec.name == "joined":
            return self._joined
        elif pspec.name == "local":
            return self._local

    def do_set_property(self, pspec, value):
        """Sets the value of a property associated with this activity.
        
        pspec -- Property specifier
        value -- Desired value

        Note that the "type" property can be set only once; attempting to set it
        to something different later will raise a RuntimeError.
        
        """
        if pspec.name == "id":
            self._id = value
        elif pspec.name == "name":
            self._name = value
        elif pspec.name == "color":
            self._color = value
        elif pspec.name == "type":
            if self._type:
                raise RuntimeError("activity type is already set")
            self._type = value
        elif pspec.name == "joined":
            self._joined = value
        elif pspec.name == "local":
            self._local = value

        self._update_validity()

    def _update_validity(self):
        """Sends a "validity-changed" signal if this activity's validity has changed.
        
        Determines whether this activity's status has changed from valid to
        invalid, or invalid to valid, and emits a "validity-changed" signal
        if either is true.  "Valid" means that the object's type, ID, name,
        colour and type properties have all been set to something valid
        (i.e., not "None").
        
        """
        try:
            old_valid = self._valid
            if self._color and self._name and self._id and self._type:
                self._valid = True
            else:
                self._valid = False

            if old_valid != self._valid:
                self.emit("validity-changed", self._valid)
        except AttributeError:
            self._valid = False

    # dbus signals
    @dbus.service.signal(_ACTIVITY_INTERFACE,
                        signature="o")
    def BuddyJoined(self, buddy_path):
        """Generates DBUS signal when a buddy joins this activity.
        
        buddy_path -- DBUS path to buddy object
        """
        pass

    @dbus.service.signal(_ACTIVITY_INTERFACE,
                        signature="o")
    def BuddyLeft(self, buddy_path):
        """Generates DBUS signal when a buddy leaves this activity.
        
        buddy_path -- DBUS path to buddy object
        """
        pass

    @dbus.service.signal(_ACTIVITY_INTERFACE,
                        signature="o")
    def NewChannel(self, channel_path):
        """Generates DBUS signal when a new channel is created for this activity.
        
        channel_path -- DBUS path to new channel
        
        XXX - what is this supposed to do?  Who is supposed to call it?
        What is the channel path?  Right now this is never called.
        
        """
        pass

    # dbus methods
    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="s")
    def GetId(self):
        """DBUS method to get this activity's ID
        
        returns Activity ID
        """
        return self.props.id

    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="s")
    def GetColor(self):
        """DBUS method to get this activity's colour
        
        returns Activity colour
        """
        return self.props.color

    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="s")
    def GetType(self):
        """DBUS method to get this activity's type
        
        returns Activity type
        """
        return self.props.type

    @dbus.service.method(_ACTIVITY_INTERFACE, in_signature="", out_signature="",
                        async_callbacks=('async_cb', 'async_err_cb'))
    def Join(self, async_cb, async_err_cb):
        """DBUS method to for the local user to attempt to join the activity
        
        async_cb -- Callback method to be called if join attempt is successful
        async_err_cb -- Callback method to be called if join attempt is unsuccessful
        
        """
        self.join(async_cb, async_err_cb)

    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="ao")
    def GetJoinedBuddies(self):
        """DBUS method to return a list of valid buddies who are joined in this activity
        
        returns A list of buddy object paths
        """
        ret = []
        for buddy in self._buddies:
            if buddy.props.valid:
                ret.append(buddy.object_path())
        return ret

    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="soao")
    def GetChannels(self):
        """DBUS method to get the list of channels associated with this activity
        
        returns XXX - Not sure what this returns as get_channels doesn't actually return
          a list of channels!
        """
        return self.get_channels()

    @dbus.service.method(_ACTIVITY_INTERFACE,
                        in_signature="", out_signature="s")
    def GetName(self):
        """DBUS method to get this activity's name
        
        returns Activity name
        """
        return self.props.name

    # methods
    def object_path(self):
        """Retrieves our dbus.ObjectPath object
        
        returns DBUS ObjectPath object
        """
        return dbus.ObjectPath(self._object_path)

    def get_joined_buddies(self):
        """Local method to return a list of valid buddies who are joined in this activity
        
        This method is called by the PresenceService on the local machine.
        
        returns A list of buddy objects
        """
        ret = []
        for buddy in self._buddies:
            if buddy.props.valid:
                ret.append(buddy)
        return ret

    def buddy_joined(self, buddy):
        """Adds a buddy to this activity and sends a BuddyJoined signal
        
        buddy -- Buddy object representing the buddy being added
        
        Adds a buddy to this activity if the buddy is not already in the buddy list.
        If this activity is "valid", a BuddyJoined signal is also sent.
        This method is called by the PresenceService on the local machine.
        
        """
        if buddy not in self._buddies:
            self._buddies.append(buddy)
            if self.props.valid:
                self.BuddyJoined(buddy.object_path())

    def buddy_left(self, buddy):
        """Removes a buddy from this activity and sends a BuddyLeft signal.
        
        buddy -- Buddy object representing the buddy being removed
        
        Removes a buddy from this activity if the buddy is in the buddy list.
        If this activity is "valid", a BuddyLeft signal is also sent.
        This method is called by the PresenceService on the local machine.
        
        """
        if buddy in self._buddies:
            self._buddies.remove(buddy)
            if self.props.valid:
                self.BuddyLeft(buddy.object_path())

    def _handle_share_join(self, tp, text_channel):
        """Called when a join to a network activity was successful.
        
        Called by the _shared_cb and _joined_cb methods.
        """
        if not text_channel:
            logging.debug("Error sharing: text channel was None, shouldn't happen")
            raise RuntimeError("Plugin returned invalid text channel")

        self._text_channel = text_channel
        self._text_channel[CHANNEL_INTERFACE].connect_to_signal('Closed',
                self._text_channel_closed_cb)
        self._joined = True
        return True

    def _shared_cb(self, tp, activity_id, text_channel, exc, userdata):
        """XXX - not documented yet
        """
        if activity_id != self.props.id:
            # Not for us
            return

        (sigid, owner, async_cb, async_err_cb) = userdata
        self._tp.disconnect(sigid)

        if exc:
            logging.debug("Share of activity %s failed: %s" % (self._id, exc))
            async_err_cb(exc)
        else:
            self._handle_share_join(tp, text_channel)
            self.send_properties()
            owner.add_activity(self)
            async_cb(dbus.ObjectPath(self._object_path))
            logging.debug("Share of activity %s succeeded." % self._id)

    def _share(self, (async_cb, async_err_cb), owner):
        """XXX - not documented yet
        
        XXX - This method is called externally by the PresenceService despite the fact
        that this is supposed to be an internal method!
        """
        logging.debug("Starting share of activity %s" % self._id)
        if self._joined:
            async_err_cb(RuntimeError("Already shared activity %s" % self.props.id))
            return
        sigid = self._tp.connect('activity-shared', self._shared_cb)
        self._tp.share_activity(self.props.id, (sigid, owner, async_cb, async_err_cb))
        logging.debug("done with share attempt %s" % self._id)

    def _joined_cb(self, tp, activity_id, text_channel, exc, userdata):
        """XXX - not documented yet
        """
        if activity_id != self.props.id:
            # Not for us
            return

        (sigid, async_cb, async_err_cb) = userdata
        self._tp.disconnect(sigid)

        if exc:
            async_err_cb(exc)
        else:
            self._handle_share_join(tp, text_channel)
            async_cb()

    def join(self, async_cb, async_err_cb):
        """Local method for the local user to attempt to join the activity.
        
        async_cb -- Callback method to be called if join attempt is successful
        async_err_cb -- Callback method to be called if join attempt is unsuccessful
        
        The two callbacks are passed to the server_plugin ("tp") object, which in turn
        passes them back as parameters in a callback to the _joined_cb method; this
        callback is set up within this method.
        
        """
        if self._joined:
            async_err_cb(RuntimeError("Already joined activity %s" % self.props.id))
            return
        sigid = self._tp.connect('activity-joined', self._joined_cb)
        self._tp.join_activity(self.props.id, (sigid, async_cb, async_err_cb))

    def get_channels(self):
        """Local method to get the list of channels associated with this activity
        
        returns XXX - expected a list of channels, instead returning a tuple?  ???
        """
        conn = self._tp.get_connection()
        # FIXME add tubes and others channels
        return str(conn.service_name), conn.object_path, [self._text_channel.object_path]

    def leave(self):
        """Local method called when the user wants to leave the activity.
        
        (XXX - doesn't appear to be called anywhere!)
        
        """
        if self._joined:
            self._text_channel[CHANNEL_INTERFACE].Close()

    def _text_channel_closed_cb(self):
        """Callback method called when the text channel is closed.
        
        This callback is set up in the _handle_share_join method.
        """
        self._joined = False
        self._text_channel = None

    def send_properties(self):
        """Tells the Telepathy server what the properties of this activity are.
        
        """
        props = {}
        props['name'] = self._name
        props['color'] = self._color
        props['type'] = self._type
        self._tp.set_activity_properties(self.props.id, props)

    def set_properties(self, properties):
        """Sets name, colour and/or type properties for this activity all at once.
        
        properties - Dictionary object containing properties keyed by property names
        
        Note that if any of the name, colour and/or type property values is changed from
        what it originally was, the update_validity method will be called, resulting in
        a "validity-changed" signal being generated.  (Also note that unlike with the
        do_set_property method, it *is* possible to change an already-set activity type
        to something else; this may be a bug.)  Called by the PresenceService on the
        local machine.
        """
        changed  = False
        if "name" in properties.keys():
            name = properties["name"]
            if name != self._name:
                self._name = name
                changed = True

        if "color" in properties.keys():
            color = properties["color"]
            if color != self._color:
                self._color = color
                changed = True

        if "type" in properties.keys():
            type = properties["type"]
            if type != self._type:
                self._type = type
                changed = True

        if changed:
            self._update_validity()