~ltp-devs/loco-team-portal/0.2

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
# -*- coding: utf-8 -*-
#!/usr/bin/python

from django.core.management.base import NoArgsCommand
from django.contrib.auth.models import Group

from teams import models
from userprofiles.models import UserProfile, create_profile
from common import launchpad

from datetime import datetime
import sys

import logging
st_handler = logging.StreamHandler(sys.stderr)
formatter = logging.Formatter("[%(asctime)s] - %(levelname)s - %(module)s - %(message)s")
st_handler.setFormatter(formatter)

log = logging.getLogger(__name__)
log.addHandler(st_handler)
log.setLevel(logging.DEBUG)


def create_admin_dict(admins):
    admin_dict = {}
    for (lpid, realname) in admins:
        admin_dict[lpid] = realname
    return admin_dict


def update_admins(ld_team, lp_team, lp):
    admins = set(get_team_admins(lp_team))
    team_owner = lp_team.team_owner
    if team_owner.is_team:
        admins.union(set(team_owner.participants))
    ld_admin_names = create_admin_dict([(a.user.username, a.realname) \
                                           for a in ld_team.admin_profiles.all()])
    lp_admin_names = create_admin_dict([(a.name, a.display_name) \
                                           for a in admins])
    ld_admin_set = set(ld_admin_names.keys())
    lp_admin_set = set(lp_admin_names.keys())
    for admin_name in ld_admin_set.difference(lp_admin_set):
        try:
            admin = ld_team.admin_profiles.get(user__username=admin_name)
            ld_team.admin_profiles.remove(admin)
        except UserProfile.DoesNotExist:
            pass
    for admin_name in lp_admin_set.difference(ld_admin_set):
        admin = create_profile(admin_name)
        admin.realname = lp_admin_names[admin_name]
        admin.tz = launchpad.get_user_timezone(admin_name, lp)
        admin.save()
        ld_team.admin_profiles.add(admin)


def get_team_owner(lp_team):
    owner = lp_team.team_owner
    if owner.is_team:
        return get_team_owner(owner)
    return owner


def get_team_admins(lp_team):
    ''' Get all the admins of a team (recursive) '''
    admins = []
    for admin in lp_team.getMembersByStatus(status='Administrator'):
        if admin.is_team:
            admins.extend(admin.participants)
        else:
            admins.append(admin)
    return admins


class Command(NoArgsCommand):
    help = "Pull list of LoCo Teams from Launchpad and add them to the DB."

    def handle_noargs(self, **options):
        lp = launchpad.lp_login()
        if not lp:
            sys.exit(1)
        TEAM_BLACKLIST = (u"ubuntu-games-merged")

        existing_locos = models.Team.objects.all()
        existing_groups = Group.objects.all()
        locos = filter(lambda a: a.is_team and a.name not in TEAM_BLACKLIST,
                       lp.people["locoteams"].members)
        for l in locos:
            if not existing_locos or l.name not in [b.lp_name for b in existing_locos]:
                team = models.Team(lp_name=l.name, name=l.display_name,
                                   owner_profile=create_profile(get_team_owner(l).name))
                team.save()
                log.debug("Created team %s" % team.name)
            else:
                team = filter(lambda a: a.lp_name == l.name, existing_locos)[0]
                team.name = l.display_name
                team.owner_profile = create_profile(get_team_owner(l).name)
                if not len(team.contact_profiles.all()):
                    team.contact_profiles.add(team.owner_profile)
                log.debug("Updated team %s" % team.name)
            update_admins(team, l, lp)

            if not existing_groups or l.name not in [g.name for g in existing_groups]:
                group = Group(name=l.name)
                group.save()
            approved_entry = filter(lambda a: a.team.name == u"locoteams-verified", l.memberships_details)
            if approved_entry:
                team.approved = True
                if team.approved:
                    approval = approved_entry[0]
                    if isinstance(approval.date_expires, unicode):
                        try:
                            team.expires_date = datetime.strptime(approval.date_expires[:19], "%Y-%m-%dT%H:%M:%S")
                        except ValueError:
                            team.expires_date = datetime.strptime(approval.date_expires[:11], "%Y-%m-%d")
                    else:
                        team.expires_date = approval.date_expires
            else:
                team.approved = False
                team.expires_date = None

            a = lp.people[team.lp_name]
            if hasattr(a, 'logo_link'):
                team.mugshot_url = launchpad.get_mugshot_url(a.logo_link)
            team.save()

        lp_loco_names = set([a.name for a in locos])
        ld_loco_names = set([a.lp_name for a in existing_locos])
        for a in existing_locos:
            if a.lp_name in ld_loco_names.difference(lp_loco_names):
                a.active = False
            else:
                a.active = True
            a.save()