~ken-vandine/gwibber/unity-lens-gwibber-dee

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
#!/usr/bin/python
#
# Copyright (C) 2011 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Authored by Ken VanDine <ken.vandine@canonical.com>
#

import sys
from os.path import join, realpath, exists, expanduser, isdir
from os import makedirs
import logging
import logging.handlers
import xdg.BaseDirectory
import json
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
# FIXME: Some weird bug in Dee or PyGI makes Dee fail unless we probe
#    it *before* we import the Unity module... ?!
_m = dir(Dee.SequenceModel)
from gi.repository import Unity

BUS_NAME = "net.launchpad.UnityPlaceGwibber"

# Group ids. Must match the offset into the group models
GROUP_ALL = 0
GROUP_MESSAGES = 1
GROUP_REPLIES = 2
GROUP_IMAGES = 3
GROUP_VIDEOS = 4
GROUP_LINKS = 5
GROUP_PRIVATE = 6
GROUP_PUBLIC = 7

# Section ids. Must match the offset into the section model
SECTION_ALL = 0
SECTION_MESSAGES = 1
SECTION_REPLIES = 2
SECTION_IMAGES = 3
SECTION_VIDEOS = 4
SECTION_LINKS = 5
SECTION_PRIVATE = 6
SECTION_PUBLIC = 7

STREAM_ICON_PATH = "/usr/share/gwibber/ui/icons/streams/24x24/"
CACHE_BASE_DIR = join(expanduser("~"), ".cache")

class Logger:
    def __init__(self):
        cache_dir = realpath(join(xdg.BaseDirectory.xdg_cache_home, "gwibber"))
        if not isdir(cache_dir):
            makedirs(cache_dir)

        LOG_FILENAME = join(cache_dir, "lens.log")
        loghandler = logging.handlers.RotatingFileHandler(
                     LOG_FILENAME, maxBytes=20971520, backupCount=5)
        self.logger = logging.getLogger('Gwibber Lens')
        logformatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        loghandler.setFormatter(logformatter)
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(loghandler)
        self.logger.name = "Gwibber Lens"

