Improving support for a worker thread and moving more code over to it
[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         OLDEST_MESSAGE_WINDOW = datetime.timedelta(days=60)
27
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
34
35                 self.updateSignalHandler = coroutines.CoTee()
36
37         @property
38         def _name(self):
39                 return repr(self._get_raw_conversations.__name__)
40
41         def load(self, path):
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                 else:
58                         _moduleLogger.debug(
59                                 "%s Skipping cache due to version mismatch (%s-%s)" % (
60                                         self._name, fileVersion, fileBuild
61                                 )
62                         )
63
64         def save(self, path):
65                 try:
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)
74
75         def update(self, force=False):
76                 if not force and self._conversations:
77                         return
78
79                 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
80                 le.start()
81
82         @misc_utils.log_exception(_moduleLogger)
83         def _update(self):
84                 conversationResult = yield (
85                         self._get_raw_conversations,
86                         (),
87                         {},
88                 )
89
90                 oldConversationIds = set(self._conversations.iterkeys())
91
92                 updateConversationIds = set()
93                 conversations = list(conversationResult)
94                 conversations.sort()
95                 for conversation in conversations:
96                         key = misc_utils.normalize_number(conversation.number)
97                         try:
98                                 mergedConversations = self._conversations[key]
99                         except KeyError:
100                                 mergedConversations = MergedConversations()
101                                 self._conversations[key] = mergedConversations
102
103                         if self._loadedFromCache or self._hasDoneUpdate:
104                                 markAllAsRead = False
105                         else:
106                                 markAllAsRead = True
107                         try:
108                                 mergedConversations.append_conversation(conversation, markAllAsRead)
109                                 isConversationUpdated = True
110                         except RuntimeError, e:
111                                 if False:
112                                         _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
113                                 isConversationUpdated = False
114
115                         if isConversationUpdated:
116                                 updateConversationIds.add(key)
117
118                 if updateConversationIds:
119                         message = (self, updateConversationIds, )
120                         self.updateSignalHandler.stage.send(message)
121                 self._hasDoneUpdate = True
122
123         def get_conversations(self):
124                 return self._conversations.iterkeys()
125
126         def get_conversation(self, key):
127                 return self._conversations[key]
128
129         def clear_conversation(self, key):
130                 try:
131                         del self._conversations[key]
132                 except KeyError:
133                         _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
134
135         def clear_all(self):
136                 self._conversations.clear()
137
138
139 class MergedConversations(object):
140
141         def __init__(self):
142                 self._conversations = []
143
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)
149
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
161                 if markAllAsRead:
162                         newConversation.isRead = True
163                 else:
164                         newConversation.isRead = False
165
166                 if newConversation.messages:
167                         # must not have had all items removed due to duplicates
168                         self._conversations.append(newConversation)
169
170         def to_dict(self):
171                 selfDict = {}
172                 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
173                 return selfDict
174
175         @property
176         def conversations(self):
177                 return self._conversations
178
179         def compress(self, timedelta):
180                 now = datetime.datetime.now()
181                 oldNumConvs = len(self._conversations)
182                 oldConvs = self._conversations
183                 self._conversations = [
184                         conv
185                         for conv in self._conversations
186                         if (now - conv.time) < timedelta
187                 ]
188                 newNumConvs = len(self._conversations)
189                 if oldNumConvs != newNumConvs:
190                         _moduleLogger.debug("Compressed conversations from %s to %s" % (oldNumConvs, newNumConvs))
191                 else:
192                         _moduleLogger.debug("Did not compress, %s" % (newNumConvs))
193
194         def _validate(self, newConversation):
195                 if not self._conversations:
196                         return
197
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),
202                         )
203
204                 if newConversation.time <= self._conversations[-1].time:
205                         raise RuntimeError("Conversations got out of order")
206
207         def _find_related_conversation(self, convId):
208                 similarConversations = (
209                         conversation
210                         for conversation in self._conversations
211                         if conversation.id == convId
212                 )
213                 return similarConversations
214
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)
219
220         def _remove_repeats(self, relatedConversation, newConversation):
221                 newConversationMessages = newConversation.messages
222                 newConversation.messages = [
223                         newMessage
224                         for newMessage in newConversationMessages
225                         if newMessage not in relatedConversation.messages
226                 ]
227                 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
228                         len(newConversationMessages) - len(newConversation.messages),
229                         newConversation.id,
230                         len(newConversation.messages),
231                         len(newConversationMessages),
232                 ))
233                 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
234
235
236 def filter_out_read(conversations):
237         return (
238                 conversation
239                 for conversation in conversations
240                 if not conversation.isRead and not conversation.isArchived
241         )
242
243
244 def is_message_from_self(message):
245         return message.whoFrom == "Me:"
246
247
248 def filter_out_self(conversations):
249         return (
250                 newConversation
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
255                 )
256         )
257
258
259 class FilterOutReported(object):
260
261         NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
262
263         def __init__(self):
264                 self._lastMessageTimestamp = self.NULL_TIMESTAMP
265
266         def get_last_timestamp(self):
267                 return self._lastMessageTimestamp
268
269         def __call__(self, conversations):
270                 filteredConversations = [
271                         conversation
272                         for conversation in conversations
273                         if self._lastMessageTimestamp < conversation.time
274                 ]
275                 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
276                         self._lastMessageTimestamp = filteredConversations[0].time
277                 return filteredConversations