Bug fixes, code cleanup, debugging help all working together to make it so that I...
[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                 self._conn.session.stateMachine.reset_timers()
52
53                 self.Sent(int(time.time()), messageType, text)
54
55         @gtk_toolbox.log_exception(_moduleLogger)
56         def Close(self):
57                 try:
58                         # Clear since the user has seen it all and it should start a new conversation
59                         self._conn.session.conversations.clear_conversation(self._contactKey)
60
61                         self._conn.session.conversations.updateSignalHandler.unregister_sink(
62                                 self._callback
63                         )
64                 finally:
65                         telepathy.server.ChannelTypeText.Close(self)
66                         self.remove_from_connection()
67
68         @property
69         def _contactKey(self):
70                 contactKey = self._otherHandle.contactID, self._otherHandle.phoneNumber
71                 return contactKey
72
73         @gobject_utils.async
74         @gtk_toolbox.log_exception(_moduleLogger)
75         def _on_conversations_updated(self, conv, conversationIds):
76                 if self._contactKey not in conversationIds:
77                         return
78                 _moduleLogger.info("Incoming messages from %r for existing conversation" % (self._contactKey, ))
79                 mergedConversations = self._conn.session.conversations.get_conversation(self._contactKey)
80                 self._report_conversation(mergedConversations)
81
82         def _report_conversation(self, mergedConversations):
83                 newConversations = mergedConversations.conversations
84                 newConversations = self._filter_out_reported(newConversations)
85                 newConversations = self._filter_out_read(newConversations)
86                 newConversations = list(newConversations)
87                 if not newConversations:
88                         _moduleLogger.info(
89                                 "New messages for %r have already been read externally" % (self._contactKey, )
90                         )
91                         return
92                 self._lastMessageTimestamp = newConversations[-1].time
93
94                 messages = [
95                         newMessage
96                         for newConversation in newConversations
97                         for newMessage in newConversation.messages
98                         if newMessage.whoFrom != "Me:"
99                 ]
100                 if not newConversations:
101                         _moduleLogger.info(
102                                 "All incoming messages were really outbound messages for %r" % (self._contactKey, )
103                         )
104                         return
105
106                 for newMessage in messages:
107                         formattedMessage = self._format_message(newMessage)
108                         self._report_new_message(formattedMessage)
109
110         def _filter_out_reported(self, conversations):
111                 return (
112                         conversation
113                         for conversation in conversations
114                         if self._lastMessageTimestamp < conversation.time
115                 )
116
117         def _filter_out_read(self, conversations):
118                 return (
119                         conversation
120                         for conversation in conversations
121                         if not conversation.isRead and not conversation.isArchived
122                 )
123
124         def _format_message(self, message):
125                 return " ".join(part.text.strip() for part in message.body)
126
127         def _report_new_message(self, message):
128                 currentReceivedId = self._nextRecievedId
129
130                 timestamp = int(time.time())
131                 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
132
133                 _moduleLogger.info("Received message from User %r" % self._otherHandle)
134                 self.Received(currentReceivedId, timestamp, self._otherHandle, type, 0, message)
135
136                 self._nextRecievedId += 1