class Daemon:

    active_section = 0
    results_dirty = False

    def __init__ (self):
        # The path for the place entry *must* also match the one in our .place file
        self._entry = Unity.PlaceEntryInfo.new ("/net/launchpad/unityplacegwibber/mainentry")
        
        #
        # Set up all the datamodels we'll share with the Unity process
        # See https://wiki.ubuntu.com/Unity/Places
        #
        # Terminology:
        #
        #   - "sections" A set of disjoint browsable categories.
        #        Fx. "Books", "Film", and "Music"
        #
        #   - "groups" A set of labels that partition the result set into
        #          user-visible chunks. "Popular Books", "Most Recent Books" 
        #
        sections_model = Dee.SharedModel.new (BUS_NAME + ".SectionsModel");
        sections_model.set_schema ("s", "s");
        self._entry.set_property("sections_model", sections_model)

        groups_model = Dee.SharedModel.new (BUS_NAME + ".GroupsModel");
        groups_model.set_schema ("s", "s", "s");
        self._entry.get_property("entry_renderer_info").set_property("groups_model", groups_model)

        global_groups_model = Dee.SharedModel.new (BUS_NAME + ".GlobalGroupsModel");
        global_groups_model.set_schema ("s", "s", "s");
        self._entry.get_property("global_renderer_info").set_property("groups_model", global_groups_model)


        self.results_model = Dee.SharedModel.new (BUS_NAME + ".ResultsModel");
        self.results_model.set_schema ("s", "s", "u", "s", "s", "s");
        self._entry.get_property("entry_renderer_info").set_property("results_model", self.results_model)

        global_results_model = Dee.SharedModel.new (BUS_NAME + ".GlobalResultsModel");
        global_results_model.set_schema ("s", "s", "u", "s", "s", "s");
        self._entry.get_property("global_renderer_info").set_property("results_model", global_results_model)

        #
        # Populate the sections and groups once we are in sync with Unity
        #
        sections_model.connect ("notify::synchronized", self.on_sections_synchronized)
        groups_model.connect ("notify::synchronized", self.on_groups_synchronized)
        global_groups_model.connect ("notify::synchronized", self.on_global_groups_synchronized)

        #
        # Set up the signals we'll receive when Unity starts to talk to us
        #
        
        # The 'active-search' property is changed when the users searches
        # within this particular place
        self._entry.connect ("notify::active-search", self.on_search_changed)
        
        # The 'active-global-search' property is changed when the users searches
        # from the Dash aka Home Screen
        self._entry.connect ("notify::active-global-search", self.on_global_search_changed)

        # Listen for changes to the section
        self._entry.connect("notify::active-section", self.on_section_change)
        
        self._entry.connect("notify::active", self.on_active_change)
        #
        # PlaceEntries are housed by PlaceControllers.
        # You may have mutiple entries per controller if you like.
        # The controller *must* have the DBus Object path you specify
        # in your .place file
        #
        self._ctrl = Unity.PlaceController.new ("/net/launchpad/unityplacegwibber")        
        self._ctrl.add_entry (self._entry)
        self._ctrl.export ()
        self.streams = None
        self.setup_gwibber_bus()

    def on_row_added(self, model, iter, *args):
        if self.results_dirty:
            return
        if len(self.streams_model) == 0: return
        log.logger.debug("on_row_added %s", self.streams_model[0])
        if not self.results_model.is_synchronized():
            return
        msg = self.streams_model[0]
        if msg in self.results_model: return
        active_search = self._entry.get_property("active-search")
        if active_search:
            search = active_search.get_search_string()
        else:
            search = None

        if msg[1] not in ["messages", "replies", "private", "images", "links", "videos", "public"]:
            return
        if self.active_section != GROUP_ALL:
            if eval("GROUP_" + msg[1].upper()) != self.active_section:
                return
        if search:
            if search.lower() not in msg[3].lower() and search.lower() not in msg[5].lower():
                return
        #log.logger.debug("%s, %s, %s", eval("GROUP_" + msg[1].upper()),  msg[3], msg[5])
        #print "ADDED %s" % msg
        self.results_model.prepend(msg[7], msg[6], eval("GROUP_" + msg[1].upper()), "text/html", msg[3], msg[5])
        self.results_model.flush_revision_queue()

    def on_row_deleted(self, model, iter, *args):
        print "DELETED"
        self.results_model.clear()
        self.results_model.flush_revision_queue()
        #self.refresh_filter()

    def setup_gwibber_bus(self):
        session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
        try:
            self.streams = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                          'com.Gwibber.Streams',
                          '/com/gwibber/Streams',
                          'com.Gwibber.Streams', None)
        except:
            self.streams = None

        try:
            self.messages = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                          'com.Gwibber.Messages',
                          '/com/gwibber/Messages',
                          'com.Gwibber.Messages', None)
        except:
            self.messages = None

    def filter_model(self, search=None, model=None, section=None):
        log.logger.debug("filter_model search is %s and section is %s", search, self.active_section)
        self.models = []

        # Store all results in a list to be filtered on as needed
        streams_model = Dee.SharedModel.new("com.Gwibber.Streams.Model")
        streams_model.connect ("notify::synchronized", self.on_streams_synchronized, search, model, section)

        self.models.append(streams_model)

    def on_streams_synchronized(self, streams_model, synchronized, search, results_model, section):
        log.logger.debug("on_streams_synchronized search is %s and section is %s", search, section)
        active_search = self._entry.get_property("active-search")
        if active_search:
            search = active_search.get_search_string()
        else:
            search = None
        
        results_model.clear()

        log.logger.debug("filter_model BEFORE loop")
        print "###############################################################"
        print "There are now %s rows in the streams model" % len(streams_model) 
        print "###############################################################"
        log.logger.debug("There are now %s rows in the streams model", len(streams_model))
        log.logger.debug("%s", streams_model[0])
        log.logger.debug("%s", streams_model[len(streams_model)-1])

        for msg in streams_model:
            if msg[1] not in ["messages", "replies", "private", "images", "links", "videos", "public"]:
                continue
            if self.active_section != GROUP_ALL:
                #log.logger.debug("Not GROUP_ALL, group is %d", eval("GROUP_" + msg[1].upper()))
                if eval("GROUP_" + msg[1].upper()) != self.active_section:
                    continue
            if search:
                if search.lower() not in msg[3].lower() and search.lower() not in msg[5].lower():
                    continue
            #log.logger.debug("%s, %s, %s", eval("GROUP_" + msg[1].upper()),  msg[3], msg[5])
            results_model.prepend(msg[7], msg[6], eval("GROUP_" + msg[1].upper()), "text/html", msg[3], msg[5])
        log.logger.debug("filter_model AFTER loop")
        results_model.flush_revision_queue()
        log.logger.debug("filter_model AFTER flush")
        if streams_model:
            del streams_model
        if self.models:
            del self.models

    def on_active_change(self, entry, section):
        if self.results_dirty:
            return
        if self._entry.get_property("active"):
            log.logger.debug("on_active_change got active")
            active_search = self._entry.get_property("active-search")
            if active_search:
                search = active_search.get_search_string()
            else:
                search = None
            if self.active_section == self._entry.get_property("active-section"):
                self.filter_model (search, self.results_model, self.active_section)
            return
        log.logger.debug("on_active_change got inactive")

    def on_section_change(self, entry, section):
        log.logger.debug("on_section_change")
        if self.results_dirty:
            return
        self.active_section = self._entry.get_property("active-section")
        log.logger.debug("on_section_change - section is %d", self.active_section)
        active_search = self._entry.get_property("active-search")
        if active_search:
            search = active_search.get_search_string()
        else:
            search = None
        self.filter_model(search, self.results_model, section)
        #self.results_model.flush_revision_queue()
        if active_search:
            active_search.finished()
    
    def on_sections_synchronized (self, sections_model, *args):
        sections_model.clear ()
        sections_model.append ("Everything",
                       self.get_stream_icon_path("home"))
        sections_model.append ("Posts",
                       self.get_stream_icon_path("messages"))
        sections_model.append ("Replies",
                       self.get_stream_icon_path("replies"))
        sections_model.append ("Images",
                       self.get_stream_icon_path("images"))
        sections_model.append ("Videos",
                       self.get_stream_icon_path("videos"))
        sections_model.append ("Links",
                       self.get_stream_icon_path("links"))
        sections_model.append ("Private Messages",
                       self.get_stream_icon_path("private"))
        sections_model.append ("Public",
                       self.get_stream_icon_path("public"))
    
    def on_groups_synchronized (self, groups_model, *args):
        groups_model.clear ()
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Everything",
                     self.get_stream_icon_path("home"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Posts",
                     self.get_stream_icon_path("messages"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Replies",
                     self.get_stream_icon_path("replies"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Images",
                     self.get_stream_icon_path("images"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Videos",
                     self.get_stream_icon_path("videos"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Links",
                     self.get_stream_icon_path("links"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Private Messages",
                     self.get_stream_icon_path("private"))
        groups_model.append ("UnityHorizontalTileRenderer",
                     "Public",
                     self.get_stream_icon_path("public"))
    
    def on_global_groups_synchronized (self, global_groups_model, *args):
        self.on_groups_synchronized (global_groups_model)
    
    def on_search_changed (self, entry, *args):        
        log.logger.debug("on_search_change")
        # Prevent concurrent searches and concurrent updates of our models,
        # by preventing any notify signals from propagating to us.
        # Important: Remember to thaw the notifys again! 
        self._entry.freeze_notify ()
        active_search = self._entry.get_property("active_search")
        search = active_search.get_search_string() if active_search else None
        self.filter_model (search, self.results_model, self.active_section)
        active_search.finished()
        GObject.idle_add(self.thaw, self._entry)
    
    def thaw(self, entry):
        self._entry.thaw_notify ()
        return False

    def on_global_search_changed (self, entry, param_spec):
        # Prevent concurrent searches and concurrent updates of our models,
        # by preventing any notify signals from propagating to us.
        # Important: Remember to thaw the notifys again! 
        entry.freeze_notify ()
        active_search = entry.get_property("active_global_search")
        search = active_search.get_search_string() if active_search else None
        self.filter_model (search, self.results_model)
        #self.results_model.flush_revision_queue()
        GObject.idle_add(self.thaw, entry)
        active_search.finished()

    def _check_msg (self, search, msg):
        if not search: return True
        # acctid, stream, service, name, time, content, icon, url
        if search.lower() in msg[3].lower() or search.lower() in msg[5].lower():
            return True
        return False

    def get_icon(self, msg):
        if msg["sender"]["image"]:
            icon = self.get_avatar_path(msg["sender"]["image"])
            if not icon:
                icon = msg["sender"]["image"]
        else:
            icon = Gio.ThemedIcon("nobody").to_string()
        return icon

    def sanitize_image_data(self, msg):
        url = None
        icon = None
        text = None
        if msg.has_key("photo"):
            if msg["photo"].has_key("picture"): icon = msg["photo"]["picture"]
            if msg["photo"].has_key("url"): url = msg["photo"]["url"]
        elif msg.has_key("images") and isinstance(msg["images"], list):
            if msg["images"][0].has_key("src"): icon = msg["images"][0]["src"]
            if msg["images"][0].has_key("url"): url = msg["images"][0]["url"]
        if not icon and msg["sender"]["image"]:
            icon = self.get_avatar_path(msg["sender"]["image"])
        elif not icon:
            icon = Gio.ThemedIcon("nobody").to_string()
        if not url and msg.has_key("url"): url = msg["url"]
        if not text and msg.has_key("text"): text = msg["text"]
        return icon, url, text

    def sanitize_video_data(self, msg):
        url = None
        icon = None
        text = None
        if msg.has_key("text"): text = msg["text"]
        if msg.has_key("video"):
            if msg["video"].has_key("picture"): icon = msg["video"]["picture"]
            if msg["video"].has_key("url"): url = msg["video"]["url"]
            if not text and msg["video"].has_key("name"): text = msg["video"]["name"]
        if not icon and msg["sender"]["image"]:
            icon = self.get_avatar_path(msg["sender"]["image"])
        elif not icon:
            icon = Gio.ThemedIcon("nobody").to_string()
        if not url and msg.has_key("url"): url = msg["url"]
        return icon, url, text

    def sanitize_link_data(self, msg):
        url = None
        icon = None
        text = None
        if msg.has_key("text"): text = msg["text"]
        if msg.has_key("link"):
            if msg["link"].has_key("picture"): 
                if msg["link"]["picture"]: icon = msg["link"]["picture"]
                elif msg["sender"]["image"]: icon = self.get_avatar_path(msg["sender"]["image"])
            if msg["link"].has_key("url"): url = msg["link"]["url"]
            if not text and msg["link"].has_key("name"): text = msg["link"]["name"]
        if not icon and msg["sender"]["image"]:
            icon = self.get_avatar_path(msg["sender"]["image"])
        elif not icon:
            icon = Gio.ThemedIcon("nobody").to_string()
        if not url and msg.has_key("url"): url = msg["url"]
        return icon, url, text

    def get_stream_icon_path (self, name):
        return join(STREAM_ICON_PATH, (name + ".png"))

    def get_avatar_path(self, url):
        avatar_cache_dir = realpath(join(CACHE_BASE_DIR, "gwibber", "avatars"))
        avatar_cache_image = join(avatar_cache_dir, url.replace("/",""))

        if not exists(avatar_cache_image) or len(open(avatar_cache_image, "r").read()) < 1:
            return None
        if len(open(avatar_cache_image, "r").read()) > 0:
            return avatar_cache_image
        return None

if __name__ == "__main__":
    log = Logger()
    session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
    session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
                          'org.freedesktop.DBus',
                          '/org/freedesktop/DBus',
                          'org.freedesktop.DBus', None)
    result = session_bus.call_sync('RequestName',
                       GLib.Variant ("(su)", (BUS_NAME, 0x4)),
                       0, -1, None)
                       
    result = result.unpack()[0]
    
    if result != 1 :
        print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
        raise SystemExit (1)
    
    daemon = Daemon()
    GObject.MainLoop().run()