File: imapServer.py

package info (click to toggle)
roundup 1.2.1-10%2Betch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 4,764 kB
  • ctags: 3,756
  • sloc: python: 30,296; sh: 1,497; perl: 23; makefile: 22
file content (383 lines) | stat: -rw-r--r-- 14,159 bytes parent folder | download | duplicates (5)
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
#!/usr/bin/env python
"""\
This script is a wrapper around the mailgw.py script that exists in roundup.
It runs as service instead of running as a one-time shot.
It also connects to a secure IMAP server. The main reasons for this script are:

1) The roundup-mailgw script isn't designed to run as a server. It
    expects that you either run it by hand, and enter the password each
    time, or you supply the password on the command line. I prefer to
    run a server that I initialize with the password, and then it just
    runs. I don't want to have to pass it on the command line, so
    running through crontab isn't a possibility. (This wouldn't be a
    problem on a local machine running through a mailspool.)
2) mailgw.py somehow screws up SSL support so IMAP4_SSL doesn't work. So
    hopefully running that work outside of the mailgw will allow it to work.
3) I wanted to be able to check multiple projects at the same time.
    roundup-mailgw is only for 1 mailbox and 1 project.


*TODO*:
  For the first round, the program spawns a new roundup-mailgw for
  each imap message that it finds and pipes the result in. In the
  future it might be more practical to actually include the roundup
  files and run the appropriate commands using python.

*TODO*:
  Look into supporting a logfile instead of using 2>/logfile

*TODO*:
  Add an option for changing the uid/gid of the running process.
"""

import getpass
import logging
import imaplib
import optparse
import os
import re
import time

logging.basicConfig()
log = logging.getLogger('IMAPServer')

version = '0.1.2'

class RoundupMailbox:
    """This contains all the info about each mailbox.
    Username, Password, server, security, roundup database
    """
    def __init__(self, dbhome='', username=None, password=None, mailbox=None
        , server=None, protocol='imaps'):
        self.username = username
        self.password = password
        self.mailbox = mailbox
        self.server = server
        self.protocol = protocol
        self.dbhome = dbhome

        try:
            if not self.dbhome:
                self.dbhome = raw_input('Tracker home: ')
                if not os.path.exists(self.dbhome):
                    raise ValueError, 'Invalid home address: ' \
                        'directory "%s" does not exist.' % self.dbhome

            if not self.server:
                self.server = raw_input('Server: ')
                if not self.server:
                    raise ValueError, 'No Servername supplied'
                protocol = raw_input('protocol [imaps]? ')
                self.protocol = protocol

            if not self.username:
                self.username = raw_input('Username: ')
                if not self.username:
                    raise ValueError, 'Invalid Username'

            if not self.password:
                print 'For server %s, user %s' % (self.server, self.username)
                self.password = getpass.getpass()
                # password can be empty because it could be superceeded
                # by a later entry

            #if self.mailbox is None:
            #   self.mailbox = raw_input('Mailbox [INBOX]: ')
            #   # We allow an empty mailbox because that will
            #   # select the INBOX, whatever it is called

        except (KeyboardInterrupt, EOFError):
            raise ValueError, 'Canceled by User'

    def __str__(self):
        return 'Mailbox{ server:%(server)s, protocol:%(protocol)s, ' \
            'username:%(username)s, mailbox:%(mailbox)s, ' \
            'dbhome:%(dbhome)s }' % self.__dict__


