File: launchpad.py

package info (click to toggle)
groundcontrol 1.6.6-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 2,296 kB
  • ctags: 670
  • sloc: python: 3,486; sh: 26; makefile: 11
file content (411 lines) | stat: -rw-r--r-- 13,972 bytes parent folder | download
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
#
# Copyright 2009 Martin Owens
#
# 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/>
#
"""
This provides some interaction with launchpad
"""

import os
import logging
import httplib2

from launchpadlib.errors import HTTPError
from launchpadlib.launchpad import Launchpad
from launchpadlib.credentials import Credentials

from bzrlib.config import GlobalConfig
from bzrlib.plugins.launchpad.account import get_lp_login

from GroundControl.base import (
    Events, LAUNCHPAD_XDG, PROJECT_NAME,
    LP_WEB_ROOT, LP_SERVE_ROOT,
)
from GroundControl.launchpadweb import FormParser, LaunchpadWeb


CACHE_DIR = LAUNCHPAD_XDG.get_cache_dir('oauth')
# This is the path used by other things...
#DEFAULT_CRED = os.path.expanduser('~/.cache/lp_credentials/%s-edge.txt')
# But we will use this directory
DEFAULT_CRED = os.path.join(
    LAUNCHPAD_XDG.get_cache_dir('credentials'), '%s-edge.txt')
ICONS     = {}
ICON_PATH = CACHE_DIR


def get_launchpad(project=PROJECT_NAME):
    """One single MyLaunchpad to rule them all, control varience"""
    return MyLaunchpad(project)

def get_browser(root=LP_WEB_ROOT):
    """Return a default launchpad web browser"""
    return LaunchpadWeb(root=root)


class MyLaunchpad(object):
    """Manage an authorised user's launchpad account"""
    def __init__(self, project, credentials=None):
        if not credentials:
            credentials = DEFAULT_CRED % project
        logging.info(_("Save cache file to %s") % credentials)
        self._project = project
        self._crds    = None
        self._cfile   = credentials
        self._me      = None
        self._lp = None

    @property
    def credentials(self):
        """Loaded credentials object"""
        if not self._crds:
            self._crds = Credentials(self._project)
            if os.path.exists(self._cfile):
                self._crds.load(open(self._cfile))
            else:
                self.request_credentials()
        return self._crds

    @property
    def launchpad(self):
        """Load this user's launchpad object"""
        if not self._lp:
            logging.debug("Loading Launchpad %s." % LP_SERVE_ROOT)
            try:
                self._lp = Launchpad(self.credentials,
                    LP_SERVE_ROOT, CACHE_DIR)
            except httplib2.ServerNotFoundError:
                logging.warn(_("No Launchpad server %s.") % LP_SERVE_ROOT)
        return self._lp

    def request_credentials(self, web_root=LP_WEB_ROOT):
        """Request a set of credentials from launchpad"""
        authorization_url = self._crds.get_request_token(web_root=web_root)
        browser = get_browser(root=LP_SERVE_ROOT)
        content = browser.request(authorization_url, user_required=False)
        # We parse everythign outselves without going to the web browser
        # As web browsers are untrustworthy for authentication.
        par = FormParser()
        par.feed(str(content))
        form = par.get_form('launchpadform')
        if form and form.action and 'token' in form.action:
            data = form.submit_data('field.actions.WRITE_PRIVATE')
            logging.warn(_("Posting REQUEST to %s with %s via %s") % (
                form.action, str(data), form.method))
            content = browser.request(
                form.action, data=data, method=form.method)
            self.confirm_credentials(web_root)
        else:
            logging.warn(_("Unable to get Launchpad auth - not logged in."))

    def confirm_credentials(self, web_root=LP_WEB_ROOT):
        """Confirm the credential request"""
        try:
            self._crds.exchange_request_token_for_access_token(web_root)
        except HTTPError, message:
            logging.error("Unablr to log into Launchpad OAuth, %s" % message)
        else:
            self._crds.save(file(self._cfile, "w"))

    def logoff(self):
        """Remove tokens and reset object"""
        if os.path.exists(self._cfile):
            os.unlink(self._cfile)
        self._crds = None #Credentials(self._project)
        self._lp   = None

    @property
    def name(self):
        """Return the display name of this user"""
        return self.launchpad.me.display_name

    @property
    def username(self):
        """Return the username of this user"""
        return self.me.name

    @property
    def me(self):
        """Return a me launchpad wrapper object"""
        if not self._me:
            self._me = LaunchpadPerson(self.launchpad, obj=self.launchpad.me)
        return self._me

    def bzr_config(self):
        """Return the configuration for bazaar"""
        return GlobalConfig()

    def bzr_username(self):
        """Return the username configured in bazaar/launchpad."""
        return get_lp_login(self.bzr_config())


