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
59 "%s Skipping cache due to version mismatch (%s-%s)" % (
60 self._name, fileVersion, fileBuild
65 _moduleLogger.info("%s Saving cache" % (self._name, ))
66 if not self._conversations:
67 _moduleLogger.info("%s Odd, no conversations to cache. Did we never load the cache?" % (self._name, ))
71 dataToDump = (constants.__version__, constants.__build__, self._conversations)
72 with open(path, "wb") as f:
73 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
74 except (pickle.PickleError, IOError):
75 _moduleLogger.exception("While saving for %s" % self._name)
76 _moduleLogger.info("%s Cache saved" % (self._name, ))
78 def update(self, force=False):
79 if not force and self._conversations:
82 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
85 @misc_utils.log_exception(_moduleLogger)
88 conversationResult = yield (
89 self._get_raw_conversations,
94 _moduleLogger.exception("%s While updating conversations" % (self._name, ))
97 oldConversationIds = set(self._conversations.iterkeys())
99 updateConversationIds = set()
100 conversations = list(conversationResult)
102 for conversation in conversations:
103 key = misc_utils.normalize_number(conversation.number)
105 mergedConversations = self._conversations[key]
107 mergedConversations = MergedConversations()
108 self._conversations[key] = mergedConversations
110 if self._loadedFromCache or self._hasDoneUpdate:
111 markAllAsRead = False
115 mergedConversations.append_conversation(conversation, markAllAsRead)
116 isConversationUpdated = True
117 except RuntimeError, e:
119 _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
120 isConversationUpdated = False
122 if isConversationUpdated:
123 updateConversationIds.add(key)
125 for key in updateConversationIds:
126 mergedConv = self._conversations[key]
127 _moduleLogger.debug("%s \tUpdated %s" % (self._name, key))
128 for conv in mergedConv.conversations:
129 message = "%s \t\tUpdated %s (%r) %r %r %r" % (
130 self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
132 _moduleLogger.debug(message)
134 if updateConversationIds:
135 message = (self, updateConversationIds, )
136 self.updateSignalHandler.stage.send(message)
137 self._hasDoneUpdate = True
139 def get_conversations(self):
140 return self._conversations.iterkeys()
142 def get_conversation(self, key):
143 return self._conversations[key]
145 def clear_conversation(self, key):
147 del self._conversations[key]
149 _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
152 self._conversations.clear()
155 class MergedConversations(object):
158 self._conversations = []
160 def append_conversation(self, newConversation, markAllAsRead):
161 self._validate(newConversation)
162 for similarConversation in self._find_related_conversation(newConversation.id):
163 self._update_previous_related_conversation(similarConversation, newConversation)
164 self._remove_repeats(similarConversation, newConversation)
166 # HACK: Because GV marks all messages as read when you reply it has
167 # the following race:
168 # 1. Get all messages
169 # 2. Contact sends a text
170 # 3. User sends a text marking contacts text as read
171 # 4. Get all messages not returning text from step 2
172 # This isn't a problem for voicemails but we don't know(?( enough.
173 # So we hack around this by:
174 # * We cache to disk the history of messages sent/received
175 # * On first run we mark all server messages as read due to no cache
176 # * If not first load or from cache (disk or in-memory) then it must be unread
178 newConversation.isRead = True
180 newConversation.isRead = False
182 if newConversation.messages:
183 # must not have had all items removed due to duplicates
184 self._conversations.append(newConversation)
188 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
192 def conversations(self):
193 return self._conversations
195 def _validate(self, newConversation):
196 if not self._conversations:
199 for constantField in ("number", ):
200 assert getattr(self._conversations[0], constantField) == getattr(newConversation, constantField), "Constant field changed, soemthing is seriously messed up: %r v %r" % (
201 getattr(self._conversations[0], constantField),
202 getattr(newConversation, constantField),
205 if newConversation.time <= self._conversations[-1].time:
206 raise RuntimeError("Conversations got out of order")
208 def _find_related_conversation(self, convId):
209 similarConversations = (
211 for conversation in self._conversations
212 if conversation.id == convId
214 return similarConversations
216 def _update_previous_related_conversation(self, relatedConversation, newConversation):
217 for commonField in ("isSpam", "isTrash", "isArchived"):
218 newValue = getattr(newConversation, commonField)
219 setattr(relatedConversation, commonField, newValue)
221 def _remove_repeats(self, relatedConversation, newConversation):
222 newConversationMessages = newConversation.messages
223 newConversation.messages = [
225 for newMessage in newConversationMessages
226 if newMessage not in relatedConversation.messages
228 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
229 len(newConversationMessages) - len(newConversation.messages),
231 len(newConversation.messages),
232 len(newConversationMessages),
234 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
237 def filter_out_read(conversations):
240 for conversation in conversations
241 if not conversation.isRead and not conversation.isArchived
245 def is_message_from_self(message):
246 return message.whoFrom == "Me:"
249 def filter_out_self(conversations):
252 for newConversation in conversations
253 if len(newConversation.messages) and any(
254 not is_message_from_self(message)
255 for message in newConversation.messages
260 class FilterOutReported(object):
262 NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
265 self._lastMessageTimestamp = self.NULL_TIMESTAMP
267 def get_last_timestamp(self):
268 return self._lastMessageTimestamp
270 def __call__(self, conversations):
271 filteredConversations = [
273 for conversation in conversations
274 if self._lastMessageTimestamp < conversation.time
276 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
277 self._lastMessageTimestamp = filteredConversations[0].time
278 return filteredConversations