Switching over to coroutine trampolines
[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.LinearExecution(self._send)
59                 le.start(messageType, text)
60
61         def _send(self, messageType, text, on_success, on_error):
62                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
63                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
64
65                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
66                 try:
67                         result = yield self._conn.session.pool.add_task, (
68                                 self._conn.session.backend.send_sms,
69                                 ([self.__otherHandle.phoneNumber], text),
70                                 {},
71                                 on_success,
72                                 on_error,
73                         ), {}
74                 except Exception:
75                         _moduleLogger.exception(result)
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                 newConversations = gvoice.conversations.filter_out_self(newConversations)
128                 newConversations = self._filter_out_reported(newConversations)
129                 newConversations = gvoice.conversations.filter_out_read(newConversations)
130                 newConversations = list(newConversations)
131                 if not newConversations:
132                         _moduleLogger.debug(
133                                 "New messages for %r have already been read externally" % (self._contactKey, )
134                         )
135                         return
136
137                 messages = [
138                         newMessage
139                         for newConversation in newConversations
140                         for newMessage in newConversation.messages
141                         if not gvoice.conversations.is_message_from_self(newMessage)
142                 ]
143                 if not messages:
144                         _moduleLogger.debug(
145                                 "How did this happen for %r?" % (self._contactKey, )
146                         )
147                         return
148                 for newMessage in messages:
149                         formattedMessage = self._format_message(newMessage)
150                         self._report_new_message(formattedMessage)
151
152                 for conv in newConversations:
153                         conv.isRead = True
154
155         def _format_message(self, message):
156                 return " ".join(part.text.strip() for part in message.body)
157
158         def _report_new_message(self, message):
159                 currentReceivedId = self.__nextRecievedId
160                 timestamp = int(time.time())
161                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
162
163                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
164                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
165
166                 self.__nextRecievedId += 1