Removing @todo/@bugs because we are now on bugs.maemo.org
[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         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                 self.__lastMessageTimestamp = datetime.datetime(1, 1, 1)
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                 # The only reason there should be anything in the conversation is if
40                 # its new, so report it all
41                 try:
42                         mergedConversations = self._conn.session.voicemails.get_conversation(self._contactKey)
43                 except KeyError:
44                         _moduleLogger.debug("No voicemails in the conversation yet for %r" % (self._contactKey, ))
45                 else:
46                         self._report_conversation(mergedConversations)
47                 try:
48                         mergedConversations = self._conn.session.texts.get_conversation(self._contactKey)
49                 except KeyError:
50                         _moduleLogger.debug("No texts conversation yet for %r" % (self._contactKey, ))
51                 else:
52                         self._report_conversation(mergedConversations)
53
54         @gtk_toolbox.log_exception(_moduleLogger)
55         def Send(self, messageType, text):
56                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
57                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
58
59                 _moduleLogger.info("Sending message to %r" % (self.__otherHandle, ))
60                 self._conn.session.backend.send_sms(self.__otherHandle.phoneNumber, text)
61                 self._conn.session.textsStateMachine.reset_timers()
62
63                 self.Sent(int(time.time()), messageType, text)
64
65         @gtk_toolbox.log_exception(_moduleLogger)
66         def Close(self):
67                 self.close()
68
69         def close(self):
70                 _moduleLogger.debug("Closing text")
71                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
72                         self.__callback
73                 )
74                 self._conn.session.texts.updateSignalHandler.unregister_sink(
75                         self.__callback
76                 )
77                 self.__callback = None
78
79                 tp.ChannelTypeText.Close(self)
80                 self.remove_from_connection()
81
82         @property
83         def _contactKey(self):
84                 contactKey = self.__otherHandle.phoneNumber
85                 return contactKey
86
87         @gtk_toolbox.log_exception(_moduleLogger)
88         def _on_conversations_updated(self, conv, conversationIds):
89                 if self._contactKey not in conversationIds:
90                         return
91                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
92                 mergedConversations = conv.get_conversation(self._contactKey)
93                 self._report_conversation(mergedConversations)
94
95         def _report_conversation(self, mergedConversations):
96                 # Can't filter out messages in a texting conversation that came in
97                 # before the last one sent because that creates a race condition of two
98                 # people sending at about the same time, which happens quite a bit
99                 newConversations = mergedConversations.conversations
100                 if not newConversations:
101                         _moduleLogger.debug(
102                                 "No messages ended up existing for %r" % (self._contactKey, )
103                         )
104                         return
105                 newConversations = self._filter_out_reported(newConversations)
106                 newConversations = self._filter_out_read(newConversations)
107                 newConversations = list(newConversations)
108                 if not newConversations:
109                         _moduleLogger.debug(
110                                 "New messages for %r have already been read externally" % (self._contactKey, )
111                         )
112                         return
113                 self.__lastMessageTimestamp = newConversations[-1].time
114
115                 messages = [
116                         newMessage
117                         for newConversation in newConversations
118                         for newMessage in newConversation.messages
119                         if newMessage.whoFrom != "Me:"
120                 ]
121                 if not newConversations:
122                         _moduleLogger.debug(
123                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
124                         )
125                         return
126
127                 for newMessage in messages:
128                         formattedMessage = self._format_message(newMessage)
129                         self._report_new_message(formattedMessage)
130                 for conv in newConversations:
131                         conv.isRead = True
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         @staticmethod
141         def _filter_out_read(conversations):
142                 return (
143                         conversation
144                         for conversation in conversations
145                         if not conversation.isRead and not conversation.isArchived
146                 )
147
148         def _format_message(self, message):
149                 return " ".join(part.text.strip() for part in message.body)
150
151         def _report_new_message(self, message):
152                 currentReceivedId = self.__nextRecievedId
153                 timestamp = int(time.time())
154                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
155
156                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
157                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
158
159                 self.__nextRecievedId += 1