~mhall119/onehundredscopes/loco-team-portal

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
#! /usr/bin/python

#    Copyright (c) 2011 David Calle <davidc@framli.eu>
#    Copyright (c) 2011 Michael Hall <mhall119@gmail.com>

#    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 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 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/>.

import sys
import os
import datetime
import locodir

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.lens.ltp"

LTP_TEAMS = 0
LTP_EVENTS = 1
LTP_MEETINGS = 2
LTP_VENUES = 3

class Daemon:

    def __init__ (self):
        # The path for the Lens *must* also match the one in our .lens file
        self._lens = Unity.Lens.new ("/net/launchpad/lens/ltp", "ltp")
        self._scope = Unity.Scope.new ("/net/launchpad/lens/ltp/main")
        self._scope.connect ("notify::active-search", self.on_search_changed)
        self._scope.connect ("filters-changed", self.on_search_changed);
        self._scope.connect ("notify::active", self.on_search_changed);
        #self._scope.connect ("activate-uri", self.on_activate_uri);
        self._scope.export()

        self._lens.props.search_hint = "Search LoCo Teams & Activity"
        self._lens.props.visible = True;
        self._lens.props.search_in_global = False;
        
        # Populate categories
        cats = []
        cats.append (Unity.Category.new ("Teams",
                                         Gio.ThemedIcon.new("ubuntu-logo"),
                                         Unity.CategoryRenderer.VERTICAL_TILE))

        cats.append (Unity.Category.new ("Events",
                                         Gio.ThemedIcon.new("calendar"),
                                         Unity.CategoryRenderer.HORIZONTAL_TILE))

        cats.append (Unity.Category.new ("Meetings",
                                         Gio.ThemedIcon.new("applications-chat"),
                                         Unity.CategoryRenderer.HORIZONTAL_TILE))

        cats.append (Unity.Category.new ("Venues",
                                         Gio.ThemedIcon.new("stock_home"),
                                         Unity.CategoryRenderer.HORIZONTAL_TILE))

        self._lens.props.categories = cats
        
        # Populate filters
        filters = []
        self._lens.props.filters = filters

        self._lens.add_local_scope (self._scope);
        self._lens.export ()

        self._ltp = locodir.LocoDirectory()

    def thaw(self, entry):
        entry.thaw_notify()
        return False

    def on_search_changed (self, entry, *args):
        print "on_search_changed"
        # 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 ()
        search = self._scope.props.active_search or None
        if search:
            search_string = search.props.search_string or None
        else:
            search_string = None
        results = self._scope.props.results_model
        self.update_results_model (search_string, results)
        GObject.idle_add(self.thaw, entry)

#
# Update results model
#
    def update_results_model(self, search, model):
        print "update_results_model"
        model.clear()
        if search != '' and search:
            self._ltp.clearCache()
            # Teams by name
            # Until we have a longer search phrase, only match the beginning of the team name
            if len(search) < 2:
                teams = self._ltp.getTeams(name__istartswith=search)
            else:
                teams = self._ltp.getTeams(name__icontains=search)
            for team in teams.values():
                model.append('http://loco.ubuntu.com/teams/%s/' % team['lp_name'],
                             team['mugshot_url'],
                             LTP_TEAMS,
                             "text/html",
                             team['name'], team['lp_name'], '')

                # To avoid long waits, don't search for a team's events and meetings until we have only a handful of teams
                if len(teams) <= 5:
                    # Events by team
                    for tevent in self._ltp.getTeamEvents(teams=team['id'], date_end__gte=datetime.datetime.utcnow()).values():
                        model.append('http://loco.ubuntu.com/events/%s/%s/detail/' % (team['lp_name'], tevent['id']),
                                     team['mugshot_url'],
                                     LTP_EVENTS,
                                     "text/html",
                                     tevent['name'], '%s\n%s' % (tevent['date_begin'], tevent['description']), '')

                    # Meetings by team
                    print "Looking for meetings for %s" % team['name']
                    for tmeeting in self._ltp.getTeamMeetings(teams=team['id'], date_end__gte=datetime.datetime.utcnow()).values():
                        model.append('http://loco.ubuntu.com/meetings/%s/%s/detail/' % (team['lp_name'], tmeeting['id']),
                                     team['mugshot_url'],
                                     LTP_MEETINGS,
                                     "text/html",
                                     tmeeting['name'], tmeeting['date_begin'], '')
                 
            
            # To avoid long waits, don't search for events and meetings until we have a longer search phrase
            if len(search) >= 3:
                # Events by name
                for tevent in self._ltp.getTeamEvents(name__icontains=search, date_end__gte=datetime.datetime.utcnow()).values():
                    team = self._ltp.getTeam(tevent['teams'][0])
                    model.append('http://loco.ubuntu.com/events/%s/%s/detail/' % (team['lp_name'], tevent['id']),
                                 team['mugshot_url'],
                                 LTP_EVENTS,
                                 "text/html",
                                 tevent['name'], '%s\n%s' % (tevent['date_begin'], tevent['description']), '')
                
                # Meetings by name
                for tmeeting in self._ltp.getTeamMeetings(name__icontains=search, date_end__gte=datetime.datetime.utcnow()).values():
                    team = self._ltp.getTeam(tmeeting['teams'][0])
                    model.append('http://loco.ubuntu.com/meetings/%s/%s/detail/' % (team['lp_name'], tmeeting['id']),
                                 team['mugshot_url'],
                                 LTP_MEETINGS,
                                 "text/html",
                                 tmeeting['name'], tmeeting['date_begin'], '')

        else:
            # Display all teams
            for team in self._ltp.getTeams().values():
                model.append('http://loco.ubuntu.com/teams/%s/' % team['lp_name'],
                             team['mugshot_url'],
                             LTP_TEAMS,
                             "text/html",
                             team['name'], team['lp_name'], '')

if __name__ == "__main__":
    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)
                                   
    # Unpack variant response with signature "(u)". 1 means we got it.
    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()