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")
27 def __init__(self, getter, asyncPool):
28 self._get_raw_conversations = getter
29 self._asyncPool = asyncPool
30 self._conversations = {}
31 self._loadedFromCache = False
32 self._hasDoneUpdate = False
34 self.updateSignalHandler = coroutines.CoTee()
38 return repr(self._get_raw_conversations.__name__)
41 _moduleLogger.debug("%s Loading cache" % (self._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 convs and 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
57 for key, mergedConv in self._conversations.iteritems():
58 _moduleLogger.debug("%s \tLoaded %s" % (self._name, key))
59 for conv in mergedConv.conversations:
60 message = "%s \t\tLoaded %s (%r) %r %r %r" % (
61 self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
63 _moduleLogger.debug(message)
66 "%s Skipping cache due to version mismatch (%s-%s)" % (
67 self._name, fileVersion, fileBuild
72 _moduleLogger.info("%s Saving cache" % (self._name, ))
73 if not self._conversations:
74 _moduleLogger.info("%s Odd, no conversations to cache. Did we never load the cache?" % (self._name, ))
78 dataToDump = (constants.__version__, constants.__build__, self._conversations)
79 with open(path, "wb") as f:
80 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
81 except (pickle.PickleError, IOError):
82 _moduleLogger.exception("While saving for %s" % self._name)
84 for key, mergedConv in self._conversations.iteritems():
85 _moduleLogger.debug("%s \tSaving %s" % (self._name, key))
86 for conv in mergedConv.conversations:
87 message = "%s \t\tSaving %s (%r) %r %r %r" % (
88 self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
90 _moduleLogger.debug(message)
92 _moduleLogger.info("%s Cache saved" % (self._name, ))
94 def update(self, force=False):
95 if not force and self._conversations:
98 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
101 @misc_utils.log_exception(_moduleLogger)
104 conversationResult = yield (
105 self._get_raw_conversations,
110 _moduleLogger.exception("%s While updating conversations" % (self._name, ))
113 oldConversationIds = set(self._conversations.iterkeys())
115 updateConversationIds = set()
116 conversations = list(conversationResult)
118 for conversation in conversations:
119 key = misc_utils.normalize_number(conversation.number)
121 mergedConversations = self._conversations[key]
123 mergedConversations = MergedConversations()
124 self._conversations[key] = mergedConversations
126 if self._loadedFromCache or self._hasDoneUpdate:
127 markAllAsRead = False
131 mergedConversations.append_conversation(conversation, markAllAsRead)
132 isConversationUpdated = True
133 except RuntimeError, e:
135 _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
136 isConversationUpdated = False
138 if isConversationUpdated:
139 updateConversationIds.add(key)
141 for key in updateConversationIds:
142 mergedConv = self._conversations[key]
143 _moduleLogger.debug("%s \tUpdated %s" % (self._name, key))
144 for conv in mergedConv.conversations:
145 message = "%s \t\tUpdated %s (%r) %r %r %r" % (
146 self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
148 _moduleLogger.debug(message)
150 if updateConversationIds:
151 message = (self, updateConversationIds, )
152 self.updateSignalHandler.stage.send(message)
153 self._hasDoneUpdate = True
155 def get_conversations(self):
156 return self._conversations.iterkeys()
158 def get_conversation(self, key):
159 return self._conversations[key]
161 def clear_conversation(self, key):
163 del self._conversations[key]
165 _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
168 self._conversations.clear()
171 class MergedConversations(object):
174 self._conversations = []
176 def append_conversation(self, newConversation, markAllAsRead):
177 self._validate(newConversation)
178 for similarConversation in self._find_related_conversation(newConversation.id):
179 self._update_previous_related_conversation(similarConversation, newConversation)
180 self._remove_repeats(similarConversation, newConversation)
182 # HACK: Because GV marks all messages as read when you reply it has
183 # the following race:
184 # 1. Get all messages
185 # 2. Contact sends a text
186 # 3. User sends a text marking contacts text as read
187 # 4. Get all messages not returning text from step 2
188 # This isn't a problem for voicemails but we don't know(?( enough.
189 # So we hack around this by:
190 # * We cache to disk the history of messages sent/received
191 # * On first run we mark all server messages as read due to no cache
192 # * If not first load or from cache (disk or in-memory) then it must be unread
194 newConversation.isRead = True
196 newConversation.isRead = False
198 if newConversation.messages:
199 # must not have had all items removed due to duplicates
200 self._conversations.append(newConversation)
204 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
208 def conversations(self):
209 return self._conversations
211 def _validate(self, newConversation):
212 if not self._conversations:
215 for constantField in ("number", ):
216 assert getattr(self._conversations[0], constantField) == getattr(newConversation, constantField), "Constant field changed, soemthing is seriously messed up: %r v %r" % (
217 getattr(self._conversations[0], constantField),
218 getattr(newConversation, constantField),
221 if newConversation.time <= self._conversations[-1].time:
222 raise RuntimeError("Conversations got out of order")
224 def _find_related_conversation(self, convId):
225 similarConversations = (
227 for conversation in self._conversations
228 if conversation.id == convId
230 return similarConversations
232 def _update_previous_related_conversation(self, relatedConversation, newConversation):
233 for commonField in ("isSpam", "isTrash", "isArchived"):
234 newValue = getattr(newConversation, commonField)
235 setattr(relatedConversation, commonField, newValue)
237 def _remove_repeats(self, relatedConversation, newConversation):
238 newConversationMessages = newConversation.messages
239 newConversation.messages = [
241 for newMessage in newConversationMessages
242 if newMessage not in relatedConversation.messages
244 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
245 len(newConversationMessages) - len(newConversation.messages),
247 len(newConversation.messages),
248 len(newConversationMessages),
250 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
253 def filter_out_read(conversations):
256 for conversation in conversations
257 if not conversation.isRead and not conversation.isArchived
261 def is_message_from_self(message):
262 return message.whoFrom == "Me:"
265 def filter_out_self(conversations):
268 for newConversation in conversations
269 if len(newConversation.messages) and any(
270 not is_message_from_self(message)
271 for message in newConversation.messages
276 class FilterOutReported(object):
278 NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
281 self._lastMessageTimestamp = self.NULL_TIMESTAMP
283 def get_last_timestamp(self):
284 return self._lastMessageTimestamp
286 def __call__(self, conversations):
287 filteredConversations = [
289 for conversation in conversations
290 if self._lastMessageTimestamp < conversation.time
292 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
293 self._lastMessageTimestamp = filteredConversations[0].time
294 return filteredConversations