7fbe1ca637146aed4ddd3216d825b76761b00463
[theonering] / src / gvoice / conversations.py
1 #!/usr/bin/python
2
3 from __future__ import with_statement
4
5 import logging
6
7 try:
8         import cPickle
9         pickle = cPickle
10 except ImportError:
11         import pickle
12
13 import constants
14 import util.coroutines as coroutines
15 import util.misc as util_misc
16
17
18 _moduleLogger = logging.getLogger("gvoice.conversations")
19
20
21 class Conversations(object):
22
23         def __init__(self, getter):
24                 self._get_raw_conversations = getter
25                 self._conversations = {}
26
27                 self.updateSignalHandler = coroutines.CoTee()
28
29         @property
30         def _name(self):
31                 return repr(self._get_raw_conversations.__name__)
32
33         def load(self, path):
34                 assert not self._conversations
35                 try:
36                         with open(path, "rb") as f:
37                                 fileVersion, fileBuild, convs = pickle.load(f)
38                 except (pickle.PickleError, IOError):
39                         _moduleLogger.exception("While loading for %s" % self._name)
40                         return
41
42                 if fileVersion == constants.__version__ and fileBuild == constants.__build__:
43                         self._conversations = convs
44                 else:
45                         _moduleLogger.debug(
46                                 "%s Skipping cache due to version mismatch (%s-%s)" % (self._name, fileVersion, fileBuild)
47                         )
48
49         def save(self, path):
50                 try:
51                         dataToDump = (constants.__version__, constants.__build__, self._conversations)
52                         with open(path, "wb") as f:
53                                 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
54                 except (pickle.PickleError, IOError):
55                         _moduleLogger.exception("While saving for %s" % self._name)
56
57         def update(self, force=False):
58                 if not force and self._conversations:
59                         return
60
61                 oldConversationIds = set(self._conversations.iterkeys())
62
63                 updateConversationIds = set()
64                 conversations = list(self._get_raw_conversations())
65                 conversations.sort()
66                 for conversation in conversations:
67                         key = util_misc.normalize_number(conversation.number)
68                         try:
69                                 mergedConversations = self._conversations[key]
70                         except KeyError:
71                                 mergedConversations = MergedConversations()
72                                 self._conversations[key] = mergedConversations
73
74                         try:
75                                 mergedConversations.append_conversation(conversation)
76                                 isConversationUpdated = True
77                         except RuntimeError, e:
78                                 if False:
79                                         _moduleLogger.debug("%s Skipping conversation for %r because '%s'" % (self._name, key, e))
80                                 isConversationUpdated = False
81
82                         if isConversationUpdated:
83                                 updateConversationIds.add(key)
84
85                 if updateConversationIds:
86                         message = (self, updateConversationIds, )
87                         self.updateSignalHandler.stage.send(message)
88
89         def get_conversations(self):
90                 return self._conversations.iterkeys()
91
92         def get_conversation(self, key):
93                 return self._conversations[key]
94
95         def clear_conversation(self, key):
96                 try:
97                         del self._conversations[key]
98                 except KeyError:
99                         _moduleLogger.info("%s Conversation never existed for %r" % (self._name, key, ))
100
101         def clear_all(self):
102                 self._conversations.clear()
103
104
105 class MergedConversations(object):
106
107         def __init__(self):
108                 self._conversations = []
109
110         def append_conversation(self, newConversation):
111                 self._validate(newConversation)
112                 similarExist = False
113                 for similarConversation in self._find_related_conversation(newConversation.id):
114                         self._update_previous_related_conversation(similarConversation, newConversation)
115                         self._remove_repeats(similarConversation, newConversation)
116                         similarExist = True
117                 if similarExist:
118                         # Hack to reduce a race window with GV marking messages as read
119                         # because it thinks we replied when really we replied to the
120                         # previous message.  Clients of this code are expected to handle
121                         # this gracefully.  Other race conditions may exist but clients are
122                         # responsible for them
123                         if newConversation.messages:
124                                 newConversation.isRead = False
125                         else:
126                                 newConversation.isRead = True
127                 self._conversations.append(newConversation)
128
129         def to_dict(self):
130                 selfDict = {}
131                 selfDict["conversations"] = [conv.to_dict() for conv in self._conversations]
132                 return selfDict
133
134         @property
135         def conversations(self):
136                 return self._conversations
137
138         def _validate(self, newConversation):
139                 if not self._conversations:
140                         return
141
142                 for constantField in ("number", ):
143                         assert getattr(self._conversations[0], constantField) == getattr(newConversation, constantField), "Constant field changed, soemthing is seriously messed up: %r v %r" % (
144                                 getattr(self._conversations[0], constantField),
145                                 getattr(newConversation, constantField),
146                         )
147
148                 if newConversation.time <= self._conversations[-1].time:
149                         raise RuntimeError("Conversations got out of order")
150
151         def _find_related_conversation(self, convId):
152                 similarConversations = (
153                         conversation
154                         for conversation in self._conversations
155                         if conversation.id == convId
156                 )
157                 return similarConversations
158
159         def _update_previous_related_conversation(self, relatedConversation, newConversation):
160                 for commonField in ("isSpam", "isTrash", "isArchived"):
161                         newValue = getattr(newConversation, commonField)
162                         setattr(relatedConversation, commonField, newValue)
163
164         def _remove_repeats(self, relatedConversation, newConversation):
165                 newConversationMessages = newConversation.messages
166                 newConversation.messages = [
167                         newMessage
168                         for newMessage in newConversationMessages
169                         if newMessage not in relatedConversation.messages
170                 ]
171                 _moduleLogger.debug("Found %d new messages in conversation %s (%d/%d)" % (
172                         len(newConversationMessages) - len(newConversation.messages),
173                         newConversation.id,
174                         len(newConversation.messages),
175                         len(newConversationMessages),
176                 ))
177                 assert 0 < len(newConversation.messages), "Everything shouldn't have been removed"