4ad3fcb3aef685bf3bf78957ae2041aec9d51cdf
[theonering] / src / channel / text.py
1 import time
2 import datetime
3 import logging
4
5 import telepathy
6
7 import util.go_utils as gobject_utils
8 import util.coroutines as coroutines
9 import gtk_toolbox
10
11
12 _moduleLogger = logging.getLogger("channel.text")
13
14
15 class TextChannel(telepathy.server.ChannelTypeText):
16         """
17         Look into implementing ChannelInterfaceMessages for rich text formatting
18         """
19
20         def __init__(self, connection, h):
21                 telepathy.server.ChannelTypeText.__init__(self, connection, h)
22                 self._nextRecievedId = 0
23                 self._lastMessageTimestamp = datetime.datetime(1, 1, 1)
24
25                 self._otherHandle = h
26
27                 self._callback = coroutines.func_sink(
28                         coroutines.expand_positional(
29                                 self._on_conversations_updated
30                         )
31                 )
32                 self._conn.session.conversations.updateSignalHandler.register_sink(
33                         self._callback
34                 )
35
36                 # The only reason there should be anything in the conversation is if
37                 # its new, so report it all
38                 try:
39                         mergedConversations = self._conn.session.conversations.get_conversation(self._contactKey)
40                 except KeyError:
41                         pass
42                 else:
43                         self._report_conversation(mergedConversations)
44
45         @gtk_toolbox.log_exception(_moduleLogger)
46         def Send(self, messageType, text):
47                 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
48                         raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
49
50                 self._conn.session.backend.send_sms(self._otherHandle.phoneNumber, text)
51
52                 self.Sent(int(time.time()), messageType, text)
53
54         @gtk_toolbox.log_exception(_moduleLogger)
55         def Close(self):
56                 try:
57                         # Clear since the user has seen it all and it should start a new conversation
58                         self._conn.session.conversations.clear_conversation(self._contactKey)
59
60                         self._conn.session.conversations.updateSignalHandler.unregister_sink(
61                                 self._callback
62                         )
63                 finally:
64                         telepathy.server.ChannelTypeText.Close(self)
65                         self.remove_from_connection()
66
67         @property
68         def _contactKey(self):
69                 contactKey = self._otherHandle.contactID, self._otherHandle.phoneNumber
70                 return contactKey
71
72         @gobject_utils.async
73         @gtk_toolbox.log_exception(_moduleLogger)
74         def _on_conversations_updated(self, conv, conversationIds):
75                 if self._contactKey not in conversationIds:
76                         return
77                 _moduleLogger.info("Incoming messages from %r for existing conversation" % (self._contactKey, ))
78                 mergedConversations = self._conn.session.conversations.get_conversation(self._contactKey)
79                 self._report_conversation(mergedConversations)
80
81         def _report_conversation(self, mergedConversations):
82                 newConversations = mergedConversations.conversations
83                 newConversations = self._filter_out_reported(newConversations)
84                 newConversations = self._filter_out_read(newConversations)
85                 newConversations = list(newConversations)
86                 if not newConversations:
87                         _moduleLogger.info(
88                                 "New messages for %r have already been read externally" % (self._contactKey, )
89                         )
90                         return
91                 self._lastMessageTimestamp = newConversations[-1].time
92
93                 messages = [
94                         newMessage
95                         for newConversation in newConversations
96                         for newMessage in newConversation.messages
97                         if newMessage.whoFrom != "Me:"
98                 ]
99                 if not newConversations:
100                         _moduleLogger.info(
101                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
102                         )
103                         return
104
105                 for newMessage in messages:
106                         formattedMessage = self._format_message(newMessage)
107                         self._report_new_message(formattedMessage)
108
109         def _filter_out_reported(self, conversations):
110                 return (
111                         conversation
112                         for conversation in conversations
113                         if self._lastMessageTimestamp < conversation.time
114                 )
115
116         def _filter_out_read(self, conversations):
117                 return (
118                         conversation
119                         for conversation in conversations
120                         if not conversation.isRead and not conversation.isArchived
121                 )
122
123         def _format_message(self, message):
124                 return " ".join(part.text.strip() for part in message.body)
125
126         def _report_new_message(self, message):
127                 currentReceivedId = self._nextRecievedId
128
129                 timestamp = int(time.time())
130                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
131
132                 _moduleLogger.info("Received message from User %r" % self._otherHandle)
133                 self.Received(currentReceivedId, timestamp, self._otherHandle, type, 0, message)
134
135                 self._nextRecievedId += 1