Switching to shipping parts of python-telepathy with The One Ring so random changes...
[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 gtk_toolbox
10
11
12 _moduleLogger = logging.getLogger("channel.text")
13
14
15 class TextChannel(tp.ChannelTypeText):
16         """
17         Look into implementing ChannelInterfaceMessages for rich text formatting
18         """
19
20         def __init__(self, connection, manager, props, contactHandle):
21                 self.__manager = manager
22                 self.__props = props
23
24                 tp.ChannelTypeText.__init__(self, connection, manager, props)
25                 self.__nextRecievedId = 0
26                 self.__lastMessageTimestamp = datetime.datetime(1, 1, 1)
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                 # The only reason there should be anything in the conversation is if
43                 # its new, so report it all
44                 try:
45                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
46                 except KeyError:
47                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
48                 else:
49                         self._report_conversation(mergedConversations)
50                 try:
51                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
52                 except KeyError:
53                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
54                 else:
55                         self._report_conversation(mergedConversations)
56
57         @gtk_toolbox.log_exception(_moduleLogger)
58         def Send(self, messageType, text):
59                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
60                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
61
62                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
63                 self._conn.session.backend.send_sms(self.__otherHandle.phoneNumber, text)
64                 self._conn.session.textsStateMachine.reset_timers()
65
66                 self.Sent(int(time.time()), messageType, text)
67
68         @gtk_toolbox.log_exception(_moduleLogger)
69         def Close(self):
70                 self.close()
71
72         def close(self):
73                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
74                         self.__callback
75                 )
76                 self._conn.session.texts.updateSignalHandler.unregister_sink(
77                         self.__callback
78                 )
79                 self.__callback = None
80
81                 tp.ChannelTypeText.Close(self)
82                 self.remove_from_connection()
83
84         @property
85         def _contactKey(self):
86                 contactKey = self.__otherHandle.contactID, self.__otherHandle.phoneNumber
87                 return contactKey
88
89         @gtk_toolbox.log_exception(_moduleLogger)
90         def _on_conversations_updated(self, conv, conversationIds):
91                 if self._contactKey not in conversationIds:
92                         return
93                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
94                 mergedConversations = conv.get_conversation(self._contactKey)
95                 self._report_conversation(mergedConversations)
96
97         def _report_conversation(self, mergedConversations):
98                 # Can't filter out messages in a texting conversation that came in
99                 # before the last one sent because that creates a race condition of two
100                 # people sending at about the same time, which happens quite a bit
101                 newConversations = mergedConversations.conversations
102                 if not newConversations:
103                         _moduleLogger.debug(
104                                 "No messages ended up existing for %r" % (self._contactKey, )
105                         )
106                         return
107                 newConversations = self._filter_out_reported(newConversations)
108                 newConversations = self._filter_out_read(newConversations)
109                 newConversations = list(newConversations)
110                 if not newConversations:
111                         _moduleLogger.debug(
112                                 "New messages for %r have already been read externally" % (self._contactKey, )
113                         )
114                         return
115                 self.__lastMessageTimestamp = newConversations[-1].time
116
117                 messages = [
118                         newMessage
119                         for newConversation in newConversations
120                         for newMessage in newConversation.messages
121                         if newMessage.whoFrom != "Me:"
122                 ]
123                 if not newConversations:
124                         _moduleLogger.debug(
125                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
126                         )
127                         return
128
129                 for newMessage in messages:
130                         formattedMessage = self._format_message(newMessage)
131                         self._report_new_message(formattedMessage)
132
133         def _filter_out_reported(self, conversations):
134                 return (
135                         conversation
136                         for conversation in conversations
137                         if self.__lastMessageTimestamp < conversation.time
138                 )
139
140         def _filter_out_read(self, conversations):
141                 return (
142                         conversation
143                         for conversation in conversations
144                         if not conversation.isRead and not conversation.isArchived
145                 )
146
147         def _format_message(self, message):
148                 return " ".join(part.text.strip() for part in message.body)
149
150         def _report_new_message(self, message):
151                 currentReceivedId = self.__nextRecievedId
152                 timestamp = int(time.time())
153                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
154
155                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
156                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
157
158                 self.__nextRecievedId += 1