1f15dbfe006b1b56cf415ae1e5291b9564a1b100
[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 gvoice
10
11
12 _moduleLogger = logging.getLogger(__name__)
13
14
15 class TextChannel(tp.ChannelTypeText):
16
17         def __init__(self, connection, manager, props, contactHandle):
18                 self.__manager = manager
19                 self.__props = props
20
21                 tp.ChannelTypeText.__init__(self, connection, manager, props)
22                 self.__nextRecievedId = 0
23
24                 self.__otherHandle = contactHandle
25
26                 self.__callback = coroutines.func_sink(
27                         coroutines.expand_positional(
28                                 self._on_conversations_updated
29                         )
30                 )
31                 self._conn.session.voicemails.updateSignalHandler.register_sink(
32                         self.__callback
33                 )
34                 self._conn.session.texts.updateSignalHandler.register_sink(
35                         self.__callback
36                 )
37
38                 self._filter_out_reported = gvoice.conversations.FilterOutReported()
39
40                 # The only reason there should be anything in the conversation is if
41                 # its new, so report it all
42                 try:
43                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
44                 except KeyError:
45                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
46                 else:
47                         self._report_conversation(mergedConversations)
48                 try:
49                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
50                 except KeyError:
51                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
52                 else:
53                         self._report_conversation(mergedConversations)
54
55         @misc_utils.log_exception(_moduleLogger)
56         def Send(self, messageType, text):
57                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
58                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
59
60                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
61                 self._conn.session.pool.add_task(
62                         self._conn.session.backend.send_sms,
63                         ([self.__otherHandle.phoneNumber], text),
64                         {},
65                         self._on_send_sms(messageType, text),
66                         self._on_send_sms_failed,
67                 )
68
69         def _on_send_sms(self, messageType, text):
70
71                 @misc_utils.log_exception(_moduleLogger)
72                 def _actual_on_send_sms(self, *args):
73                         self._conn.session.textsStateMachine.reset_timers()
74
75                         self.Sent(int(time.time()), messageType, text)
76
77                 return _actual_on_send_sms
78
79         @misc_utils.log_exception(_moduleLogger)
80         def _on_send_sms_failed(self, error):
81                 _moduleLogger.error(error)
82
83         @misc_utils.log_exception(_moduleLogger)
84         def Close(self):
85                 self.close()
86
87         def close(self):
88                 _moduleLogger.debug("Closing text")
89                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
90                         self.__callback
91                 )
92                 self._conn.session.texts.updateSignalHandler.unregister_sink(
93                         self.__callback
94                 )
95                 self.__callback = None
96
97                 tp.ChannelTypeText.Close(self)
98                 self.remove_from_connection()
99
100         @property
101         def _contactKey(self):
102                 contactKey = self.__otherHandle.phoneNumber
103                 return contactKey
104
105         @misc_utils.log_exception(_moduleLogger)
106         def _on_conversations_updated(self, conv, conversationIds):
107                 if self._contactKey not in conversationIds:
108                         return
109                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
110                 mergedConversations = conv.get_conversation(self._contactKey)
111                 self._report_conversation(mergedConversations)
112
113         def _report_conversation(self, mergedConversations):
114                 newConversations = mergedConversations.conversations
115                 if not newConversations:
116                         _moduleLogger.info(
117                                 "No messages ended up existing for %r" % (self._contactKey, )
118                         )
119                         return
120
121                 # Can't filter out messages in a texting conversation that came in
122                 # before the last one sent because that creates a race condition of two
123                 # people sending at about the same time, which happens quite a bit
124                 newConversations = gvoice.conversations.filter_out_self(newConversations)
125                 newConversations = self._filter_out_reported(newConversations)
126                 newConversations = gvoice.conversations.filter_out_read(newConversations)
127                 newConversations = list(newConversations)
128                 if not newConversations:
129                         _moduleLogger.debug(
130                                 "New messages for %r have already been read externally" % (self._contactKey, )
131                         )
132                         return
133
134                 messages = [
135                         newMessage
136                         for newConversation in newConversations
137                         for newMessage in newConversation.messages
138                         if not gvoice.conversations.is_message_from_self(newMessage)
139                 ]
140                 if not messages:
141                         _moduleLogger.debug(
142                                 "How did this happen for %r?" % (self._contactKey, )
143                         )
144                         return
145                 for newMessage in messages:
146                         formattedMessage = self._format_message(newMessage)
147                         self._report_new_message(formattedMessage)
148
149                 for conv in newConversations:
150                         conv.isRead = True
151
152         def _format_message(self, message):
153                 return " ".join(part.text.strip() for part in message.body)
154
155         def _report_new_message(self, message):
156                 currentReceivedId = self.__nextRecievedId
157                 timestamp = int(time.time())
158                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
159
160                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
161                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
162
163                 self.__nextRecievedId += 1