966ebeda6a850106978a997b53ee094502145285
[debianmemberportfolio.git] / debianmemberportfolio / model / urlbuilder.py
1 # -*- python -*-
2 # -*- coding: utf8 -*-
3 #
4 # DDPortfolio service url builder
5 # Copyright © 2009, 2010, 2011, 2012 Jan Dittberner <jan@dittberner.info>
6 #
7 # This file is part of DDPortfolio service.
8 #
9 # DDPortfolio service is free software: you can redistribute it and/or
10 # modify it under the terms of the GNU Affero General Public License
11 # as published by the Free Software Foundation, either version 3 of
12 # the License, or (at your option) any later version.
13 #
14 # DDPortfolio service is distributed in the hope that it will be
15 # useful, but WITHOUT ANY WARRANTY; without even the implied warranty
16 # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # Affero General Public License for more details.
18 #
19 # You should have received a copy of the GNU Affero General Public
20 # License along with this program.  If not, see
21 # <http://www.gnu.org/licenses/>.
22 #
23 """
24 This module provides the function build_urls to build personalized
25 URLs using the given information and the URL patterns defined in
26 ddportfolio.ini.
27 """
28
29 from ConfigParser import ConfigParser, InterpolationMissingOptionError
30 import pkg_resources
31 from ddportfolioservice.model import keyfinder
32 from urllib import quote_plus
33 from pylons.i18n.translation import _, N_
34
35
36 my_config = ConfigParser()
37 my_config.readfp(pkg_resources.resource_stream(__name__, 'ddportfolio.ini'))
38
39 _FIELDNAMES_MAP = {
40     'email': N_('Email address'),
41     'name': N_('Name'),
42     'gpgfp': N_('GPG fingerprint'),
43     'username': N_('Debian user name'),
44     'nonddemail': N_('Non Debian email address'),
45     'aliothusername': N_('Alioth user name'),
46     }
47
48
49 class DDPortfolioEntry(object):
50     def __init__(self, config, section, key):
51         self.name = key
52         self.optional = config.has_option(section, key + '.optional') and \
53             config.getboolean(section, key + '.optional') or False
54         if config.has_option(section, key + '.type'):
55             self.type = config.get(section, key + '.type')
56         else:
57             self.type = 'url'
58
59
60 def build_urls(fields):
61     """Build personalized URLs using the developer information in
62     fields."""
63     data = []
64     qfields = {}
65     for key, value in fields.iteritems():
66         if value is not None:
67             if isinstance(value, unicode):
68                 qfields[key] = quote_plus(value.encode('utf8'))
69             elif isinstance(value, str):
70                 qfields[key] = quote_plus(value)
71             else:
72                 qfields[key] = value
73
74     if 'gpgfp' not in qfields:
75         fpr = keyfinder.getFingerprintByEmail(fields['email'].encode('utf8'))
76         if fpr:
77             qfields['gpgfp'] = fpr[0]
78     qfields['firstchar'] = fields['email'][0].encode('utf8')
79     qfields['emailnoq'] = fields['email'].encode('utf8')
80     for section in [section.strip() for section in \
81                         my_config.get('DEFAULT',
82                                       'urlbuilder.sections').split(',')]:
83         data.append(['section', section])
84         if my_config.has_option(section, 'urls'):
85             for entry in ([
86                     DDPortfolioEntry(my_config, section, url) for url in \
87                         my_config.get(section, 'urls').split(',')]):
88                 try:
89                     data.append(
90                         ['url', section, entry,
91                              my_config.get(section, entry.name + '.pattern',
92                                            False, qfields)])
93                 except InterpolationMissingOptionError, e:
94                     if not entry.optional:
95                         if e.reference in _FIELDNAMES_MAP:
96                             data.append(['error', section, entry,
97                                          _('Missing input: %s') % \
98                                              _(_FIELDNAMES_MAP[e.reference])])
99                         else:
100                             data.append(['error', section, entry,
101                                          _('Missing input: %s') % e.reference])
102     return data