Adding conic dependency, fixing bug with disconnecting from conic, reducing the numbe...
[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                 _moduleLogger.debug("Closing text")
74                 self._conn.session.voicemails.updateSignalHandler.unregister_sink(
75                         self.__callback
76                 )
77                 self._conn.session.texts.updateSignalHandler.unregister_sink(
78                         self.__callback
79                 )
80                 self.__callback = None
81
82                 tp.ChannelTypeText.Close(self)
83                 self.remove_from_connection()
84
85         @property
86         def _contactKey(self):
87                 contactKey = self.__otherHandle.phoneNumber
88                 return contactKey
89
90         @gtk_toolbox.log_exception(_moduleLogger)
91         def _on_conversations_updated(self, conv, conversationIds):
92                 if self._contactKey not in conversationIds:
93                         return
94                 _moduleLogger.debug("Incoming messages from %r for existing conversation" % (self._contactKey, ))
95                 mergedConversations = conv.get_conversation(self._contactKey)
96                 self._report_conversation(mergedConversations)
97
98         def _report_conversation(self, mergedConversations):
99                 # Can't filter out messages in a texting conversation that came in
100                 # before the last one sent because that creates a race condition of two
101                 # people sending at about the same time, which happens quite a bit
102                 newConversations = mergedConversations.conversations
103                 if not newConversations:
104                         _moduleLogger.debug(
105                                 "No messages ended up existing for %r" % (self._contactKey, )
106                         )
107                         return
108                 newConversations = self._filter_out_reported(newConversations)
109                 newConversations = self._filter_out_read(newConversations)
110                 newConversations = list(newConversations)
111                 if not newConversations:
112                         _moduleLogger.debug(
113                                 "New messages for %r have already been read externally" % (self._contactKey, )
114                         )
115                         return
116                 self.__lastMessageTimestamp = newConversations[-1].time
117
118                 messages = [
119                         newMessage
120                         for newConversation in newConversations
121                         for newMessage in newConversation.messages
122                         if newMessage.whoFrom != "Me:"
123                 ]
124                 if not newConversations:
125                         _moduleLogger.debug(
126                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
127                         )
128                         return
129
130                 for newMessage in messages:
131                         formattedMessage = self._format_message(newMessage)
132                         self._report_new_message(formattedMessage)
133
134         def _filter_out_reported(self, conversations):
135                 return (
136                         conversation
137                         for conversation in conversations
138                         if self.__lastMessageTimestamp < conversation.time
139                 )
140
141         @staticmethod
142         def _filter_out_read(conversations):
143                 return (
144                         conversation
145                         for conversation in conversations
146                         if not conversation.isRead and not conversation.isArchived
147                 )
148
149         def _format_message(self, message):
150                 return " ".join(part.text.strip() for part in message.body)
151
152         def _report_new_message(self, message):
153                 currentReceivedId = self.__nextRecievedId
154                 timestamp = int(time.time())
155                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
156
157                 _moduleLogger.info("Received message from User %r" % self.__otherHandle)
158                 self.Received(currentReceivedId, timestamp, self.__otherHandle, type, 0, message)
159
160                 self.__nextRecievedId += 1