3 from __future__ import with_statement
15 import util.coroutines as coroutines
16 import util.misc as misc_utils
17 import util.go_utils as gobject_utils
20 _moduleLogger = logging.getLogger(__name__)
23 class Conversations(object):
25 OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("0.8.0")
26 OLDEST_MESSAGE_WINDOW = datetime.timedelta(days=60)
28 def __init__(self, getter, asyncPool):
29 self._get_raw_conversations = getter
30 self._asyncPool = asyncPool
31 self._conversations = {}
32 self._loadedFromCache = False
33 self._hasDoneUpdate = False
35 self.updateSignalHandler = coroutines.CoTee()
39 return repr(self._get_raw_conversations.__name__)
42 assert not self._conversations
44 with open(path, "rb") as f:
45 fileVersion, fileBuild, convs = pickle.load(f)
46 except (pickle.PickleError, IOError, EOFError, ValueError):
47 _moduleLogger.exception("While loading for %s" % self._name)
50 if misc_utils.compare_versions(
51 self.OLDEST_COMPATIBLE_FORMAT_VERSION,
52 misc_utils.parse_version(fileVersion),
54 _moduleLogger.info("%s Loaded cache" % (self._name, ))
55 self._conversations = convs
56 self._loadedFromCache = True
59 "%s Skipping cache due to version mismatch (%s-%s)" % (
60 self._name, fileVersion, fileBuild
66 _moduleLogger.info("%s Saving cache" % (self._name, ))
67 for conv in self._conversations.itervalues():
68 conv.compress(self.OLDEST_MESSAGE_WINDOW)
69 dataToDump = (constants.__version__, constants.__build__, self._conversations)
70 with open(path, "wb") as f:
71 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
72 except (pickle.PickleError, IOError):
73 _moduleLogger.exception("While saving for %s" % self._name)
75 def update(self, force=False):
76 if not force and self._conversations:
79 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
82 @misc_utils.log_exception(_moduleLogger)
84 conversationResult = yield (
85 self._get_raw_conversations,
90 oldConversationIds = set(self._conversations.iterkeys())
92 updateConversationIds = set()
93 conversations = list(conversationResult)
95 for conversation in conversations:
96 key = misc_utils.normalize_number(conversation.number)
98 mergedConversations = self._conversations[key]
100 mergedConversations = MergedConversations()
101 self._conversations[key] = mergedConversations
103 if self._loadedFromCache or self._hasDoneUpdate:
104 markAllAsRead = False
108 mergedConversations.append_conversation(conversation, markAllAsRead)
109 isConversationUpdated = True
110 except RuntimeError, e:
112 _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
113 isConversationUpdated = False
115 if isConversationUpdated:
116 updateConversationIds.add(key)
118 if updateConversationIds:
119 message = (self, updateConversationIds, )
120 self.updateSignalHandler.stage.send(message)
121 self._hasDoneUpdate = True
123 def get_conversations(self):
124 return self._conversations.iterkeys()
126 def get_conversation(self, key):
127 return self._conversations[key]
129 def clear_conversation(self, key):
131 del self._conversations[key]
133 _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
136 self._conversations.clear()
139 class MergedConversations(object):
142 self._conversations = []
144 def append_conversation(self, newConversation, markAllAsRead):
145 self._validate(newConversation)
146 for similarConversation in self._find_related_conversation(newConversation.id):
147 self._update_previous_related_conversation(similarConversation, newConversation)
148 self._remove_repeats(similarConversation, newConversation)
150 # HACK: Because GV marks all messages as read when you reply it has
151 # the following race:
152 # 1. Get all messages
153 # 2. Contact sends a text
154 # 3. User sends a text marking contacts text as read
155 # 4. Get all messages not returning text from step 2
156 # This isn't a problem for voicemails but we don't know(?( enough.
157 # So we hack around this by:
158 # * We cache to disk the history of messages sent/received
159 # * On first run we mark all server messages as read due to no cache
160 # * If not first load or from cache (disk or in-memory) then it must be unread
162 newConversation.isRead = True
164 newConversation.isRead = False
166 if newConversation.messages:
167 # must not have had all items removed due to duplicates
168 self._conversations.append(newConversation)
172 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
176 def conversations(self):
177 return self._conversations
179 def compress(self, timedelta):
180 now = datetime.datetime.now()
181 oldNumConvs = len(self._conversations)
182 oldConvs = self._conversations
183 self._conversations = [
185 for conv in self._conversations
186 if (now - conv.time) < timedelta
188 newNumConvs = len(self._conversations)
189 if oldNumConvs != newNumConvs:
190 _moduleLogger.debug("Compressed conversations from %s to %s" % (oldNumConvs, newNumConvs))
192 _moduleLogger.debug("Did not compress, %s" % (newNumConvs))
194 def _validate(self, newConversation):
195 if not self._conversations:
198 for constantField in ("number", ):
199 assert getattr(self._conversations[0], constantField) == getattr(newConversation, constantField), "Constant field changed, soemthing is seriously messed up: %r v %r" % (
200 getattr(self._conversations[0], constantField),
201 getattr(newConversation, constantField),
204 if newConversation.time <= self._conversations[-1].time:
205 raise RuntimeError("Conversations got out of order")
207 def _find_related_conversation(self, convId):
208 similarConversations = (
210 for conversation in self._conversations
211 if conversation.id == convId
213 return similarConversations
215 def _update_previous_related_conversation(self, relatedConversation, newConversation):
216 for commonField in ("isSpam", "isTrash", "isArchived"):
217 newValue = getattr(newConversation, commonField)
218 setattr(relatedConversation, commonField, newValue)
220 def _remove_repeats(self, relatedConversation, newConversation):
221 newConversationMessages = newConversation.messages
222 newConversation.messages = [
224 for newMessage in newConversationMessages
225 if newMessage not in relatedConversation.messages
227 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
228 len(newConversationMessages) - len(newConversation.messages),
230 len(newConversation.messages),
231 len(newConversationMessages),
233 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
236 def filter_out_read(conversations):
239 for conversation in conversations
240 if not conversation.isRead and not conversation.isArchived
244 def is_message_from_self(message):
245 return message.whoFrom == "Me:"
248 def filter_out_self(conversations):
251 for newConversation in conversations
252 if len(newConversation.messages) and any(
253 not is_message_from_self(message)
254 for message in newConversation.messages
259 class FilterOutReported(object):
261 NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
264 self._lastMessageTimestamp = self.NULL_TIMESTAMP
266 def get_last_timestamp(self):
267 return self._lastMessageTimestamp
269 def __call__(self, conversations):
270 filteredConversations = [
272 for conversation in conversations
273 if self._lastMessageTimestamp < conversation.time
275 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
276 self._lastMessageTimestamp = filteredConversations[0].time
277 return filteredConversations