77584bd51b9daa4401ce79be388da757e8d39f67
[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         @todo Look into implementing ChannelInterfaceMessages for rich text formatting
18
19         @bug Stopped working on Maemo 4.1
20         """
21
22         def __init__(self, connection, manager, props, contactHandle):
23                 self.__manager = manager
24                 self.__props = props
25
26                 tp.ChannelTypeText.__init__(self, connection, manager, props)
27                 self.__nextRecievedId = 0
28                 self.__lastMessageTimestamp = datetime.datetime(1, 1, 1)
29
30                 self.__otherHandle = contactHandle
31
32                 self.__callback = coroutines.func_sink(
33                         coroutines.expand_positional(
34                                 self._on_conversations_updated
35                         )
36                 )
37                 self._conn.session.voicemails.updateSignalHandler.register_sink(
38                         self.__callback
39                 )
40                 self._conn.session.texts.updateSignalHandler.register_sink(
41                         self.__callback
42                 )
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         @gtk_toolbox.log_exception(_moduleLogger)
60         def Send(self, messageType, text):
61                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
62                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
63
64                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
65                 self._conn.session.backend.send_sms(self.__otherHandle.phoneNumber, text)
66                 self._conn.session.textsStateMachine.reset_timers()
67
68                 self.Sent(int(time.time()), messageType, text)
69
70         @gtk_toolbox.log_exception(_moduleLogger)
71         def Close(self):
72                 self.close()
73
74         def close(self):
75                 _moduleLogger.debug("Closing text")
76                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
77                         self.__callback
78                 )
79                 self._conn.session.texts.updateSignalHandler.unregister_sink(
80                         self.__callback
81                 )
82                 self.__callback = None
83
84                 tp.ChannelTypeText.Close(self)
85                 self.remove_from_connection()
86
87         @property
88         def _contactKey(self):
89                 contactKey = self.__otherHandle.phoneNumber
90                 return contactKey
91
92         @gtk_toolbox.log_exception(_moduleLogger)
93         def _on_conversations_updated(self, conv, conversationIds):
94                 if self._contactKey not in conversationIds:
95                         return
96                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
97                 mergedConversations = conv.get_conversation(self._contactKey)
98                 self._report_conversation(mergedConversations)
99
100         def _report_conversation(self, mergedConversations):
101                 # Can't filter out messages in a texting conversation that came in
102                 # before the last one sent because that creates a race condition of two
103                 # people sending at about the same time, which happens quite a bit
104                 newConversations = mergedConversations.conversations
105                 if not newConversations:
106                         _moduleLogger.debug(
107                                 "No messages ended up existing for %r" % (self._contactKey, )
108                         )
109                         return
110                 newConversations = self._filter_out_reported(newConversations)
111                 newConversations = self._filter_out_read(newConversations)
112                 newConversations = list(newConversations)
113                 if not newConversations:
114                         _moduleLogger.debug(
115                                 "New messages for %r have already been read externally" % (self._contactKey, )
116                         )
117                         return
118                 self.__lastMessageTimestamp = newConversations[-1].time
119
120                 messages = [
121                         newMessage
122                         for newConversation in newConversations
123                         for newMessage in newConversation.messages
124                         if newMessage.whoFrom != "Me:"
125                 ]
126                 if not newConversations:
127                         _moduleLogger.debug(
128                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
129                         )
130                         return
131
132                 for newMessage in messages:
133                         formattedMessage = self._format_message(newMessage)
134                         self._report_new_message(formattedMessage)
135
136         def _filter_out_reported(self, conversations):
137                 return (
138                         conversation
139                         for conversation in conversations
140                         if self.__lastMessageTimestamp < conversation.time
141                 )
142
143         @staticmethod
144         def _filter_out_read(conversations):
145                 return (
146                         conversation
147                         for conversation in conversations
148                         if not conversation.isRead and not conversation.isArchived
149                 )
150
151         def _format_message(self, message):
152                 return " ".join(part.text.strip() for part in message.body)
153
154         def _report_new_message(self, message):
155                 currentReceivedId = self.__nextRecievedId
156                 timestamp = int(time.time())
157                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
158
159                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
160                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
161
162                 self.__nextRecievedId += 1