Updating TOR to use latest GV bindings from Dialcentral, particularly a bug fix is...
[theonering] / src / channel / text.py
1 import time
2 import logging
3
4 import telepathy
5
6 import tp
7 import util.coroutines as coroutines
8 import util.misc as misc_utils
9 import gvoice
10
11
12 _moduleLogger = logging.getLogger(__name__)
13
14
15 class TextChannel(tp.ChannelTypeText):
16
17         def __init__(self, connection, manager, props, contactHandle):
18                 self.__manager = manager
19                 self.__props = props
20
21                 tp.ChannelTypeText.__init__(self, connection, manager, props)
22                 self.__nextRecievedId = 0
23                 self.__hasServerBeenPolled = False
24
25                 self.__otherHandle = contactHandle
26
27                 self.__callback = coroutines.func_sink(
28                         coroutines.expand_positional(
29                                 self._on_conversations_updated
30                         )
31                 )
32                 self._conn.session.voicemails.updateSignalHandler.register_sink(
33                         self.__callback
34                 )
35                 self._conn.session.texts.updateSignalHandler.register_sink(
36                         self.__callback
37                 )
38
39                 self._filter_out_reported = gvoice.conversations.FilterOutReported()
40
41                 # The only reason there should be anything in the conversation is if
42                 # its new, so report it all
43                 try:
44                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
45                 except KeyError:
46                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
47                 else:
48                         self._report_conversation(mergedConversations)
49                 try:
50                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
51                 except KeyError:
52                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
53                 else:
54                         self._report_conversation(mergedConversations)
55
56         @misc_utils.log_exception(_moduleLogger)
57         def Send(self, messageType, text):
58                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
59                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
60
61                 if not self.__hasServerBeenPolled:
62                         # Hack: GV marks messages as read when they are replied to.  If GV
63                         # marks them as read than we ignore them.  So reduce the window for
64                         # them being marked as read.  Oh and Conversations already handles
65                         # it if the message was already part of a thread, so we can limit
66                         # this to if we are trying to start a thread.  You might say a
67                         # voicemail could be what is being replied to and that doesn't mean
68                         # anything.  Oh well.
69                         try:
70                                 self._conn.session.texts.update(force=True)
71                         except Exception:
72                                 _moduleLogger.exception(
73                                         "Update failed when proactively checking for texts"
74                                 )
75
76                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
77                 self._conn.session.backend.send_sms([self.__otherHandle.phoneNumber], text)
78                 self._conn.session.textsStateMachine.reset_timers()
79
80                 self.Sent(int(time.time()), messageType, text)
81
82         @misc_utils.log_exception(_moduleLogger)
83         def Close(self):
84                 self.close()
85
86         def close(self):
87                 _moduleLogger.debug("Closing text")
88                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
89                         self.__callback
90                 )
91                 self._conn.session.texts.updateSignalHandler.unregister_sink(
92                         self.__callback
93                 )
94                 self.__callback = None
95
96                 tp.ChannelTypeText.Close(self)
97                 self.remove_from_connection()
98
99         @property
100         def _contactKey(self):
101                 contactKey = self.__otherHandle.phoneNumber
102                 return contactKey
103
104         @misc_utils.log_exception(_moduleLogger)
105         def _on_conversations_updated(self, conv, conversationIds):
106                 if self._contactKey not in conversationIds:
107                         return
108                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
109                 mergedConversations = conv.get_conversation(self._contactKey)
110                 self._report_conversation(mergedConversations)
111
112         def _report_conversation(self, mergedConversations):
113                 newConversations = mergedConversations.conversations
114                 if not newConversations:
115                         _moduleLogger.info(
116                                 "No messages ended up existing for %r" % (self._contactKey, )
117                         )
118                         return
119
120                 # Can't filter out messages in a texting conversation that came in
121                 # before the last one sent because that creates a race condition of two
122                 # people sending at about the same time, which happens quite a bit
123                 newConversations = self._filter_out_reported(newConversations)
124                 newConversations = gvoice.conversations.filter_out_read(newConversations)
125                 newConversations = gvoice.conversations.filter_out_self(newConversations)
126                 newConversations = list(newConversations)
127                 if not newConversations:
128                         _moduleLogger.debug(
129                                 "New messages for %r have already been read externally" % (self._contactKey, )
130                         )
131                         return
132
133                 messages = [
134                         newMessage
135                         for newConversation in newConversations
136                         for newMessage in newConversation.messages
137                         if not gvoice.conversations.is_message_from_self(newMessage)
138                 ]
139                 if not messages:
140                         _moduleLogger.debug(
141                                 "How did this happen for %r?" % (self._contactKey, )
142                         )
143                         return
144                 for newMessage in messages:
145                         formattedMessage = self._format_message(newMessage)
146                         self._report_new_message(formattedMessage)
147
148                 for conv in newConversations:
149                         conv.isRead = True
150                 self.__hasServerBeenPolled = True
151
152         def _format_message(self, message):
153                 return " ".join(part.text.strip() for part in message.body)
154
155         def _report_new_message(self, message):
156                 currentReceivedId = self.__nextRecievedId
157                 timestamp = int(time.time())
158                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
159
160                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
161                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
162
163                 self.__nextRecievedId += 1