Commit | Line | Data |
---|---|---|
c9da760a PD |
1 | ''' |
2 | fix_imap_internaldate.py - Fix the INTERNALDATE field on IMAP servers | |
3 | ||
4 | Copyright (c) 2012 Intra2net AG | |
5 | Author: Plamen Dimitrov | |
6 | ||
7 | This program is free software: you can redistribute it and/or modify | |
8 | it under the terms of the GNU General Public License as published by | |
9 | the Free Software Foundation, either version 3 of the License, or | |
10 | (at your option) any later version. | |
11 | ||
12 | This program is distributed in the hope that it will be useful, | |
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | GNU General Public License for more details. | |
c9da760a PD |
16 | ''' |
17 | ||
d0cfa9d0 | 18 | import sys |
c9da760a | 19 | import csv |
d0cfa9d0 PD |
20 | import argparse |
21 | # python version handling | |
22 | try: | |
23 | import configparser | |
24 | except ImportError: | |
25 | print("This module needs python version 3 or later.") | |
26 | sys.exit() | |
8fe4e3ff | 27 | import logging |
8a9d4c89 | 28 | from mail_date_parser import MailDateParser |
c9da760a | 29 | from mail_iterator import MailIterator |
8301e589 | 30 | from caching_data import CachingData |
c9da760a | 31 | |
6177b21d TJ |
32 | CONFIG_FILENAME = "fix_imap_internaldate.cfg" |
33 | LOG_FILENAME = "fix_imap_internaldate.log" | |
34 | CSV_FILENAME = "userdata.csv" | |
35 | ||
c9da760a | 36 | def main(): |
97bd6bea PD |
37 | """Interprets command arguments and initializes configuration and logger. |
38 | Then begins mail synchronization.""" | |
648f0037 | 39 | |
97bd6bea | 40 | # parse arguments |
648f0037 PD |
41 | parser = argparse.ArgumentParser(description="Fix the INTERNALDATE field on IMAP servers. " |
42 | "Small tool to fix the IMAP internaldate " | |
43 | "in case it's too much off compared to the last date " | |
44 | "stored in the received lines.") | |
45 | parser.add_argument('-u', '--update', dest='test_mode', action='store_false', | |
46 | default=True, help='update all e-mails and exit test mode') | |
c9da760a | 47 | |
8fe4e3ff | 48 | # config and logging setup |
c9da760a | 49 | config = load_configuration() |
8fe4e3ff | 50 | prepare_logger(config) |
97bd6bea | 51 | args = parser.parse_args() |
648f0037 | 52 | if(args.test_mode): |
f9fd9b29 | 53 | logging.info("Testing mode initiated. No message will be modified on the server.") |
648f0037 | 54 | else: |
f9fd9b29 | 55 | logging.info("Update mode initiated. Messages will be modified.") |
3b81023f | 56 | |
97bd6bea | 57 | # proceed to main functionality |
d0cfa9d0 PD |
58 | try: |
59 | synchronize_csv(config, args.test_mode) | |
60 | except KeyboardInterrupt: | |
61 | logging.info("Script was interrupted by the user.") | |
97bd6bea PD |
62 | |
63 | return | |
64 | ||
65 | def load_configuration(): | |
66 | """Loads the script configuration from a file or creates such.""" | |
67 | config = configparser.RawConfigParser() | |
6177b21d | 68 | success = config.read(CONFIG_FILENAME) |
97bd6bea PD |
69 | if(len(success)==0): |
70 | config.add_section('basic_settings') | |
71 | config.set('basic_settings', 'file_log_level', logging.INFO) | |
72 | config.set('basic_settings', 'console_log_level', logging.INFO) | |
73 | config.set('basic_settings', 'imap_server', 'imap.company.com') | |
74 | config.set('basic_settings', 'tolerance', 30) | |
6177b21d | 75 | with open(CONFIG_FILENAME, 'w') as configfile: |
97bd6bea | 76 | config.write(configfile) |
926e6e98 | 77 | configfile.write("# 0 NOTSET, 10 DEBUG, 20 INFO, 30 WARNING, 40 ERROR, 50 CRITICAL") |
97bd6bea PD |
78 | return config |
79 | ||
80 | def prepare_logger(config): | |
81 | """Sets up the logging functionality""" | |
6177b21d | 82 | |
97bd6bea | 83 | # reset the log |
6177b21d | 84 | with open(LOG_FILENAME, 'w'): |
97bd6bea | 85 | pass |
6177b21d | 86 | |
97bd6bea | 87 | # add basic configuration |
6177b21d | 88 | logging.basicConfig(filename=LOG_FILENAME, |
97bd6bea PD |
89 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
90 | level=config.getint('basic_settings', 'file_log_level')) | |
6177b21d | 91 | |
97bd6bea PD |
92 | # add a handler for a console output |
93 | console = logging.StreamHandler() | |
94 | console.setLevel(config.getint('basic_settings', 'console_log_level')) | |
95 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
96 | console.setFormatter(formatter) | |
97 | logging.getLogger('').addHandler(console) | |
98 | return | |
99 | ||
100 | def synchronize_csv(config, test_mode): | |
101 | """Iterates through csv list of users and synchronizes their messages.""" | |
102 | ||
103 | # initialize loop permanent data | |
104 | caching_data = CachingData() | |
105 | date_parser = MailDateParser() | |
c9da760a | 106 | server = config.get('basic_settings', 'imap_server') |
8fe4e3ff | 107 | tolerance = config.getint('basic_settings', 'tolerance') * 60 |
c9da760a | 108 | |
97bd6bea | 109 | # iterate through the users in the csv data |
6177b21d | 110 | user_reader = csv.DictReader(open(CSV_FILENAME, "r"), delimiter=',') |
c9da760a PD |
111 | for user in user_reader: |
112 | try: | |
113 | session = MailIterator(server, user['username'], user['password']) | |
114 | except UserWarning as ex: | |
115 | logging.error(ex) | |
116 | continue | |
117 | for mailbox in session: | |
118 | try: | |
7a1d4c35 | 119 | box = caching_data.retrieve_cached_mailbox(mailbox[0], mailbox[1], user['username']) |
c9da760a | 120 | mail_ids = session.fetch_messages() |
3b81023f | 121 | new_ids = box.synchronize(mail_ids, tolerance) |
6f2bc406 | 122 | logging.info("%s new messages out of %s found in %s.", len(new_ids), len(mail_ids), box.name) |
c9da760a PD |
123 | except UserWarning as ex: |
124 | logging.error(ex) | |
125 | continue | |
8301e589 | 126 | for mid in new_ids: |
c9da760a PD |
127 | try: |
128 | fetched_internal_date = session.fetch_internal_date(mid) | |
8a9d4c89 | 129 | internal_date = date_parser.extract_internal_date(fetched_internal_date) |
c9da760a | 130 | fetched_received_date = session.fetch_received_date(mid) |
8a9d4c89 | 131 | received_date = date_parser.extract_received_date(fetched_received_date) |
c9da760a | 132 | if(received_date==""): |
d5ccfbec | 133 | logging.debug("No received date could be found in message uid: %s - mailbox: %s - user: %s.", |
8a9d4c89 | 134 | mid.decode('iso-8859-1'), box.name, box.owner) |
7a1d4c35 | 135 | box.no_received_field += 1 |
c9da760a PD |
136 | continue |
137 | except UserWarning as ex: | |
138 | logging.error(ex) | |
139 | continue | |
8a9d4c89 | 140 | if(date_parser.compare_dates(received_date, internal_date, tolerance)): |
36f4d196 TJ |
141 | logging.warning("Date conflict found in message uid: %s - mailbox: %s - user: %s.\nInternal date %s is different from received date %s from RECEIVED header:\n%s.", |
142 | mid.decode('iso-8859-1'), box.name, box.owner, | |
143 | internal_date.strftime("%d %b %Y %H:%M:%S"), | |
144 | received_date.strftime("%d %b %Y %H:%M:%S"), | |
145 | fetched_received_date.split("Received:")[1]) | |
5a4bc5d8 | 146 | if(not test_mode): |
c9da760a | 147 | try: |
7a1d4c35 | 148 | session.update_message(mid, box.name, received_date) |
c9da760a PD |
149 | except UserWarning as ex: |
150 | logging.error(ex) | |
151 | continue | |
36f4d196 | 152 | |
8301e589 | 153 | # count total emails for every user and mailbox |
7a1d4c35 | 154 | box.date_conflicts += 1 |
36f4d196 | 155 | |
8301e589 | 156 | # if all messages were successfully fixed confirm caching |
97bd6bea | 157 | if(not test_mode): |
7a1d4c35 | 158 | box.confirm_change() |
6177b21d | 159 | |
08ba5736 PD |
160 | # final report on date conflicts |
161 | caching_data.report_conflicts() | |
8fe4e3ff PD |
162 | return |
163 | ||
c9da760a PD |
164 | if(__name__ == "__main__"): |
165 | main() |