Forcing calls to quit immediately rather than giving time to cancel to fix issues...
[theonering] / src / channel / text.py
1 import time
2 import datetime
3 import logging
4
5 import telepathy
6
7 import tp
8 import util.coroutines as coroutines
9 import util.misc as misc_utils
10 import util.go_utils as gobject_utils
11 import gvoice
12
13
14 _moduleLogger = logging.getLogger(__name__)
15
16
17 class TextChannel(tp.ChannelTypeText):
18
19         OLDEST_MESSAGE_WINDOW = datetime.timedelta(days=1)
20
21         def __init__(self, connection, manager, props, contactHandle):
22                 self.__manager = manager
23                 self.__props = props
24
25                 tp.ChannelTypeText.__init__(self, connection, manager, props)
26                 self.__nextRecievedId = 0
27
28                 self.__otherHandle = contactHandle
29
30                 self.__callback = coroutines.func_sink(
31                         coroutines.expand_positional(
32                                 self._on_conversations_updated
33                         )
34                 )
35                 self._conn.session.voicemails.updateSignalHandler.register_sink(
36                         self.__callback
37                 )
38                 self._conn.session.texts.updateSignalHandler.register_sink(
39                         self.__callback
40                 )
41
42                 # The only reason there should be anything in the conversation is if
43                 # its new, so report it all
44                 try:
45                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
46                 except KeyError:
47                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
48                 else:
49                         self._report_conversation(mergedConversations)
50                 try:
51                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
52                 except KeyError:
53                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
54                 else:
55                         self._report_conversation(mergedConversations)
56
57         @misc_utils.log_exception(_moduleLogger)
58         def Send(self, messageType, text):
59                 le = gobject_utils.AsyncLinearExecution(self._conn.session.pool, self._send)
60                 le.start(messageType, text)
61
62         @misc_utils.log_exception(_moduleLogger)
63         def _send(self, messageType, text):
64                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
65                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
66
67                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
68                 try:
69                         result = yield (
70                                 self._conn.session.backend.send_sms,
71                                 ([self.__otherHandle.phoneNumber], text),
72                                 {},
73                         )
74                 except Exception:
75                         _moduleLogger.exception("Oh no, what happened?")
76                         return
77
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 _on_send_sms_failed(self, error):
84                 _moduleLogger.error(error)
85
86         @misc_utils.log_exception(_moduleLogger)
87         def Close(self):
88                 self.close()
89
90         def close(self):
91                 _moduleLogger.debug("Closing text")
92                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
93                         self.__callback
94                 )
95                 self._conn.session.texts.updateSignalHandler.unregister_sink(
96                         self.__callback
97                 )
98                 self.__callback = None
99
100                 tp.ChannelTypeText.Close(self)
101                 self.remove_from_connection()
102
103         @property
104         def _contactKey(self):
105                 contactKey = self.__otherHandle.phoneNumber
106                 return contactKey
107
108         @misc_utils.log_exception(_moduleLogger)
109         def _on_conversations_updated(self, conv, conversationIds):
110                 if self._contactKey not in conversationIds:
111                         return
112                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
113                 mergedConversations = conv.get_conversation(self._contactKey)
114                 self._report_conversation(mergedConversations)
115
116         def _report_conversation(self, mergedConversations):
117                 newConversations = mergedConversations.conversations
118                 if not newConversations:
119                         _moduleLogger.info(
120                                 "No messages ended up existing for %r" % (self._contactKey, )
121                         )
122                         return
123
124                 # Can't filter out messages in a texting conversation that came in
125                 # before the last one sent because that creates a race condition of two
126                 # people sending at about the same time, which happens quite a bit
127                 postUpdateLen = len(newConversations)
128                 newConversations = gvoice.conversations.filter_out_self(newConversations)
129                 newConversations = list(newConversations)
130                 postSelfLen = len(newConversations)
131                 if postSelfLen < postUpdateLen:
132                         _moduleLogger.info("Dropped %s messages due to being from self" % (postUpdateLen - postSelfLen))
133                 if not newConversations:
134                         _moduleLogger.debug(
135                                 "New messages for %r are from yourself" % (self._contactKey, )
136                         )
137                         return
138
139                 newConversations = gvoice.conversations.filter_out_read(newConversations)
140                 newConversations = list(newConversations)
141                 postReadLen = len(newConversations)
142                 if postReadLen < postSelfLen:
143                         _moduleLogger.info("Dropped %s messages due to already being read" % (postSelfLen- postReadLen))
144                 if not newConversations:
145                         _moduleLogger.debug(
146                                 "New messages for %r have already been read externally" % (self._contactKey, )
147                         )
148                         return
149
150                 messages = [
151                         (newMessage, newConversation)
152                         for newConversation in newConversations
153                         for newMessage in newConversation.messages
154                         if not gvoice.conversations.is_message_from_self(newMessage)
155                 ]
156                 if not messages:
157                         _moduleLogger.debug(
158                                 "How did this happen for %r?" % (self._contactKey, )
159                         )
160                         return
161
162                 now = datetime.datetime.now()
163                 for newMessage, conv in messages:
164                         if self.OLDEST_MESSAGE_WINDOW < (now - conv.time):
165                                 _moduleLogger.warning("Why are we reporting a message that is so old?")
166                                 _moduleLogger.warning("\t%r %r (%r) with %r messages" % (conv.number, conv.id, conv.time, len(conv.messages)))
167                         formattedMessage = self._format_message(newMessage)
168                         self._report_new_message(formattedMessage, conv.time)
169
170                 for conv in mergedConversations.conversations:
171                         conv.isRead = True
172
173         def _format_message(self, message):
174                 return " ".join(part.text.strip() for part in message.body)
175
176         def _report_new_message(self, message, convTime):
177                 currentReceivedId = self.__nextRecievedId
178                 timestamp = time.mktime(convTime.timetuple())
179                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
180
181                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
182                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
183
184                 self.__nextRecievedId += 1