7 import util.go_utils as gobject_utils
8 import util.coroutines as coroutines
12 _moduleLogger = logging.getLogger("channel.text")
15 class TextChannel(telepathy.server.ChannelTypeText):
17 Look into implementing ChannelInterfaceMessages for rich text formatting
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)
27 self._conn.session.conversations.updateSignalHandler.register_sink(
28 self._on_conversations_updated
31 # The only reason there should be anything in the conversation is if
32 # its new, so report it all
34 conversation = self._conn.session.conversations.get_conversation(self._contactKey)
38 self._report_conversation(conversation)
40 @gtk_toolbox.log_exception(_moduleLogger)
41 def Send(self, messageType, text):
42 if messageType != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL:
43 raise telepathy.errors.NotImplemented("Unhandled message type: %r" % messageType)
45 self._conn.session.backend.send_sms(self._otherHandle.phoneNumber, text)
47 self.Sent(int(time.time()), messageType, text)
49 @gtk_toolbox.log_exception(_moduleLogger)
52 # Clear since the user has seen it all and it should start a new conversation
53 self._conn.session.conversations.clear_conversation(self._contactKey)
55 self._conn.session.conversations.updateSignalHandler.unregister_sink(
56 self._on_conversations_updated
59 telepathy.server.ChannelTypeText.Close(self)
60 self.remove_from_connection()
63 def _contactKey(self):
64 contactKey = self._otherHandle.contactID, self._otherHandle.phoneNumber
68 @coroutines.expand_positional
70 def _on_conversations_updated(self, conversationIds):
71 if self._contactKey not in conversationIds:
73 conversation = self._conn.session.conversations.get_conversation(self._contactKey)
74 self._report_conversation(conversation)
76 def _report_conversation(self, conversation):
77 # @bug Check if messages sent need to be filtered out
78 completeMessageHistory = conversation["messageParts"]
79 messages = self._filter_seen_messages(completeMessageHistory)
80 self._lastMessageTimestamp = messages[-1][0]
81 formattedMessage = self._format_messages(messages)
82 self._report_new_message(formattedMessage)
84 def _filter_seen_messages(self, messages):
87 for message in messages
88 if self._lastMessageTimestamp < message[0]
91 def _format_messages(self, messages):
92 return "\n".join(message[1] for message in messages)
94 def _report_new_message(self, message):
95 currentReceivedId = self._nextRecievedId
97 timestamp = int(time.time())
98 type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL
99 message = message.content
101 _moduleLogger.info("Received message from User %r" % self._otherHandle)
102 self.Received(id, timestamp, self._otherHandle, type, 0, message)
104 self._nextRecievedId += 1