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 # The only reason there should be anything in the conversation is if
43 # its new, so report it all
45 mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
47 _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
49 self._report_conversation(mergedConversations)
51 mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
53 _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
55 self._report_conversation(mergedConversations)
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)
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)
67 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
70 self._conn.session.backend.send_sms,
71 ([self.__otherHandle.phoneNumber], text),
75 _moduleLogger.exception("Oh no, what happened?")
78 self._conn.session.textsStateMachine.reset_timers()
80 self.Sent(int(time.time()), messageType, text)
82 @misc_utils.log_exception(_moduleLogger)
83 def _on_send_sms_failed(self, error):
84 _moduleLogger.error(error)
86 @misc_utils.log_exception(_moduleLogger)
91 _moduleLogger.debug("Closing text")
92 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
95 self._conn.session.texts.updateSignalHandler.unregister_sink(
98 self.__callback = None
100 tp.ChannelTypeText.Close(self)
101 self.remove_from_connection()
104 def _contactKey(self):
105 contactKey = self.__otherHandle.phoneNumber
108 @misc_utils.log_exception(_moduleLogger)
109 def _on_conversations_updated(self, conv, conversationIds):
110 if self._contactKey not in conversationIds:
112 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
113 mergedConversations = conv.get_conversation(self._contactKey)
114 self._report_conversation(mergedConversations)
116 def _report_conversation(self, mergedConversations):
117 newConversations = mergedConversations.conversations
118 if not newConversations:
120 "No messages ended up existing for %r" % (self._contactKey, )
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 self._conn.log_to_user(__name__, "Dropped %s messages due to being from self" % (postUpdateLen - postSelfLen))
133 if not newConversations:
135 "New messages for %r are from yourself" % (self._contactKey, )
139 newConversations = gvoice.conversations.filter_out_read(newConversations)
140 newConversations = list(newConversations)
141 postReadLen = len(newConversations)
142 if postReadLen < postSelfLen:
143 self._conn.log_to_user(__name__, "Dropped %s messages due to already being read" % (postSelfLen- postReadLen))
144 if not newConversations:
146 "New messages for %r have already been read externally" % (self._contactKey, )
151 (newMessage, newConversation)
152 for newConversation in newConversations
153 for newMessage in newConversation.messages
154 if not gvoice.conversations.is_message_from_self(newMessage)
158 "How did this happen for %r?" % (self._contactKey, )
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)
170 for conv in mergedConversations.conversations:
173 def _format_message(self, message):
174 return " ".join(part.text.strip() for part in message.body)
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
181 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
182 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
184 self.__nextRecievedId += 1