class lpobject(object):
    """Genric Wrapper for all lp objects"""
    type  = "None"
    group = None

    def __init__(self, lp, obj=None, oid=None):
        # Deal with mixed launchpad items
        self.launchpad = lp
        if type(self.group) in (str, unicode):
            self.group = getattr(self.launchpad, self.group)

        if oid and not obj and self.group:
            obj = self.group[oid]
        if type(obj) == type(None):
            raise TypeError("Launchpad object required an lp object or an id.")
        self._object = obj
        self.id = obj.name
        # This will slow everything down and cause
        # GTK to freeze because it's loading http requests.
        self.load_attributes()

    def __getattr__(self, name):
        """Return the an attribute from the object, but cache it"""
        hoop = self._object
        hname = '_' + name
        if not hasattr(hoop, hname) or not getattr(hoop, hname):
            setattr(self, hname, getattr(hoop, name))
        return getattr(self, hname)

    def _image(self, name="image"):
        """Loads an image, saves it in two caches (memory and disk)"""
        iid = "%s-%s" % (self.type, name)
        if not ICONS.has_key(iid):
            ICONS[iid] = {}
        if not ICONS[iid].has_key(self.id):
            filename = self._image_file(name)
            logging.debug(" ..Loading image file '%s'" % filename)
            ICONS[iid][self.id] = filename
        return ICONS[iid][self.id]

    def _image_file(self, name="image"):
        """Loads an image and saves it as a file."""
        # type not taken into consideration, maybe trouble
        filename = os.path.join(ICON_PATH, '%s-%s.png' % (self.id, name))
        logging.debug("Looking for image file '%s'" % filename)
        if not os.path.exists(filename):
            try:
                ol = getattr(self._object, name).open()
                data = ol.read()
            except HTTPError:
                filename = None
            else:
                fh = open(filename, "wb")
                fh.write(data)
                fh.close()
        return filename


class LaunchpadPerson(lpobject):
    """Wrap around a launchpad user account"""
    type = "person"
    group = 'people'

    def load_attributes(self):
        self.name = self._object.display_name
        self.team = self._object.is_team
        self.member = False
        self.members = []
        if self.team:
            for person in self._object.members:
                self.members.append(person)
                if person.name == self.launchpad.me.name:
                    self.member = True
        else:
            if self._object.name == self.launchpad.me.name:
                self.member = True

    def image(self):
        """Return the image for a person"""
        return self._image("mugshot")


class LaunchpadBranch(lpobject):
    """Wrap around a simple launchpad branch"""
    def __init__(self, lp, obj=None, url=None):
        """Load a bazaar branch from launchpad"""
        if url and not obj:
            obj = lp.branches.getByUrl(url=url)
            logging.debug("Getting branch from %s (%s)" % (url, obj))
        super(LaunchpadBranch, self).__init__(lp, obj)

    def load_attributes(self):
        """Load up branch attributes"""
        self.name = self._object.display_name
        self.develop = False
        self.series = None
        if self.name[:3] == 'lp:':
            items = self.name[3:].split('/')
            if len(items) == 1:
                self.develop = True
            elif len(items) == 2:
                self.series = items[1]
        self.sname = self._object.name
        self.merge_request = None
    
    def load_extra_attributes(self):
        """Load the image filename and other owner data"""
        logging.debug("Loading attributes for %s" % self.name)
        self._sowner = LaunchpadPerson(self.launchpad, self.owner)
        self._ownname = self._sowner.name.replace('&', '&amp;')
        self._fimage = self._sowner.image()
        if self.merge_request:
            for comment in self.merge_request.all_comments:
                self._request_message = comment.message_body
            #self._request_message = self.merge_request.commit_message
    
    def active(self):
        """Return true if the branch is active"""
        if self.status in [ 'Merged', 'Abandoned' ]:
            return False
        return True

    def merge_requests(self, callback=None):
        """Return merge requestd as sub branches"""
        for prop in self._object.getMergeProposals():
            brch = LaunchpadBranch(self.launchpad, prop.source_branch)
            brch.merge_request = prop
            if callback:
                callback(brch)


