Module docstrings specified and corrected
[imap-mark-seen] / src / imap_mark_seen.py
1 '''
2 imap_mark_seen.py - Tool to mark all e-mails as seen
3
4 Copyright (c) 2012 Intra2net AG
5 Author: Plamen Dimitrov and Thomas Jarosch
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.
16 '''
17 import logging
18 import argparse, getpass
19 from mail_iterator import MailIterator
20 from warnings_handler import WarningsHandler
21
22 # logging settings
23 LOG_FILENAME = "imap_mark_seen.log"
24 LOG_FILE_LEVEL = logging.DEBUG
25 LOG_SHELL_LEVEL = logging.INFO
26 LOG_UNCLEAN_EXIT_LEVEL = logging.WARNING
27
28 def main():
29     """Main function."""
30
31     # prepare configuration
32     args = configure_args()
33     warnings_handler = prepare_logger()
34     logging.info("Marking messages as seen from %s of %s", args.folder, args.user)
35     psw = getpass.getpass()
36
37     # prepare simple mail iterator and iterate throug mailboxes
38     session = MailIterator(args.server, args.user, psw)
39     total_messages = 0
40     for mailbox in session:
41         if args.folder != "all folders" and ("INBOX/" + args.folder) not in mailbox[2]:
42             continue
43         try:
44             mail_ids = session.fetch_messages()
45         except UserWarning as ex:
46             logging.error(ex)
47             continue
48         try:
49             if len(mail_ids) > 0:
50                 mail_id_range = min(mail_ids, key=int).decode('iso-8859-1') + ':' + max(mail_ids, key=int).decode('iso-8859-1')
51                 session.set_seen_messages(mail_id_range)
52                 total_messages += len(mail_ids)
53         except UserWarning as ex:
54             logging.error(ex)
55
56     logging.info("Finished marking %s messages as seen", total_messages)
57     logging.info("Exiting with code %s", warnings_handler.detected_problems)
58     return int(warnings_handler.detected_problems > 0)
59
60 def configure_args():
61     """Configure arguments and return them."""
62
63     # parse arguments
64     parser = argparse.ArgumentParser(description="Tool to mark messages as seen.")
65     parser.add_argument('-u', '--user', dest='user', action='store',
66                         required=True, help='mark all messages as seen for a single user')
67     parser.add_argument('-f', '--folder', dest='folder', action='store',
68                         default="all folders", help='only mark given folder as seen')
69     parser.add_argument('-s', '--server', dest='server', action='store',
70                         default="localhost", help='imap server name with default localhost')    
71     args = parser.parse_args()
72
73     return args
74
75 def prepare_logger():
76     """Sets up the logging functionality"""
77
78     # reset the log
79     with open(LOG_FILENAME, 'w'):
80         pass
81
82     # add basic configuration
83     logging.basicConfig(filename=LOG_FILENAME,
84                         format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
85                         level=LOG_FILE_LEVEL)
86
87     # add a handler for a console output
88     default_logger = logging.getLogger('')
89     console = logging.StreamHandler()
90     console.setLevel(LOG_SHELL_LEVEL)
91     formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
92     console.setFormatter(formatter)
93     default_logger.addHandler(console)
94
95     # add a handler for warnings counting
96     warnings_handler = WarningsHandler()
97     warnings_handler.setLevel(LOG_UNCLEAN_EXIT_LEVEL)
98     default_logger.addHandler(warnings_handler)
99
100     return warnings_handler
101
102 if __name__ == "__main__":
103     main()