First pylint validation
[imap-restore-mail] / file_iterator.py
CommitLineData
67e2ec02
PD
1'''
2restore-mail-inject.py - Tool to inject mails via IMAP
3
4Copyright (c) 2012 Intra2net AG
5'''
6
5737b10e 7import os
67e2ec02 8import re
f797b0fd 9import logging
67e2ec02
PD
10
11MAIL_FILENAME = re.compile("^[0-9]+\.$")
e42bd6a5
PD
12MBOXFILE_LINE = re.compile("^(.*?)\t(?:\d )?default[\t ](.*)$")
13ACL_STRING = re.compile("^(.*?)[\t ](.*?)\t(.*)$")
67e2ec02
PD
14
15class FileIterator:
16 """This class iterates through the e-mail files."""
17
18 # class attributes
67e2ec02
PD
19 # mailboxes created during file traversal
20 created_mailboxes = None
21 # mailboxes to update during file traversal
22 acl_mailboxes = None
23
e42bd6a5 24 def __init__(self):
67e2ec02 25 """Creates a connection and a user session."""
e42bd6a5
PD
26 self.created_mailboxes = []
27 self.acl_mailboxes = []
67e2ec02
PD
28 return
29
30 def __del__(self):
31 """Closes the connection and the user session."""
32 return
33
38f15e57
PD
34 @classmethod
35 def _message_read(cls, filename):
67e2ec02
PD
36 """Retrieves a message from the message file."""
37 try:
38 with open(filename, "r") as msgfile:
39 message = msgfile.read()
f797b0fd
PD
40 except IOError:
41 logging.warning("Could not open the e-mail file %s", filename)
42 raise
67e2ec02
PD
43 return message
44
38f15e57
PD
45 @classmethod
46 def load_mailbox_list(cls, mboxlistfile = ""):
47 """Load the list of mailboxes and acl rights for each from file."""
b0169e56 48 mboxdb = {}
e42bd6a5
PD
49 if mboxlistfile != "":
50 try:
51 with open(mboxlistfile, 'r') as acl_file:
52 for line in acl_file:
b0169e56 53 acls = {}
e42bd6a5 54 linedata = MBOXFILE_LINE.match(line).groups()
e42bd6a5 55 if len(linedata) == 0:
38f15e57 56 logging.warning("Illegal line in mailbox list dump: %s", line)
f797b0fd 57 continue
b0169e56 58 key = linedata[0]
e42bd6a5 59 aclstr = linedata[1]
b0169e56
PD
60
61 # loop through acl rights string and build dictionary of users and rights
e42bd6a5 62 while(aclstr != ""):
e42bd6a5
PD
63 acldata = ACL_STRING.match(aclstr).groups()
64 if len(acldata) == 0:
38f15e57 65 logging.error("Illegal acl string in mailbox list dump: %s", line)
f797b0fd 66 continue
e42bd6a5 67 aclstr = acldata[2]
38f15e57 68 acls[acldata[0]] = acldata[1]
b0169e56
PD
69
70 mboxdb[key] = acls
e42bd6a5 71 except IOError:
38f15e57 72 logging.warning("Could not open mboxlist file %s", mboxlistfile)
e42bd6a5
PD
73 return mboxdb
74
67e2ec02
PD
75 def load_mails(self, filepath, mailpath):
76 """Loads all e-mails from file hierarchy.
77 This recursive generator always returns a tuple of
78 the next found (e-mail, mailbox to store, internaldate)."""
38f15e57 79 logging.debug("Entered directory %s -> %s", filepath, mailpath)
67e2ec02
PD
80 try:
81 filepath = os.path.abspath(filepath)
82 os.chdir(filepath)
83 except OSError:
38f15e57 84 logging.warning("Can't open the directory %s", filepath)
67e2ec02
PD
85 return
86 # mark mailboxes that should be created
87 self.created_mailboxes.append(mailpath)
88 subpaths = os.listdir(filepath)
89 for subpath in subpaths:
e42bd6a5 90 if subpath == "." or subpath == "..":
67e2ec02
PD
91 continue
92 new_filepath = filepath + "/" + subpath
93 if (os.path.isfile(new_filepath)):
e42bd6a5 94 if os.path.getsize(new_filepath) == 0:
38f15e57 95 logging.info("Skipping empty file %s", subpath)
67e2ec02 96 else:
e42bd6a5 97 if MAIL_FILENAME.match(subpath):
38f15e57 98 logging.info("Injecting file %s", subpath)
67e2ec02
PD
99 try:
100 message = self._message_read(new_filepath)
101 # suggest file modification date for internaldate
102 yield (message, mailpath, os.path.getmtime(new_filepath))
f797b0fd 103 except IOError:
38f15e57 104 logging.warning("Could not retrieve mail from the file %s", new_filepath)
67e2ec02 105 else:
e42bd6a5 106 if os.path.isdir(new_filepath):
67e2ec02
PD
107 # cyrus ^ vs . storage replacement
108 subpath = subpath.replace("^", ".")
109 new_mailpath = mailpath + "/" + subpath
38f15e57 110 logging.debug("Inserting mails from directory %s into mailbox %s", new_filepath, new_mailpath)
67e2ec02
PD
111 # load_mails($mboxdbref, $origuser, $targetuser)
112 rcrs_generator = self.load_mails(new_filepath, new_mailpath)
113 # you enter the generator in the for loop
114 for rcr in rcrs_generator:
115 yield rcr
38f15e57 116 logging.debug("Done with directory %s and mailbox %s", new_filepath, new_mailpath)
67e2ec02
PD
117 # mark mailboxes that need acl update
118 self.acl_mailboxes.append(mailpath)
b2bbd1f5 119 return