def SetAliases(self, aliases): for handle_id, alias in aliases.iteritems(): handle = self.handle(telepathy.HANDLE_TYPE_CONTACT, handle_id) if handle == SunshineHandleFactory(self, 'self'): logger.info("Self alias changed to '%s'" % alias) self.configfile.save_self_alias(alias) self.AliasesChanged(((SunshineHandleFactory(self, 'self'), alias), )) else: logger.debug("Called SetAliases for handle: %s, alias: %s" % (handle.name, alias)) if alias == handle.name: alias = '' new_alias = alias try: handle.contact.updateName(new_alias) except: pass #alias = unicode(alias, 'utf-8') logger.info("Contact %s alias changed to '%s'" % (unicode(handle.name), alias)) self.aliases[handle.name] = alias self.AliasesChanged([(handle, alias)])
def makeTelepathyGroupChannels(self): logger.debug("Method makeTelepathyGroupChannels called.") for group in self.profile.groups: handle = SunshineHandleFactory(self, 'group', group.Name) props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, handle, False) self._channel_manager.channel_for_props(props, signal=True)
def _update_capabilities(self, contact): handle = SunshineHandleFactory(self, 'contact', contact.account, contact.network_id) ctype = telepathy.CHANNEL_TYPE_STREAMED_MEDIA new_gen, new_spec, rcc = self._get_capabilities(contact) if handle in self._caps: old_gen, old_spec = self._caps[handle][ctype] else: old_gen = 0 old_spec = 0 if old_gen != new_gen or old_spec != new_spec: diff = (int(handle), ctype, old_gen, new_gen, old_spec, new_spec) self.CapabilitiesChanged([diff]) if rcc is None: return self._contact_caps.setdefault(handle, []) if rcc in self._contact_caps[handle]: return if self.audio_chat_class in self._contact_caps[handle]: self._contact_caps[handle].remove(self.audio_chat_class) if self.audio_chat_class in self._contact_caps[handle]: self._contact_caps[handle].remove(self.audio_chat_class) self._contact_caps[handle].append(rcc) ret = dbus.Dictionary({handle: self._contact_caps[handle]}, signature='ua(a{sv}as)') self.ContactCapabilitiesChanged(ret)
def _get_alias(self, handle_id): """Get the alias from one handle id""" handle = self.handle(telepathy.HANDLE_TYPE_CONTACT, handle_id) if handle == SunshineHandleFactory(self, 'self'): logger.info("SunshineHandleFactory for self handle '%s', id: %s" % (handle.name, handle.id)) alias = self.configfile.get_self_alias() self.configfile.save_self_alias(alias) if alias == None or len(alias) == 0: alias = handle.name else: logger.info("SunshineHandleFactory handle '%s', id: %s" % (handle.name, handle.id)) contact = handle.contact #print str(self.aliases) if self.aliases.has_key(handle.name): alias = self.aliases[handle.name] #del self.aliases[handle.name] elif contact is None: alias = handle.name else: alias = contact.ShowName if alias == '' or alias is None: alias = str(handle.name) return alias
def SetChatState(self, state): # Not useful if we dont have a conversation. if state == telepathy.CHANNEL_CHAT_STATE_COMPOSING: t = 1 else: t = 0 handle = SunshineHandleFactory(self._conn_ref(), 'self') self._conn_ref().profile.sendTypingNotify(int(self.handle.name), t) self.ChatStateChanged(handle, state)
def SetPresence(self, status, message): if status == SunshinePresenceMapping.OFFLINE: self.Disconnect() try: presence = SunshinePresenceMapping.to_gg[status] except KeyError: raise telepathy.errors.InvalidArgument logger.info("Setting Presence to '%s'" % presence) logger.info("Setting Personal message to '%s'" % message) message = message.encode('UTF-8') self.presence = presence self.personal_message = message if self._status == telepathy.CONNECTION_STATUS_CONNECTED: self._self_presence_changed(SunshineHandleFactory(self, 'self'), presence, message) self.profile.setMyState(presence, message) else: self._self_presence_changed(SunshineHandleFactory(self, 'self'), presence, message)
def RequestHandles(self, handle_type, names, sender): logger.info( "Method RequestHandles called, handle type: %s, names: %s" % (str(handle_type), str(names))) self.check_connected() self.check_handle_type(handle_type) handles = [] for name in names: if handle_type == telepathy.HANDLE_TYPE_CONTACT: contact_name = name try: int(str(contact_name)) except: raise InvalidHandle handle_id = self.get_handle_id_by_name( telepathy.constants.HANDLE_TYPE_CONTACT, str(contact_name)) if handle_id != 0: handle = self.handle( telepathy.constants.HANDLE_TYPE_CONTACT, handle_id) else: handle = SunshineHandleFactory(self, 'contact', str(contact_name), None) elif handle_type == telepathy.HANDLE_TYPE_ROOM: handle = SunshineHandleFactory(self, 'room', name) elif handle_type == telepathy.HANDLE_TYPE_LIST: handle = SunshineHandleFactory(self, 'list', name) elif handle_type == telepathy.HANDLE_TYPE_GROUP: handle = SunshineHandleFactory(self, 'group', name) else: raise telepathy.NotAvailable('Handle type unsupported %d' % handle_type) handles.append(handle.id) self.add_client_handle(handle, sender) return handles
def _populate_capabilities(self): """ Add the capability to create text channels to all contacts in our contacts list.""" handles = set([self._self_handle]) for contact in self.profile.contacts: handle = SunshineHandleFactory(self, 'contact', str(contact.uin), None) handles.add(handle) self.add_text_capabilities(handles) # These caps were updated before we were online. for caps in self._update_capabilities_calls: self.UpdateCapabilities(caps) self._update_capabilities_calls = []
def _populate(self, connection): added = set() local_pending = set() remote_pending = set() for contact in connection.gadu_client.contacts: #logger.info("New contact %s, name: %s added." % (contact.uin, contact.ShowName)) ad, lp, rp = self._filter_contact(contact) if ad or lp or rp: handle = SunshineHandleFactory(self._conn_ref(), 'contact', contact.uin, None) #capabilities self._conn_ref().contactAdded(handle) if ad: added.add(handle) if lp: local_pending.add(handle) if rp: remote_pending.add(handle) #self._conn_ref()._populate_capabilities() #capabilities for self handle self._conn_ref().contactAdded(self._conn_ref().GetSelfHandle()) self.MembersChanged('', added, (), local_pending, remote_pending, 0, telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE)
def add_contact_to_group(self, group, contact, contact_handle): group_name = group.Name if group_name == self._handle.name: if hasattr(contact, 'uin'): contact_uin = contact.uin else: contact_uin = contact_handle.name handle = SunshineHandleFactory(self.conn, 'contact', contact_uin, None) added = set() added.add(handle) if group.Name and group.Id: is_group = False contact_groups_xml = ET.Element("Groups") if hasattr(contact, 'Groups'): contact_groups = ET.fromstring(contact.Groups) for c_group in contact_groups.getchildren(): if c_group.text == group.Id: is_group = True ET.SubElement(contact_groups_xml, "GroupId").text = c_group.text if is_group != True: ET.SubElement(contact_groups_xml, "GroupId").text = group.Id c_groups = ET.tostring(contact_groups_xml) if hasattr(contact, 'updateGroups'): contact.updateGroups(c_groups) else: self.conn.pending_contacts_to_group[contact_uin] = c_groups self.MembersChanged('', added, (), (), (), 0, telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE) logger.debug("Contact %s added to group %s" % (handle.name, group_name))
def get_simple_presences(self, contacts): presences = dbus.Dictionary(signature='u(uss)') for handle_id in contacts: handle = self.handle(telepathy.HANDLE_TYPE_CONTACT, handle_id) if handle == SunshineHandleFactory(self, 'self'): presence = SunshinePresenceMapping.to_telepathy[self.presence] personal_message = self.personal_message else: #I dont know what to do here. Do I really need this? :P contact = handle.contact if contact is not None: if contact.status in SunshinePresenceMapping.from_gg_to_tp: presence = SunshinePresenceMapping.from_gg_to_tp[contact.status] else: presence = SunshinePresenceMapping.from_gg_to_tp[0] personal_message = str('') else: presence = SunshinePresenceMapping.OFFLINE personal_message = u"" presence_type = SunshinePresenceMapping.to_presence_type[presence] presences[handle] = dbus.Struct((presence_type, presence, personal_message), signature='uss') return presences
def delete_contact_from_group(self, group, contact, contact_handle): group_name = group.Name if group_name == self._handle.name: handle = SunshineHandleFactory(self.conn, 'contact', contact.uin, None) removed = set() removed.add(handle) contact_groups_xml = ET.Element("Groups") contact_groups = ET.fromstring(contact.Groups) if contact.Groups: for c_group in contact_groups.getchildren(): if c_group.text != group.Id: ET.SubElement(contact_groups_xml, "GroupId").text = c_group.text c_groups = ET.tostring(contact_groups_xml) contact.updateGroups(c_groups) self.MembersChanged('', (), removed, (), (), 0, telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE) logger.debug("Contact %s removed from group %s" % (handle.name, group_name))
def __init__(self, conn, props): # If we have InitiatorHandle set in our new channel, use that, if telepathy.CHANNEL_INTERFACE + '.InitiatorHandle' in props: self._initiator = conn.handle( telepathy.HANDLE_TYPE_CONTACT, props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle']) # otherwise use InitiatorID. elif telepathy.CHANNEL_INTERFACE + '.InitiatorID' in props: self._initiator = SunshineHandleFactory( conn, 'contact', id=props[telepathy.CHANNEL_INTERFACE + '.InitiatorID']) # If we don't have either of the above but we requested the channel, # then we're the initiator. elif props[telepathy.CHANNEL_INTERFACE + '.Requested']: self._initiator = conn.GetSelfHandle() else: logger.warning( 'InitiatorID or InitiatorHandle not set on new channel') self._initiator = None # Don't implement the initiator properties if we don't have one. if self._initiator: self._implement_property_get( telepathy.CHANNEL_INTERFACE, { 'InitiatorHandle': lambda: dbus.UInt32(self._initiator.id), 'InitiatorID': lambda: self._initiator.name }) self._add_immutables({ 'InitiatorHandle': telepathy.CHANNEL_INTERFACE, 'InitiatorID': telepathy.CHANNEL_INTERFACE, })
def on_messageReceived(self, msg): if hasattr(msg.content.attrs, 'conference') and msg.content.attrs.conference != None: recipients = msg.content.attrs.conference.recipients recipients = map(str, recipients) recipients.append(str(msg.sender)) recipients = sorted(recipients) conf_name = ', '.join(map(str, recipients)) #active handle for current writting contact ahandle_id = self.get_handle_id_by_name( telepathy.constants.HANDLE_TYPE_CONTACT, str(msg.sender)) if ahandle_id != 0: ahandle = self.handle(telepathy.constants.HANDLE_TYPE_CONTACT, ahandle_id) else: ahandle = SunshineHandleFactory(self, 'contact', str(msg.sender), None) #now we need to preapare a new room and make initial users in it room_handle_id = self.get_handle_id_by_name( telepathy.constants.HANDLE_TYPE_ROOM, str(conf_name)) handles = [] if room_handle_id == 0: room_handle = SunshineHandleFactory(self, 'room', str(conf_name)) for number in recipients: handle_id = self.get_handle_id_by_name( telepathy.constants.HANDLE_TYPE_CONTACT, number) if handle_id != 0: handle = self.handle( telepathy.constants.HANDLE_TYPE_CONTACT, handle_id) else: handle = SunshineHandleFactory(self, 'contact', number, None) handles.append(handle) else: room_handle = self.handle(telepathy.constants.HANDLE_TYPE_ROOM, room_handle_id) props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, room_handle, False) if handles: channel = self._channel_manager.channel_for_props( props, signal=True, conversation=handles) channel.MembersChanged( '', handles, [], [], [], 0, telepathy.CHANNEL_GROUP_CHANGE_REASON_NONE) else: channel = self._channel_manager.channel_for_props( props, signal=True, conversation=None) if int(msg.content.klass) == 9: timestamp = int(msg.time) else: timestamp = int(time.time()) type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL logger.info("User %s sent a message" % ahandle.name) logger.info("Msg from %r %d %d [%r] [%r]" % (msg.sender, msg.content.offset_plain, msg.content.offset_attrs, msg.content.plain_message, msg.content.html_message)) if msg.content.html_message: #we need to strip all html tags text = unescape(stripHTML(msg.content.html_message)) else: text = unescape( (msg.content.plain_message).decode('windows-1250')) message = "%s" % unicode( str(text).replace('\x00', '').replace('\r', '')) #print 'message: ', message channel.Received(self._recv_id, timestamp, ahandle, type, 0, message) self._recv_id += 1 else: handle_id = self.get_handle_id_by_name( telepathy.constants.HANDLE_TYPE_CONTACT, str(msg.sender)) if handle_id != 0: handle = self.handle(telepathy.constants.HANDLE_TYPE_CONTACT, handle_id) else: handle = SunshineHandleFactory(self, 'contact', str(msg.sender), None) if int(msg.content.klass) == 9: timestamp = int(msg.time) else: timestamp = int(time.time()) type = telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL logger.info("User %s sent a message" % handle.name) logger.info("Msg from %r %d %d [%r] [%r]" % (msg.sender, msg.content.offset_plain, msg.content.offset_attrs, msg.content.plain_message, msg.content.html_message)) props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, handle, False) channel = self._channel_manager.channel_for_props( props, signal=True, conversation=None) if msg.content.html_message: #we need to strip all html tags text = unescape( stripHTML(msg.content.html_message.replace('<br>', '\n'))) else: text = unescape( (msg.content.plain_message).decode('windows-1250')) message = "%s" % unicode( str(text).replace('\x00', '').replace('\r', '')) channel.signalTextReceived(self._recv_id, timestamp, handle, type, 0, handle.name, message) self._recv_id += 1
def makeTelepathyContactsChannel(self): logger.debug("Method makeTelepathyContactsChannel called.") handle = SunshineHandleFactory(self, 'list', 'subscribe') props = self._generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, handle, False) self._channel_manager.channel_for_props(props, signal=True)
def __init__(self, protocol, manager, parameters): protocol.check_parameters(parameters) try: account = unicode(parameters['account']) server = (parameters['server'], parameters['port']) self._manager = weakref.proxy(manager) self._account = (parameters['account'], parameters['password']) self.param_server = (parameters['server'], parameters['port']) self._export_contacts = bool(parameters['export-contacts']) self.param_use_ssl = bool(parameters['use-ssl']) self.param_specified_server = bool( parameters['use-specified-server']) self.profile = GaduProfile(uin=int(parameters['account'])) self.profile.uin = int(parameters['account']) self.profile.password = str(parameters['password']) self.profile.status = 0x014 self.profile.onLoginSuccess = self.on_loginSuccess self.profile.onLoginFailure = self.on_loginFailed self.profile.onContactStatusChange = self.on_updateContact self.profile.onMessageReceived = self.on_messageReceived self.profile.onTypingNotification = self.onTypingNotification self.profile.onXmlAction = self.onXmlAction self.profile.onXmlEvent = self.onXmlEvent self.profile.onUserData = self.onUserData #lets try to make file with contacts etc ^^ self.configfile = SunshineConfig(int(parameters['account'])) self.configfile.check_dirs() #lets get contacts from contacts config file contacts_list = self.configfile.get_contacts() for contact_from_list in contacts_list['contacts']: c = GaduContact.from_xml(contact_from_list) try: c.uin self.profile.addContact(c) except: pass for group_from_list in contacts_list['groups']: g = GaduContactGroup.from_xml(group_from_list) if g.Name: self.profile.addGroup(g) logger.info("We have %s contacts in file." % (self.configfile.get_contacts_count())) self.factory = GaduClientFactory(self.profile) if check_requirements() == True: self.ggapi = GG_Oauth(self.profile.uin, parameters['password']) self._channel_manager = SunshineChannelManager(self, protocol) self._recv_id = 0 self._conf_id = 0 self.pending_contacts_to_group = {} self._status = None self.profile.contactsLoop = None # Call parent initializers telepathy.server.Connection.__init__(self, 'gadugadu', account, 'sunshine', protocol) telepathy.server.ConnectionInterfaceRequests.__init__(self) SunshinePresence.__init__(self) SunshineAvatars.__init__(self) SunshineCapabilities.__init__(self) if check_requirements() == True: SunshineContactInfo.__init__(self) SunshineContacts.__init__(self) self.updateCapabilitiesCalls() self.set_self_handle(SunshineHandleFactory(self, 'self')) self.__disconnect_reason = telepathy.CONNECTION_STATUS_REASON_NONE_SPECIFIED #small hack. We started to connnect with status invisible and just later we change status to client-like self._initial_presence = 0x014 self._initial_personal_message = None self._personal_message = '' self.conn_checker = task.LoopingCall(self.connection_checker) self.conn_checker.start(5.0, False) logger.info("Connection to the account %s created" % account) except Exception, e: import traceback logger.exception("Failed to create Connection") raise