# [als] class name is misleading.  this is imap client, not imap server
class IMAPServer:

    """IMAP mail gatherer.

    This class runs as a server process. It is configured with a list of
    mailboxes to connect to, along with the roundup database directories
    that correspond with each email address.  It then connects to each
    mailbox at a specified interval, and if there are new messages it
    reads them, and sends the result to the roundup.mailgw.

    *TODO*:
      Try to be smart about how you access the mailboxes so that you can
      connect once, and access multiple mailboxes and possibly multiple
      usernames.

    *NOTE*:
      This assumes that if you are using the same user on the same
      server, you are using the same password. (the last one supplied is
      used.) Empty passwords are ignored.  Only the last protocol
      supplied is used.
    """

    def __init__(self, pidfile=None, delay=5, daemon=False):
        #This is sorted by servername, then username, then mailboxes
        self.mailboxes = {}
        self.delay = float(delay)
        self.pidfile = pidfile
        self.daemon = daemon

    def setDelay(self, delay):
        self.delay = delay

    def addMailbox(self, mailbox):
        """ The linkage is as follows:
        servers -- users - mailbox:dbhome
        So there can be multiple servers, each with multiple users.
        Each username can be associated with multiple mailboxes.
        each mailbox is associated with 1 database home
        """
        log.info('Adding mailbox %s', mailbox)
        if not self.mailboxes.has_key(mailbox.server):
            self.mailboxes[mailbox.server] = {'protocol':'imaps', 'users':{}}
        server = self.mailboxes[mailbox.server]
        if mailbox.protocol:
            server['protocol'] = mailbox.protocol

        if not server['users'].has_key(mailbox.username):
            server['users'][mailbox.username] = {'password':'', 'mailboxes':{}}
        user = server['users'][mailbox.username]
        if mailbox.password:
            user['password'] = mailbox.password

        if user['mailboxes'].has_key(mailbox.mailbox):
            raise ValueError, 'Mailbox is already defined'

        user['mailboxes'][mailbox.mailbox] = mailbox.dbhome

    def _process(self, message, dbhome):
        """Actually process one of the email messages"""
        child = os.popen('roundup-mailgw %s' % dbhome, 'wb')
        child.write(message)
        child.close()
        #print message

    def _getMessages(self, serv, count, dbhome):
        """This assumes that you currently have a mailbox open, and want to
        process all messages that are inside.
        """
        for n in range(1, count+1):
            (t, data) = serv.fetch(n, '(RFC822)')
            if t == 'OK':
                self._process(data[0][1], dbhome)
                serv.store(n, '+FLAGS', r'(\Deleted)')

    def checkBoxes(self):
        """This actually goes out and does all the checking.
        Returns False if there were any errors, otherwise returns true.
        """
        noErrors = True
        for server in self.mailboxes:
            log.info('Connecting to server: %s', server)
            s_vals = self.mailboxes[server]

            try:
                for user in s_vals['users']:
                    u_vals = s_vals['users'][user]
                    # TODO: As near as I can tell, you can only
                    # login with 1 username for each connection to a server.
                    protocol = s_vals['protocol'].lower()
                    if protocol == 'imaps':
                        serv = imaplib.IMAP4_SSL(server)
                    elif protocol == 'imap':
                        serv = imaplib.IMAP4(server)
                    else:
                        raise ValueError, 'Unknown protocol %s' % protocol

                    password = u_vals['password']

                    try:
                        log.info('Connecting as user: %s', user)
                        serv.login(user, password)

                        for mbox in u_vals['mailboxes']:
                            dbhome = u_vals['mailboxes'][mbox]
                            log.info('Using mailbox: %s, home: %s',
                                mbox, dbhome)
                            #access a specific mailbox
                            if mbox:
                                (t, data) = serv.select(mbox)
                            else:
                                # Select the default mailbox (INBOX)
                                (t, data) = serv.select()
                            try:
                                nMessages = int(data[0])
                            except ValueError:
                                nMessages = 0

                            log.info('Found %s messages', nMessages)

                            if nMessages:
                                self._getMessages(serv, nMessages, dbhome)
                                serv.expunge()

                            # We are done with this mailbox
                            serv.close()
                    except:
                        log.exception('Exception with server %s user %s',
                            server, user)
                        noErrors = False

                    serv.logout()
                    serv.shutdown()
                    del serv
            except:
                log.exception('Exception while connecting to %s', server)
                noErrors = False
        return noErrors


    def makeDaemon(self):
        """Turn this process into a daemon.

        - make our parent PID 1

        Write our new PID to the pidfile.

        From A.M. Kuuchling (possibly originally Greg Ward) with
        modification from Oren Tirosh, and finally a small mod from me.
        Originally taken from roundup.scripts.roundup_server.py
        """
        log.info('Running as Daemon')
        # Fork once
        if os.fork() != 0:
            os._exit(0)

        # Create new session
        os.setsid()

        # Second fork to force PPID=1
        pid = os.fork()
        if pid:
            if self.pidfile:
                pidfile = open(self.pidfile, 'w')
                pidfile.write(str(pid))
                pidfile.close()
            os._exit(0)

    def run(self):
        """Run email gathering daemon.

        This spawns itself as a daemon, and then runs continually, just
        sleeping inbetween checks.  It is recommended that you run
        checkBoxes once first before you select run. That way you can
        know if there were any failures.
        """
        if self.daemon:
            self.makeDaemon()
        while True:

            time.sleep(self.delay * 60.0)
            log.info('Time: %s', time.strftime('%Y-%m-%d %H:%M:%S'))
            self.checkBoxes()