class LaunchpadProject(lpobject):
    """Wrap around a launchpad project for a laugh."""
    type = 'project'
    group = 'projects'

    def load_attributes(self):
        self.id = self._object.name
        self.name = self._object.display_name
        self.desc = self._object.summary

    def icon(self):
        """Load the icon image"""
        return self._image("icon")

    def logo(self):
        """Load the logo image"""
        return self._image("logo")

    def brand(self):
        """Load the brand image"""
        return self._image("brand")

    def branches(self, *args, **kwargs):
        """Get a project's branches"""
        callback = kwargs.pop('callback', None)
        results = []
        series = []
        focus  = []
        for branch in self._object.getBranches():
            result = LaunchpadBranch(self.launchpad, branch)
            if callback:
                inta = args + (result,)
                callback(*inta, **kwargs)
            if result.develop:
                focus.append(result)
            elif result.series:
                series.append(result)
            else:
                results.append(result)
        return focus + series + results


class LaunchpadCollection(Events):
    """Wrap launchpad collections for searching."""
    group = None

    def __init__(self, lp, **kwargs):
        self.launchpad = lp
        self._target = getattr(lp, self.group)
        self._kwargs = kwargs

    def search(self, terms, no_search=False):
        """Run a project search"""
        logging.debug("Search %s for %s" % (self.group, terms))
        # We assume that an lp: prefix indicates the user knows
        # The exact object id ther're going after and so we don't
        # Do a search.
        if terms[:3] == 'lp:':
            terms = terms[3:]
            no_search = True
        try:
            self.result(self._target[terms])
        except KeyError:
            logging.debug("No exact match for %s" % terms)
        except AttributeError:
            logging.debug("Matched term isn't real.")
        if not no_search:
            self._search(terms)
            logging.debug("Finished Search")
        self.call_signal("search_finish")

    def _search(self, terms):
        """Perform an actual search, however we can"""
        for object in self._target.search(text=terms):
            self.result(object)

    def result(self, object):
        """Return a valid object via a signal."""
        self.call_signal("search_result",
            item=self.item_class(self.launchpad, object))



class LaunchpadProjects(LaunchpadCollection):
    """Wrap around the launchpad projects for our own amusement."""
    group = 'projects'
    item_class = LaunchpadProject


class LaunchpadBug(lpobject):
    """Wrap around a launchpad bug for a laugh."""
    type = 'bug'
    group = 'bugs'

    def load_attributes(self):
        self.id   = self._object.id
        self.name = self._object.title
        self.desc = self._object.description
        for task in self._object.bug_tasks:
            self.task = task
        self.project_id = self.task.bug_target_name
        self._project = None

    @property
    def project(self):
        """Return a nice project object"""
        if not self._project:
            self._project = LaunchpadProject(self.launchpad,
                oid=self.project_id)
            logging.debug("Found project %s" % self.project.name)
        return self._project


class LaunchpadBugs(LaunchpadCollection):
    """Wrap around the launchpad bugs for our own amusement."""
    group = 'bugs'
    item_class = LaunchpadBug

    def _search(self, terms):
        """Search for a bug, via the search task"""
        project = self._kwargs.get('project', None)
        if project:
            for task in project.searchTasks(search_text=terms):
                self.result(task.bug)