1 # -*- coding: UTF-8 -*- |
|
2 # Copyright (c) 2008 - 2010, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 |
|
5 """Virtual Mail Manager's MailLocation class to manage the mail_location |
|
6 for accounts.""" |
|
7 |
|
8 import re |
|
9 |
|
10 import VirtualMailManager.constants.ERROR as ERR |
|
11 from VirtualMailManager.errors import MailLocationError as MLE |
|
12 |
|
13 RE_MAILLOCATION = """^\w{1,20}$""" |
|
14 |
|
15 class MailLocation(object): |
|
16 """A wrapper class thats provide access to the maillocation table""" |
|
17 __slots__ = ('__id', '__maillocation', '_dbh') |
|
18 def __init__(self, dbh, mid=None, maillocation=None): |
|
19 """Creates a new MailLocation instance. |
|
20 |
|
21 Either mid or maillocation must be specified. |
|
22 |
|
23 Keyword arguments: |
|
24 dbh -- a pyPgSQL.PgSQL.connection |
|
25 mid -- the id of a maillocation (long) |
|
26 maillocation -- the value of the maillocation (str) |
|
27 """ |
|
28 self._dbh = dbh |
|
29 if mid is None and maillocation is None: |
|
30 raise MLE(_('Either mid or maillocation must be specified.'), |
|
31 ERR.MAILLOCATION_INIT) |
|
32 elif mid is not None: |
|
33 try: |
|
34 self.__id = long(mid) |
|
35 except ValueError: |
|
36 raise MLE(_('mid must be an int/long.'), ERR.MAILLOCATION_INIT) |
|
37 self._loadByID() |
|
38 else: |
|
39 if re.match(RE_MAILLOCATION, maillocation): |
|
40 self.__maillocation = maillocation |
|
41 self._loadByName() |
|
42 else: |
|
43 raise MLE( |
|
44 _(u'Invalid folder name ā%sā, it may consist only of\n\ |
|
45 1 - 20 single byte characters (A-Z, a-z, 0-9 and _).') % maillocation, |
|
46 ERR.MAILLOCATION_INIT) |
|
47 |
|
48 def _loadByID(self): |
|
49 dbc = self._dbh.cursor() |
|
50 dbc.execute('SELECT maillocation FROM maillocation WHERE mid = %s', |
|
51 self.__id) |
|
52 result = dbc.fetchone() |
|
53 dbc.close() |
|
54 if result is not None: |
|
55 self.__maillocation = result[0] |
|
56 else: |
|
57 raise MLE(_('Unknown mid specified.'), ERR.UNKNOWN_MAILLOCATION_ID) |
|
58 |
|
59 def _loadByName(self): |
|
60 dbc = self._dbh.cursor() |
|
61 dbc.execute('SELECT mid FROM maillocation WHERE maillocation = %s', |
|
62 self.__maillocation) |
|
63 result = dbc.fetchone() |
|
64 dbc.close() |
|
65 if result is not None: |
|
66 self.__id = result[0] |
|
67 else: |
|
68 self._save() |
|
69 |
|
70 def _save(self): |
|
71 dbc = self._dbh.cursor() |
|
72 dbc.execute("SELECT nextval('maillocation_id')") |
|
73 self.__id = dbc.fetchone()[0] |
|
74 dbc.execute('INSERT INTO maillocation(mid,maillocation) VALUES(%s,%s)', |
|
75 self.__id, self.__maillocation) |
|
76 self._dbh.commit() |
|
77 dbc.close() |
|
78 |
|
79 def getID(self): |
|
80 """Returns the unique ID of the maillocation.""" |
|
81 return self.__id |
|
82 |
|
83 def getMailLocation(self): |
|
84 """Returns the value of maillocation, ex: 'Maildir'""" |
|
85 return self.__maillocation |
|
86 |
|