Reducing log noise
[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 convs and 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                 _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, ))
68                         return
69
70                 try:
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, ))
77
78         def update(self, force=False):
79                 if not force and self._conversations:
80                         return
81
82                 le = gobject_utils.AsyncLinearExecution(self._asyncPool, self._update)
83                 le.start()
84
85         @misc_utils.log_exception(_moduleLogger)
86         def _update(self):
87                 try:
88                         conversationResult = yield (
89                                 self._get_raw_conversations,
90                                 (),
91                                 {},
92                         )
93                 except Exception:
94                         _moduleLogger.exception("%s While updating conversations" % (self._name, ))
95                         return
96
97                 oldConversationIds = set(self._conversations.iterkeys())
98
99                 updateConversationIds = set()
100                 conversations = list(conversationResult)
101                 conversations.sort()
102                 for conversation in conversations:
103                         key = misc_utils.normalize_number(conversation.number)
104                         try:
105                                 mergedConversations = self._conversations[key]
106                         except KeyError:
107                                 mergedConversations = MergedConversations()
108                                 self._conversations[key] = mergedConversations
109
110                         if self._loadedFromCache or self._hasDoneUpdate:
111                                 markAllAsRead = False
112                         else:
113                                 markAllAsRead = True
114                         try:
115                                 mergedConversations.append_conversation(conversation, markAllAsRead)
116                                 isConversationUpdated = True
117                         except RuntimeError, e:
118                                 if False:
119                                         _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
120                                 isConversationUpdated = False
121
122                         if isConversationUpdated:
123                                 updateConversationIds.add(key)
124
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)
131                                 )
132                                 _moduleLogger.debug(message)
133
134                 if updateConversationIds:
135                         message = (self, updateConversationIds, )
136                         self.updateSignalHandler.stage.send(message)
137                 self._hasDoneUpdate = True
138
139         def get_conversations(self):
140                 return self._conversations.iterkeys()
141
142         def get_conversation(self, key):
143                 return self._conversations[key]
144
145         def clear_conversation(self, key):
146                 try:
147                         del self._conversations[key]
148                 except KeyError:
149                         _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
150
151         def clear_all(self):
152                 self._conversations.clear()
153
154
155 class MergedConversations(object):
156
157         def __init__(self):
158                 self._conversations = []
159
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)
165
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
177                 if markAllAsRead:
178                         newConversation.isRead = True
179                 else:
180                         newConversation.isRead = False
181
182                 if newConversation.messages:
183                         # must not have had all items removed due to duplicates
184                         self._conversations.append(newConversation)
185
186         def to_dict(self):
187                 selfDict = {}
188                 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
189                 return selfDict
190
191         @property
192         def conversations(self):
193                 return self._conversations
194
195         def _validate(self, newConversation):
196                 if not self._conversations:
197                         return
198
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),
203                         )
204
205                 if newConversation.time <= self._conversations[-1].time:
206                         raise RuntimeError("Conversations got out of order")
207
208         def _find_related_conversation(self, convId):
209                 similarConversations = (
210                         conversation
211                         for conversation in self._conversations
212                         if conversation.id == convId
213                 )
214                 return similarConversations
215
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)
220
221         def _remove_repeats(self, relatedConversation, newConversation):
222                 newConversationMessages = newConversation.messages
223                 newConversation.messages = [
224                         newMessage
225                         for newMessage in newConversationMessages
226                         if newMessage not in relatedConversation.messages
227                 ]
228                 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
229                         len(newConversationMessages) - len(newConversation.messages),
230                         newConversation.id,
231                         len(newConversation.messages),
232                         len(newConversationMessages),
233                 ))
234                 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"
235
236
237 def filter_out_read(conversations):
238         return (
239                 conversation
240                 for conversation in conversations
241                 if not conversation.isRead and not conversation.isArchived
242         )
243
244
245 def is_message_from_self(message):
246         return message.whoFrom == "Me:"
247
248
249 def filter_out_self(conversations):
250         return (
251                 newConversation
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
256                 )
257         )
258
259
260 class FilterOutReported(object):
261
262         NULL_TIMESTAMP = datetime.datetime(1, 1, 1)
263
264         def __init__(self):
265                 self._lastMessageTimestamp = self.NULL_TIMESTAMP
266
267         def get_last_timestamp(self):
268                 return self._lastMessageTimestamp
269
270         def __call__(self, conversations):
271                 filteredConversations = [
272                         conversation
273                         for conversation in conversations
274                         if self._lastMessageTimestamp < conversation.time
275                 ]
276                 if filteredConversations and self._lastMessageTimestamp < filteredConversations[0].time:
277                         self._lastMessageTimestamp = filteredConversations[0].time
278                 return filteredConversations