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