2 caching_data.py - The module contains the CachingData class.
4 Copyright (c) 2012 Intra2net AG
5 Author: Plamen Dimitrov
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.
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.
17 import os, platform, tempfile
20 from mailbox_state import MailboxState
22 CACHE_FILENAME = "message_cache.dat"
24 STATISTICS_FILENAME = "statistics.txt"
27 """This class is responsible for the caching of data."""
30 # integer for version of the cache
32 # boolean flag which indicates fallback mode of the cache
33 fallback_to_date_header = None
34 # dictionary of usernames as keys and dictionaries as values
35 # the second dictionaries have unique mailbox keys and mailboxes as values
38 def __init__(self, fallback_mode):
39 # open data file or create one and initialize date if not found
41 cachefile = open(CACHE_FILENAME, 'rb')
42 cache_info, self.data = pickle.load(cachefile)
43 cache_info = cache_info.split(' ')
44 self.version = cache_info[0]
45 if(self.version != CACHE_VERSION):
46 raise IOError("Cache file has version %s and the script version is %s" % (self.version, CACHE_VERSION))
47 self.fallback_to_date_header = cache_info[1]
48 if(self.fallback_to_date_header != str(fallback_mode)):
49 raise IOError("Cache file date fallback mode setting is different than current settings")
50 logging.info("Cache file %s loaded", CACHE_FILENAME)
51 logging.info("%s users found.", len(self.data))
52 except (IOError, ValueError) as ex:
53 logging.warning("Couldn't load cache file %s: %s", CACHE_FILENAME, ex)
54 logging.warning("DELETING CACHE")
55 self.version = CACHE_VERSION
56 stored_cache_info = self.version + ' ' + str(fallback_mode)
58 with open(CACHE_FILENAME, 'wb') as cachefile:
59 pickle.dump((stored_cache_info, self.data), cachefile)
62 # create temporary file first
63 location = os.path.dirname(CACHE_FILENAME)
64 file_descriptor, tmpname = tempfile.mkstemp(dir=location)
66 cachefile = os.fdopen(file_descriptor, 'wb')
68 # prepare data based on a save flag
70 for user in self.data:
72 for box_key in self.data[user]:
73 if(self.data[user][box_key].needs_save):
74 saved_data[user][box_key] = self.data[user][box_key]
75 logging.debug("The mailbox %s will be saved.", saved_data[user][box_key].name)
76 if(len(saved_data[user])==0):
78 logging.debug("The user %s will not be saved.", user)
79 self.data = saved_data
80 # avoid test mode or cases where nothing needs saving
81 if(len(saved_data)==0):
87 stored_cache_info = self.version + ' ' + self.fallback_to_date_header
88 pickle.dump((stored_cache_info, self.data), cachefile)
89 logging.debug("%s users stored.", len(self.data))
91 # handle windows non-atomic rename
92 if(platform.system()=='Windows'):
93 if(os.path.exists(CACHE_FILENAME)):
95 os.unlink(CACHE_FILENAME)
97 os.rename(tmpname, CACHE_FILENAME)
99 # clean up temporary file
103 logging.info("Wrote cache file %s", CACHE_FILENAME)
105 def retrieve_cached_mailbox(self, name, uidvalidity, user):
106 """Retrieve a cached mailbox or create it."""
107 box_key = name.strip('"') + uidvalidity
108 if(user not in self.data):
110 logging.debug("New user %s cached.", user)
111 if(box_key not in self.data[user]):
112 self.data[user][box_key] = MailboxState(name, uidvalidity, user)
113 logging.debug("New mailbox %s cached.", box_key)
114 return self.data[user][box_key]
116 def report_conflicts(self):
117 """Write a date conflicts report in a file."""
118 with open(STATISTICS_FILENAME, 'w') as statsfile:
119 owner_total_conflicts = {}
120 owner_total_missing = {}
121 for user in self.data:
122 statsfile.write("user: %s\n" % user)
123 owner_total_conflicts[user] = 0
124 owner_total_missing[user] = 0
125 for box_key in self.data[user]:
126 owner_total_conflicts[user] += self.data[user][box_key].date_conflicts
127 owner_total_missing[user] += self.data[user][box_key].no_received_field
128 statsfile.write("date conflicts: %-15.15s missing header: %-15.15s mailbox: %s\n"\
129 % (self.data[user][box_key].date_conflicts,
130 self.data[user][box_key].no_received_field,
131 self.data[user][box_key].name))
132 statsfile.write("date conflicts: %-15.15s missing header: %-15.15s TOTAL \n\n"\
133 % (owner_total_conflicts[user], owner_total_missing[user]))