Enabling logging to raise exceptions, hardening my exception handling, and tracking...
[theonering] / src / gvoice / conversations.py
1 #!/usr/bin/python
2
3 from __future__ import with_statement
4
5 import datetime
6 import logging
7
8 try:
9         import cPickle
10         pickle = cPickle
11 except ImportError:
12         import pickle
13
14 import constants
15 import util.coroutines as coroutines
16 import util.misc as misc_utils
17 import util.go_utils as gobject_utils
18
19
20 _moduleLogger = logging.getLogger(__name__)
21
22
23 class Conversations(object):
24
25         OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("0.8.0")
26
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
33
34                 self.updateSignalHandler = coroutines.CoTee()
35
36         @property
37         def _name(self):
38                 return repr(self._get_raw_conversations.__name__)
39
40         def load(self, path):
41                 _moduleLogger.debug("%s Loading cache" % (self._name, ))
42                 assert not self._conversations
43                 try:
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)
48                         return
49
50                 if misc_utils.compare_versions(
51                         self.OLDEST_COMPATIBLE_FORMAT_VERSION,
52                         misc_utils.parse_version(fileVersion),
53                 ) <= 0:
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)
62                                         )
63                                         _moduleLogger.debug(message)
64                 else:
65                         _moduleLogger.debug(
66                                 "%s Skipping cache due to version mismatch (%s-%s)" % (
67                                         self._name, fileVersion, fileBuild
68                                 )
69                         )
70
71         def save(self, path):
72                 _moduleLogger.info("%s Saving cache" % (self._name, ))
73                 try:
74                         dataToDump = (constants.__version__, constants.__build__, self._conversations)
75                         with open(path, "wb") as f:
76                                 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
77                 except (pickle.PickleError, IOError):
78                         _moduleLogger.exception("While saving for %s" % self._name)
79
80                 for key, mergedConv in self._conversations.iteritems():
81                         _moduleLogger.debug("%s \tSaving %s" % (self._name, key))
82                         for conv in mergedConv.conversations:
83                                 message = "%s \t\tSaving %s (%r) %r %r %r" % (
84                                         self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
85                                 )
86                                 _moduleLogger.debug(message)
87
88                 _moduleLogger.info("%s Cache saved" % (self._name, ))
89
90         def update(self, force=False):
91                 if not force and self._conversations:
92                         return
93
94                 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
95                 le.start()
96
97         @misc_utils.log_exception(_moduleLogger)
98         def _update(self):
99                 try:
100                         conversationResult = yield (
101                                 self._get_raw_conversations,
102                                 (),
103                                 {},
104                         )
105                 except Exception:
106                         _moduleLogger.exception("%s While updating conversations" % (self._name, ))
107                         return
108
109                 oldConversationIds = set(self._conversations.iterkeys())
110
111                 updateConversationIds = set()
112                 conversations = list(conversationResult)
113                 conversations.sort()
114                 for conversation in conversations:
115                         key = misc_utils.normalize_number(conversation.number)
116                         try:
117                                 mergedConversations = self._conversations[key]
118                         except KeyError:
119                                 mergedConversations = MergedConversations()
120                                 self._conversations[key] = mergedConversations
121
122                         if self._loadedFromCache or self._hasDoneUpdate:
123                                 markAllAsRead = False
124                         else:
125                                 markAllAsRead = True
126                         try:
127                                 mergedConversations.append_conversation(conversation, markAllAsRead)
128                                 isConversationUpdated = True
129                         except RuntimeError, e:
130                                 if False:
131                                         _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
132                                 isConversationUpdated = False
133
134                         if isConversationUpdated:
135                                 updateConversationIds.add(key)
136
137                 for key in updateConversationIds:
138                         mergedConv = self._conversations[key]
139                         _moduleLogger.debug("%s \tUpdated %s" % (self._name, key))
140                         for conv in mergedConv.conversations:
141                                 message = "%s \t\tUpdated %s (%r) %r %r %r" % (
142                                         self._name, conv.id, conv.time, conv.isRead, conv.isArchived, len(conv.messages)
143                                 )
144                                 _moduleLogger.debug(message)
145
146                 if updateConversationIds:
147                         message = (self, updateConversationIds, )
148                         self.updateSignalHandler.stage.send(message)
149                 self._hasDoneUpdate = True
150
151         def get_conversations(self):
152                 return self._conversations.iterkeys()
153
154         def get_conversation(self, key):
155                 return self._conversations[key]
156
157         def clear_conversation(self, key):
158                 try:
159                         del self._conversations[key]
160                 except KeyError:
161                         _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
162
163         def clear_all(self):
164                 self._conversations.clear()
165
166
167 class MergedConversations(object):
168
169         def __init__(self):
170                 self._conversations = []
171
172         def append_conversation(self, newConversation, markAllAsRead):
173                 self._validate(newConversation)
174                 for similarConversation in self._find_related_conversation(newConversation.id):
175                         self._update_previous_related_conversation(similarConversation, newConversation)
176                         self._remove_repeats(similarConversation, newConversation)
177
178                 # HACK: Because GV marks all messages as read when you reply it has
179                 # the following race:
180                 # 1. Get all messages
181                 # 2. Contact sends a text
182                 # 3. User sends a text marking contacts text as read
183                 # 4. Get all messages not returning text from step 2
184                 # This isn't a problem for voicemails but we don't know(?( enough.
185                 # So we hack around this by:
186                 # * We cache to disk the history of messages sent/received
187                 # * On first run we mark all server messages as read due to no cache
188                 # * If not first load or from cache (disk or in-memory) then it must be unread
189                 if markAllAsRead:
190                         newConversation.isRead = True
191                 else:
192                         newConversation.isRead = False
193
194                 if newConversation.messages:
195                         # must not have had all items removed due to duplicates
196                         self._conversations.append(newConversation)
197
198         def to_dict(self):
199                 selfDict = {}
200                 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
201                 return selfDict
202
203         @property
204         def conversations(self):
205                 return self._conversations
206
207         def _validate(self, newConversation):
208                 if not self._conversations:
209                         return
210
211                 for constantField in ("number", ):
212                         assert getattr(self._conversations[0], constantField) == getattr(newConversation, constantField), "Constant field changed, soemthing is seriously messed up: %r v %r" % (
213                                 getattr(self._conversations[0], constantField),
214                                 getattr(newConversation, constantField),
215                         )
216
217                 if newConversation.time <= self._conversations[-1].time:
218                         raise RuntimeError("Conversations got out of order")
219
220         def _find_related_conversation(self, convId):
221                 similarConversations = (
222                         conversation
223                         for conversation in self._conversations
224                         if conversation.id == convId
225                 )
226                 return similarConversations
227
228         def _update_previous_related_conversation(self, relatedConversation, newConversation):
229                 for commonField in ("isSpam", "isTrash", "isArchived"):
230                         newValue = getattr(newConversation, commonField)
231                         setattr(relatedConversation, commonField, newValue)
232
233         def _remove_repeats(self, relatedConversation, newConversation):
234                 newConversationMessages = newConversation.messages
235                 newConversation.messages = [
236                         newMessage
237                         for newMessage in newConversationMessages
238                         if newMessage not in relatedConversation.messages
239                 ]
240                 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
241                         len(newConversationMessages) - len(newConversation.messages),
242                         newConversation.id,
243                         len(newConversation.messages),
244                         len(newConversationMessages),
245                 ))
246                 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
247
248
249 def filter_out_read(conversations):
250         return (
251                 conversation
252                 for conversation in conversations
253                 if not conversation.isRead and not conversation.isArchived
254         )
255
256
257 def is_message_from_self(message):
258         return message.whoFrom == "Me:"
259
260
261 def filter_out_self(conversations):
262         return (
263                 newConversation
264                 for newConversation in conversations
265                 if len(newConversation.messages) and any(
266                         not is_message_from_self(message)
267                         for message in newConversation.messages
268                 )
269         )
270
271
272 class FilterOutReported(object):
273
274         NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
275
276         def __init__(self):
277                 self._lastMessageTimestamp = self.NULL_TIMESTAMP
278
279         def get_last_timestamp(self):
280                 return self._lastMessageTimestamp
281
282         def __call__(self, conversations):
283                 filteredConversations = [
284                         conversation
285                         for conversation in conversations
286                         if self._lastMessageTimestamp < conversation.time
287                 ]
288                 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
289                         self._lastMessageTimestamp = filteredConversations[0].time
290                 return filteredConversations