Bump to 0.8.12
[theonering] / src / channel / text.py
1 import time
2 import datetime
3 import logging
4
5 import telepathy
6
7 import tp
8 import util.coroutines as coroutines
9 import util.misc as misc_utils
10 import util.go_utils as gobject_utils
11 import gvoice
12
13
14 _moduleLogger = logging.getLogger(__name__)
15
16
17 class TextChannel(tp.ChannelTypeText):
18
19         OLDEST_MESSAGE_WINDOW = datetime.timedelta(days=1)
20
21         def __init__(self, connection, manager, props, contactHandle):
22                 self.__manager = manager
23                 self.__props = props
24
25                 tp.ChannelTypeText.__init__(self, connection, manager, props)
26                 self.__nextRecievedId = 0
27
28                 self.__otherHandle = contactHandle
29
30                 self.__callback = coroutines.func_sink(
31                         coroutines.expand_positional(
32                                 self._on_conversations_updated
33                         )
34                 )
35                 self._conn.session.voicemails.updateSignalHandler.register_sink(
36                         self.__callback
37                 )
38                 self._conn.session.texts.updateSignalHandler.register_sink(
39                         self.__callback
40                 )
41
42                 self._filter_out_reported = gvoice.conversations.FilterOutReported()
43
44                 # The only reason there should be anything in the conversation is if
45                 # its new, so report it all
46                 try:
47                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
48                 except KeyError:
49                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
50                 else:
51                         self._report_conversation(mergedConversations)
52                 try:
53                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
54                 except KeyError:
55                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
56                 else:
57                         self._report_conversation(mergedConversations)
58
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)
63
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)
68
69                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
70                 try:
71                         result = yield (
72                                 self._conn.session.backend.send_sms,
73                                 ([self.__otherHandle.phoneNumber], text),
74                                 {},
75                         )
76                 except Exception:
77                         _moduleLogger.exception(result)
78                         return
79
80                 self._conn.session.textsStateMachine.reset_timers()
81
82                 self.Sent(int(time.time()), messageType, text)
83
84         @misc_utils.log_exception(_moduleLogger)
85         def _on_send_sms_failed(self, error):
86                 _moduleLogger.error(error)
87
88         @misc_utils.log_exception(_moduleLogger)
89         def Close(self):
90                 self.close()
91
92         def close(self):
93                 _moduleLogger.debug("Closing text")
94                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
95                         self.__callback
96                 )
97                 self._conn.session.texts.updateSignalHandler.unregister_sink(
98                         self.__callback
99                 )
100                 self.__callback = None
101
102                 tp.ChannelTypeText.Close(self)
103                 self.remove_from_connection()
104
105         @property
106         def _contactKey(self):
107                 contactKey = self.__otherHandle.phoneNumber
108                 return contactKey
109
110         @misc_utils.log_exception(_moduleLogger)
111         def _on_conversations_updated(self, conv, conversationIds):
112                 if self._contactKey not in conversationIds:
113                         return
114                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
115                 mergedConversations = conv.get_conversation(self._contactKey)
116                 self._report_conversation(mergedConversations)
117
118         def _report_conversation(self, mergedConversations):
119                 newConversations = mergedConversations.conversations
120                 if not newConversations:
121                         _moduleLogger.info(
122                                 "No messages ended up existing for %r" % (self._contactKey, )
123                         )
124                         return
125
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                 newConversations = gvoice.conversations.filter_out_self(newConversations)
130                 newConversations = self._filter_out_reported(newConversations)
131                 newConversations = gvoice.conversations.filter_out_read(newConversations)
132                 newConversations = list(newConversations)
133                 if not newConversations:
134                         _moduleLogger.debug(
135                                 "New messages for %r have already been read externally" % (self._contactKey, )
136                         )
137                         return
138
139                 messages = [
140                         (newMessage, newConversation)
141                         for newConversation in newConversations
142                         for newMessage in newConversation.messages
143                         if not gvoice.conversations.is_message_from_self(newMessage)
144                 ]
145                 if not messages:
146                         _moduleLogger.debug(
147                                 "How did this happen for %r?" % (self._contactKey, )
148                         )
149                         return
150
151                 now = datetime.datetime.now()
152                 for newMessage, conv in messages:
153                         if self.OLDEST_MESSAGE_WINDOW < (now - conv.time):
154                                 _moduleLogger.warning("Why are we reporting a message that is so old?")
155                                 _moduleLogger.warning("\t%r %r (%r) with %r messages" % (conv.number, conv.id, conv.time, len(conv.messages)))
156                         formattedMessage = self._format_message(newMessage)
157                         self._report_new_message(formattedMessage, conv.time)
158
159                 for conv in mergedConversations.conversations:
160                         conv.isRead = True
161
162         def _format_message(self, message):
163                 return " ".join(part.text.strip() for part in message.body)
164
165         def _report_new_message(self, message, convTime):
166                 currentReceivedId = self.__nextRecievedId
167                 timestamp = time.mktime(convTime.timetuple())
168                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
169
170                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
171                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
172
173                 self.__nextRecievedId += 1