94ae255d50d14d7bd80968f49c7e561763fbf301
[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 util.go_utils as gobject_utils
10 import gvoice
11
12
13 _moduleLogger = logging.getLogger(__name__)
14
15
16 class TextChannel(tp.ChannelTypeText):
17
18         def __init__(self, connection, manager, props, contactHandle):
19                 self.__manager = manager
20                 self.__props = props
21
22                 tp.ChannelTypeText.__init__(self, connection, manager, props)
23                 self.__nextRecievedId = 0
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                 le = gobject_utils.AsyncLinearExecution(self._conn.session.pool, self._send)
59                 le.start(messageType, text)
60
61         @misc_utils.log_exception(_moduleLogger)
62         def _send(self, messageType, text):
63                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
64                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
65
66                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
67                 try:
68                         result = yield (
69                                 self._conn.session.backend.send_sms,
70                                 ([self.__otherHandle.phoneNumber], text),
71                                 {},
72                         )
73                 except Exception:
74                         _moduleLogger.exception(result)
75                         return
76
77                 self._conn.session.textsStateMachine.reset_timers()
78
79                 self.Sent(int(time.time()), messageType, text)
80
81         @misc_utils.log_exception(_moduleLogger)
82         def _on_send_sms_failed(self, error):
83                 _moduleLogger.error(error)
84
85         @misc_utils.log_exception(_moduleLogger)
86         def Close(self):
87                 self.close()
88
89         def close(self):
90                 _moduleLogger.debug("Closing text")
91                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
92                         self.__callback
93                 )
94                 self._conn.session.texts.updateSignalHandler.unregister_sink(
95                         self.__callback
96                 )
97                 self.__callback = None
98
99                 tp.ChannelTypeText.Close(self)
100                 self.remove_from_connection()
101
102         @property
103         def _contactKey(self):
104                 contactKey = self.__otherHandle.phoneNumber
105                 return contactKey
106
107         @misc_utils.log_exception(_moduleLogger)
108         def _on_conversations_updated(self, conv, conversationIds):
109                 if self._contactKey not in conversationIds:
110                         return
111                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
112                 mergedConversations = conv.get_conversation(self._contactKey)
113                 self._report_conversation(mergedConversations)
114
115         def _report_conversation(self, mergedConversations):
116                 newConversations = mergedConversations.conversations
117                 if not newConversations:
118                         _moduleLogger.info(
119                                 "No messages ended up existing for %r" % (self._contactKey, )
120                         )
121                         return
122
123                 # Can't filter out messages in a texting conversation that came in
124                 # before the last one sent because that creates a race condition of two
125                 # people sending at about the same time, which happens quite a bit
126                 newConversations = gvoice.conversations.filter_out_self(newConversations)
127                 newConversations = self._filter_out_reported(newConversations)
128                 newConversations = gvoice.conversations.filter_out_read(newConversations)
129                 newConversations = list(newConversations)
130                 if not newConversations:
131                         _moduleLogger.debug(
132                                 "New messages for %r have already been read externally" % (self._contactKey, )
133                         )
134                         return
135
136                 messages = [
137                         (newMessage, newConversation.time)
138                         for newConversation in newConversations
139                         for newMessage in newConversation.messages
140                         if not gvoice.conversations.is_message_from_self(newMessage)
141                 ]
142                 if not messages:
143                         _moduleLogger.debug(
144                                 "How did this happen for %r?" % (self._contactKey, )
145                         )
146                         return
147                 for newMessage, convTime in messages:
148                         formattedMessage = self._format_message(newMessage)
149                         self._report_new_message(formattedMessage, convTime)
150
151                 for conv in mergedConversations.conversations:
152                         conv.isRead = True
153
154         def _format_message(self, message):
155                 return " ".join(part.text.strip() for part in message.body)
156
157         def _report_new_message(self, message, convTime):
158                 currentReceivedId = self.__nextRecievedId
159                 timestamp = time.mktime(convTime.timetuple())
160                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
161
162                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
163                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
164
165                 self.__nextRecievedId += 1