8 import util.coroutines as coroutines
9 import util.misc as misc_utils
10 import util.go_utils as gobject_utils
14 _moduleLogger = logging.getLogger(__name__)
17 class TextChannel(tp.ChannelTypeText):
19 OLDEST_MESSAGE_WINDOW = datetime.timedelta(days=1)
21 def __init__(self, connection, manager, props, contactHandle):
22 self.__manager = manager
25 tp.ChannelTypeText.__init__(self, connection, manager, props)
26 self.__nextRecievedId = 0
28 self.__otherHandle = contactHandle
30 self.__callback = coroutines.func_sink(
31 coroutines.expand_positional(
32 self._on_conversations_updated
35 self._conn.session.voicemails.updateSignalHandler.register_sink(
38 self._conn.session.texts.updateSignalHandler.register_sink(
42 self._filter_out_reported = gvoice.conversations.FilterOutReported()
44 # The only reason there should be anything in the conversation is if
45 # its new, so report it all
47 mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
49 _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
51 self._report_conversation(mergedConversations)
53 mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
55 _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
57 self._report_conversation(mergedConversations)
59 @misc_utils.log_exception(_moduleLogger)
60 def Send(self, messageType, text):
61 le = gobject_utils.AsyncLinearExecution(self._conn.session.pool, self._send)
62 le.start(messageType, text)
64 @misc_utils.log_exception(_moduleLogger)
65 def _send(self, messageType, text):
66 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
67 raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
69 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
72 self._conn.session.backend.send_sms,
73 ([self.__otherHandle.phoneNumber], text),
77 _moduleLogger.exception(result)
80 self._conn.session.textsStateMachine.reset_timers()
82 self.Sent(int(time.time()), messageType, text)
84 @misc_utils.log_exception(_moduleLogger)
85 def _on_send_sms_failed(self, error):
86 _moduleLogger.error(error)
88 @misc_utils.log_exception(_moduleLogger)
93 _moduleLogger.debug("Closing text")
94 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
97 self._conn.session.texts.updateSignalHandler.unregister_sink(
100 self.__callback = None
102 tp.ChannelTypeText.Close(self)
103 self.remove_from_connection()
106 def _contactKey(self):
107 contactKey = self.__otherHandle.phoneNumber
110 @misc_utils.log_exception(_moduleLogger)
111 def _on_conversations_updated(self, conv, conversationIds):
112 if self._contactKey not in conversationIds:
114 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
115 mergedConversations = conv.get_conversation(self._contactKey)
116 self._report_conversation(mergedConversations)
118 def _report_conversation(self, mergedConversations):
119 newConversations = mergedConversations.conversations
120 if not newConversations:
122 "No messages ended up existing for %r" % (self._contactKey, )
126 # Can't filter out messages in a texting conversation that came in
127 # before the last one sent because that creates a race condition of two
128 # people sending at about the same time, which happens quite a bit
129 postUpdateLen = len(newConversations)
130 newConversations = gvoice.conversations.filter_out_self(newConversations)
131 newConversations = list(newConversations)
132 postSelfLen = len(newConversations)
133 if postSelfLen < postUpdateLen:
134 self._conn.log_to_user(__name__, "Dropped %s messages due to being from self" % (postUpdateLen - postSelfLen))
135 if not newConversations:
137 "New messages for %r are from yourself" % (self._contactKey, )
141 newConversations = self._filter_out_reported(newConversations)
142 newConversations = list(newConversations)
143 postReportedLen = len(newConversations)
144 if postReportedLen < postSelfLen:
145 self._conn.log_to_user(__name__, "Dropped %s messages due to already being reported" % (postSelfLen - postReportedLen))
146 if not newConversations:
148 "New messages for %r have already been reported" % (self._contactKey, )
152 newConversations = gvoice.conversations.filter_out_read(newConversations)
153 newConversations = list(newConversations)
154 postReadLen = len(newConversations)
155 if postReadLen < postReportedLen:
156 self._conn.log_to_user(__name__, "Dropped %s messages due to already being read" % (postReportedLen - postReadLen))
157 if not newConversations:
159 "New messages for %r have already been read externally" % (self._contactKey, )
164 (newMessage, newConversation)
165 for newConversation in newConversations
166 for newMessage in newConversation.messages
167 if not gvoice.conversations.is_message_from_self(newMessage)
171 "How did this happen for %r?" % (self._contactKey, )
175 now = datetime.datetime.now()
176 for newMessage, conv in messages:
177 if self.OLDEST_MESSAGE_WINDOW < (now - conv.time):
178 _moduleLogger.warning("Why are we reporting a message that is so old?")
179 _moduleLogger.warning("\t%r %r (%r) with %r messages" % (conv.number, conv.id, conv.time, len(conv.messages)))
180 formattedMessage = self._format_message(newMessage)
181 self._report_new_message(formattedMessage, conv.time)
183 for conv in mergedConversations.conversations:
186 def _format_message(self, message):
187 return " ".join(part.text.strip() for part in message.body)
189 def _report_new_message(self, message, convTime):
190 currentReceivedId = self.__nextRecievedId
191 timestamp = time.mktime(convTime.timetuple())
192 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
194 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
195 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
197 self.__nextRecievedId += 1