def getItems(s):
    """Parse a string looking for userame@server"""
    myRE = re.compile(
        r'((?P<protocol>[^:]+)://)?'#You can supply a protocol if you like
        r'('                        #The username part is optional
         r'(?P<username>[^:]+)'     #You can supply the password as
         r'(:(?P<password>.+))?'    #username:password@server
        r'@)?'
        r'(?P<server>[^/]+)'
        r'(/(?P<mailbox>.+))?$'
    )
    m = myRE.match(s)
    if m:
        return m.groupdict()
    else:
        return None

def main():
    """This is what is called if run at the prompt"""
    parser = optparse.OptionParser(
        version=('%prog ' + version),
        usage="""usage: %prog [options] (home server)...

So each entry has a home, and then the server configuration. Home is just
a path to the roundup issue tracker. The server is something of the form:

    imaps://user:password@server/mailbox

If you don't supply the protocol, imaps is assumed. Without user or
password, you will be prompted for them. The server must be supplied.
Without mailbox the INBOX is used.

Examples:
  %prog /home/roundup/trackers/test imaps://test@imap.example.com/test
  %prog /home/roundup/trackers/test imap.example.com \
/home/roundup/trackers/test2 imap.example.com/test2
"""
    )
    parser.add_option('-d', '--delay', dest='delay', type='float',
        metavar='<sec>', default=5,
        help="Set the delay between checks in minutes. (default 5)"
    )
    parser.add_option('-p', '--pid-file', dest='pidfile',
        metavar='<file>', default=None,
        help="The pid of the server process will be written to <file>"
    )
    parser.add_option('-n', '--no-daemon', dest='daemon',
        action='store_false', default=True,
        help="Do not fork into the background after running the first check."
    )
    parser.add_option('-v', '--verbose', dest='verbose',
        action='store_const', const=logging.INFO,
        help="Be more verbose in letting you know what is going on."
        " Enables informational messages."
    )
    parser.add_option('-V', '--very-verbose', dest='verbose',
        action='store_const', const=logging.DEBUG,
        help="Be very verbose in letting you know what is going on."
            " Enables debugging messages."
    )
    parser.add_option('-q', '--quiet', dest='verbose',
        action='store_const', const=logging.ERROR,
        help="Be less verbose. Ignores warnings, only prints errors."
    )
    parser.add_option('-Q', '--very-quiet', dest='verbose',
        action='store_const', const=logging.CRITICAL,
        help="Be much less verbose. Ignores warnings and errors."
            " Only print CRITICAL messages."
    )

    (opts, args) = parser.parse_args()
    if (len(args) == 0) or (len(args) % 2 == 1):
        parser.error('Invalid number of arguments. '
            'Each site needs a home and a server.')

    log.setLevel(opts.verbose)
    myServer = IMAPServer(delay=opts.delay, pidfile=opts.pidfile,
        daemon=opts.daemon)
    for i in range(0,len(args),2):
        home = args[i]
        server = args[i+1]
        if not os.path.exists(home):
            parser.error('Home: "%s" does not exist' % home)

        info = getItems(server)
        if not info:
            parser.error('Invalid server string: "%s"' % server)

        myServer.addMailbox(
            RoundupMailbox(dbhome=home, mailbox=info['mailbox']
            , username=info['username'], password=info['password']
            , server=info['server'], protocol=info['protocol']
            )
        )

    if myServer.checkBoxes():
        myServer.run()

if __name__ == '__main__':
    main()

# vim: et ft=python si sts=4 sw=4