Пример #1
0
    def updateAvatar(self, contact, iconData=None, md5Hash=None, numHash=None):
        if config.disableAvatars: return
        from glue import icq2jid

        if md5Hash:
            LogEvent(INFO, self.session.jabberID,
                     "%s [M]%s" % (contact.lower(), binascii.hexlify(md5Hash)))
        elif numHash:
            LogEvent(INFO, self.session.jabberID,
                     "%s [N]%d" % (contact.lower(), numHash))

        c = self.session.contactList.findContact(icq2jid(contact))
        if not c:
            #debug.log("Update setting default avatar for %s" %(contact))
            jabContact = self.session.contactList.createContact(
                icq2jid(contact), "both")
            c = jabContact

        if iconData and (md5Hash or numHash):
            LogEvent(INFO, self.session.jabberID,
                     "Update setting custom avatar for %s" % (contact))
            try:
                # Debugging, keeps original icon pre-convert
                try:
                    f = open(
                        os.path.abspath(config.spooldir) + X + config.jid + X +
                        "avatarsdebug" + X + contact + ".icondata", 'w')
                    f.write(iconData)
                    f.close()
                except:
                    # This isn't important
                    pass
                avatarData = avatar.AvatarCache().setAvatar(
                    imgmanip.convertToPNG(iconData))
                c.updateAvatar(avatarData, push=True)
                if not md5Hash:
                    m = md5.new()
                    m.update(iconData)
                    md5Hash = m.digest()
                if not numHash:
                    numHash = oscar.getIconSum(iconData)
                self.updateIconHashes(contact.lower(),
                                      avatarData.getImageHash(),
                                      binascii.hexlify(md5Hash), numHash)
            except:
                LogEvent(
                    INFO, self.session.jabberID,
                    "Whoa there, this image doesn't want to work.  Lets leave it where it was..."
                )
        else:
            if not c.avatar:
                LogEvent(INFO, self.session.jabberID,
                         "Update setting default avatar for %s" % (contact))
                if config.disableDefaultAvatar:
                    c.updateAvatar(None, push=True)
                else:
                    if contact[0].isdigit():
                        c.updateAvatar(glue.defaultICQAvatar, push=True)
                    else:
                        c.updateAvatar(glue.defaultAIMAvatar, push=True)
Пример #2
0
    def updateSSIContact(
        self,
        contact,
        presence="unavailable",
        show=None,
        status=None,
        nick=None,
        ipaddr=None,
        lanipaddr=None,
        lanipport=None,
        icqprotocol=None,
        url=None,
    ):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID)
        self.ssicontacts[contact.lower()] = {
            "presence": presence,
            "show": show,
            "status": status,
            "url": url,
            "ipaddr": ipaddr,
            "lanipaddr": lanipaddr,
            "lanipport": lanipport,
            "icqprotocol": icqprotocol,
        }

        c = self.session.contactList.findContact(icq2jid(contact))
        if not c:
            LogEvent(INFO, self.session.jabberID, "Update setting default avatar for %s" % (contact))
            c = self.session.contactList.createContact(icq2jid(contact), "both")
            if not config.disableAvatars:
                if contact[0].isdigit():
                    c.updateAvatar(glue.defaultICQAvatar, push=False)
                else:
                    c.updateAvatar(glue.defaultAIMAvatar, push=False)

        if not self.xdbcontacts.has_key(contact.lower()):
            self.xdbcontacts[contact.lower()] = {}
            if nick:
                self.xdbcontacts[contact.lower()]["nickname"] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(icq2jid(contact), "subscribe", "both", nick)
            else:
                self.session.sendRosterImport(icq2jid(contact), "subscribe", "both", contact)
            self.session.pytrans.xdb.setListEntry(
                "roster", self.session.jabberID, contact.lower(), payload=self.xdbcontacts[contact.lower()]
            )
        else:
            decodednickname = self.xdbcontacts[contact.lower()].get("nickname", "")
            try:
                decodednickname = unicode(decodednickname, errors="replace")
            except:
                pass
            if nick and decodednickname != nick:
                self.xdbcontacts[contact.lower()]["nickname"] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(icq2jid(contact), "subscribe", "both", nick)
Пример #3
0
    def updateAvatar(self, contact, iconData=None, md5Hash=None, numHash=None):
        if config.disableAvatars:
            return
        from glue import icq2jid

        if md5Hash:
            LogEvent(INFO, self.session.jabberID, "%s [M]%s" % (
                contact.lower(), binascii.hexlify(md5Hash)))
        elif numHash:
            LogEvent(
                INFO, self.session.jabberID, "%s [N]%d" % (contact.lower(), numHash))

        c = self.session.contactList.findContact(icq2jid(contact))
        if not c:
            #debug.log("Update setting default avatar for %s" %(contact))
            jabContact = self.session.contactList.createContact(
                icq2jid(contact), "both")
            c = jabContact

        if iconData and (md5Hash or numHash):
            LogEvent(INFO, self.session.jabberID,
                     "Update setting custom avatar for %s" % (contact))
            try:
                # Debugging, keeps original icon pre-convert
                try:
                    f = open(os.path.abspath(config.spooldir) + X + config.jid +
                             X + "avatarsdebug" + X + contact + ".icondata", 'w')
                    f.write(iconData)
                    f.close()
                except:
                    # This isn't important
                    pass
                avatarData = avatar.AvatarCache().setAvatar(
                    imgmanip.convertToPNG(iconData))
                c.updateAvatar(avatarData, push=True)
                if not md5Hash:
                    m = md5.new()
                    m.update(iconData)
                    md5Hash = m.digest()
                if not numHash:
                    numHash = oscar.getIconSum(iconData)
                self.updateIconHashes(
                    contact.lower(), avatarData.getImageHash(), binascii.hexlify(md5Hash), numHash)
            except:
                LogEvent(INFO, self.session.jabberID,
                         "Whoa there, this image doesn't want to work.  Lets leave it where it was...")
        else:
            if not c.avatar:
                LogEvent(INFO, self.session.jabberID,
                         "Update setting default avatar for %s" % (contact))
                if config.disableDefaultAvatar:
                    c.updateAvatar(None, push=True)
                else:
                    if contact[0].isdigit():
                        c.updateAvatar(glue.defaultICQAvatar, push=True)
                    else:
                        c.updateAvatar(glue.defaultAIMAvatar, push=True)
Пример #4
0
    def gotAuthorizationRequest(self, uin):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID)
        if not uin in self.authorizationRequests:
            self.authorizationRequests.append(uin)
            self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), ptype="subscribe")
Пример #5
0
 def receiveTypingNotify(self, type, user):
     from glue import icq2jid
     LogEvent(INFO, self.session.jabberID)
     #debug.log("B: receiveTypingNotify %s from %s" % (type,hasattr(user,'name') and user.name or None))
     sourcejid = icq2jid(user.name)
     if type == "begin":
         self.session.sendTypingNotification(to=self.session.jabberID,
                                             fro=sourcejid,
                                             typing=True)
         self.session.sendChatStateNotification(to=self.session.jabberID,
                                                fro=sourcejid,
                                                state="composing")
     elif type == "idle":
         self.session.sendTypingNotification(to=self.session.jabberID,
                                             fro=sourcejid,
                                             typing=False)
         self.session.sendChatStateNotification(to=self.session.jabberID,
                                                fro=sourcejid,
                                                state="paused")
     elif type == "finish":
         self.session.sendTypingNotification(to=self.session.jabberID,
                                             fro=sourcejid,
                                             typing=False)
         self.session.sendChatStateNotification(to=self.session.jabberID,
                                                fro=sourcejid,
                                                state="active")
Пример #6
0
    def __init__(self, session):
        self.session = session
        self.ssicontacts = {}
        self.usercaps = {}
        self.usercustomstatuses = {}
        self.saved_snacs = dict([])
        self.uservars = {}
        self.xdbcontacts = self.getBuddyList()
        for c in self.xdbcontacts:
            from glue import icq2jid

            jabContact = self.session.contactList.createContact(icq2jid(c), "both")
            if self.xdbcontacts[c].has_key("nickname"):
                jabContact.updateNickname(self.xdbcontacts[c]["nickname"], push=False)
            if not config.disableAvatars:
                if self.xdbcontacts[c].has_key("shahash"):
                    LogEvent(INFO, self.session.jabberID, "Setting custom avatar for %s" % (c))
                    avatarData = avatar.AvatarCache().getAvatar(self.xdbcontacts[c]["shahash"])
                    jabContact.updateAvatar(avatarData, push=False)
                elif self.xdbcontacts[c].has_key("localhash"):
                    # Temporary
                    LogEvent(INFO, self.session.jabberID, "Setting custom avatar for %s" % (c))
                    avatarData = avatar.AvatarCache().getAvatar(self.xdbcontacts[c]["localhash"])
                    jabContact.updateAvatar(avatarData, push=False)
                else:
                    if not config.disableDefaultAvatar:
                        LogEvent(INFO, self.session.jabberID, "Setting default avatar for %s" % (c))
                        if c[0].isdigit():
                            jabContact.updateAvatar(glue.defaultICQAvatar, push=False)
                        else:
                            jabContact.updateAvatar(glue.defaultAIMAvatar, push=False)
Пример #7
0
	def gotAuthorizationResponse(self, uin, success):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		if success:
			for g in self.ssigroups:
				for u in g.users:
					if u.name == uin:
						u.authorized = True
						u.authorizationRequestSent = False
						self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), show=None, ptype="subscribed")
						return
		else:
			for g in self.ssigroups:
				for u in g.users:
					if u.name == uin:
						u.authorizationRequestSent = False
			self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), show=None, status=None, ptype="unsubscribed")
Пример #8
0
	def buddyAdded(self, uin):
		from glue import icq2jid
		for g in self.ssigroups:
			for u in g.users:
				if u.name == uin:
					if u.authorized:
						self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), show=None, ptype="subscribed")
						return
Пример #9
0
 def gotAuthorizationRequest(self, uin):
     from glue import icq2jid
     LogEvent(INFO, self.session.jabberID)
     if not uin in self.authorizationRequests:
         self.authorizationRequests.append(uin)
         self.session.sendPresence(to=self.session.jabberID,
                                   fro=icq2jid(uin),
                                   ptype="subscribe")
Пример #10
0
	def gotAuthorizationRequest(self, uin):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		if self.settingsOptionEnabled('clist_deny_all_auth_requests'): # deny all auth requests
			self.sendAuthorizationResponse(uin, False, "Request denied")
		else:
			if not uin in self.authorizationRequests:
				self.authorizationRequests.append(uin)
				self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), ptype="subscribe")
Пример #11
0
    def updateNickname(self, contact, nick):
        from glue import icq2jid

        c = self.session.contactList.findContact(icq2jid(contact))
        if c:
            LogEvent(INFO, self.session.jabberID)
            if not self.xdbcontacts.has_key(contact.lower()):
                self.xdbcontacts[contact.lower()] = {}
            if nick and self.xdbcontacts[contact.lower()].get('nickname',
                                                              '') != nick:
                self.xdbcontacts[contact.lower()]['nickname'] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(icq2jid(contact), "subscribe",
                                              "both", nick)
                self.session.pytrans.xdb.setListEntry(
                    "roster",
                    self.session.jabberID,
                    contact.lower(),
                    payload=self.xdbcontacts[contact.lower()])

        try:
            bos = self.session.legacycon.bos
            savetheseusers = []
            savethesegroups = []
            for g in bos.ssigroups:
                found = False
                for u in g.users:
                    if u.name.lower() == contact.lower():
                        savetheseusers.append(u)
                        found = True
                if found:
                    savethesegroups.append(g)
            if len(savetheseusers) > 0:
                bos.startModifySSI()
                for u in savetheseusers:
                    u.nick = nick
                    bos.modifyItemSSI(u)
                for g in savethesegroups:
                    bos.modifyItemSSI(g)
                bos.endModifySSI()
        except:
            raise
Пример #12
0
 def buddyAdded(self, uin):
     from glue import icq2jid
     for g in self.ssigroups:
         for u in g.users:
             if u.name == uin:
                 if u.authorized:
                     self.session.sendPresence(to=self.session.jabberID,
                                               fro=icq2jid(uin),
                                               show=None,
                                               ptype="subscribed")
                     return
Пример #13
0
Файл: glue.py Проект: 2mf/pyicqt
    def gotnovCard(self, profile, user, vcard, d):
        from glue import icq2jid
        LogEvent(INFO, self.session.jabberID)

        nickname = vcard.addElement("NICKNAME")
        nickname.addContent(utils.xmlify(user))
        jabberid = vcard.addElement("JABBERID")
        jabberid.addContent(icq2jid(user))
        desc = vcard.addElement("DESC")
        desc.addContent("User is not online.")

        d.callback(vcard)
Пример #14
0
    def offlineBuddy(self, user):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID, user.name)
        buddyjid = icq2jid(user.name)
        c = self.session.contactList.findContact(buddyjid)
        if not c:
            return
        show = None
        status = None
        ptype = "unavailable"
        c.updatePresence(show=show, status=status, ptype=ptype)
        self.oscarcon.legacyList.updateSSIContact(user.name, presence=ptype, show=show, status=status)
Пример #15
0
	def receiveReceiptMsgReceived(self, user, cookie):
		LogEvent(INFO, self.session.jabberID) # legacy client received own message
		msg_query = self.oscarcon.getUserVarValue(user, 'wait_for_confirm_msg_query')
		if len(msg_query):
			if cookie in msg_query:
				jabber_mid, resource, s_time = msg_query[cookie] # message id, resource and time of sending
				from glue import icq2jid
				sourcejid = icq2jid(user)
				self.session.sendMessage(to=self.session.jabberID + '/' + resource, fro=sourcejid, receipt=True, mID=jabber_mid) # send confirmation to jabber client
				uvars = {}
				uvars['wait_for_confirm_msg_query'] = msg_query # update query
				del msg_query[cookie] # delete cookie - id from query
				self.oscarcon.legacyList.setUserVars(user, uvars) # update user's vars
Пример #16
0
    def updateNickname(self, contact, nick):
        from glue import icq2jid

        c = self.session.contactList.findContact(icq2jid(contact))
        if c:
            LogEvent(INFO, self.session.jabberID)
            if not self.xdbcontacts.has_key(contact.lower()):
                self.xdbcontacts[contact.lower()] = {}
            if nick and self.xdbcontacts[contact.lower()].get('nickname', '') != nick:
                self.xdbcontacts[contact.lower()]['nickname'] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(
                    icq2jid(contact), "subscribe", "both", nick)
                self.session.pytrans.xdb.setListEntry(
                    "roster", self.session.jabberID, contact.lower(), payload=self.xdbcontacts[contact.lower()])

        try:
            bos = self.session.legacycon.bos
            savetheseusers = []
            savethesegroups = []
            for g in bos.ssigroups:
                found = False
                for u in g.users:
                    if u.name.lower() == contact.lower():
                        savetheseusers.append(u)
                        found = True
                if found:
                    savethesegroups.append(g)
            if len(savetheseusers) > 0:
                bos.startModifySSI()
                for u in savetheseusers:
                    u.nick = nick
                    bos.modifyItemSSI(u)
                for g in savethesegroups:
                    bos.modifyItemSSI(g)
                bos.endModifySSI()
        except:
            raise
Пример #17
0
 def offlineBuddy(self, user):
     from glue import icq2jid
     LogEvent(INFO, self.session.jabberID, user.name)
     buddyjid = icq2jid(user.name)
     c = self.session.contactList.findContact(buddyjid)
     if not c: return
     show = None
     status = None
     ptype = "unavailable"
     c.updatePresence(show=show, status=status, ptype=ptype)
     self.oscarcon.legacyList.updateSSIContact(user.name,
                                               presence=ptype,
                                               show=show,
                                               status=status)
Пример #18
0
Файл: glue.py Проект: 2mf/pyicqt
    def gotAIMvCard(self, profile, user, vcard, d):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID)

        cutprofile = oscar.dehtml(profile)
        nickname = vcard.addElement("NICKNAME")
        nickname.addContent(utils.xmlify(user))
        jabberid = vcard.addElement("JABBERID")
        jabberid.addContent(icq2jid(user))
        desc = vcard.addElement("DESC")
        desc.addContent(utils.xmlify(cutprofile))

        d.callback(vcard)
Пример #19
0
	def receiveTypingNotify(self, type, user):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		#debug.log("B: receiveTypingNotify %s from %s" % (type,hasattr(user,'name') and user.name or None))
		sourcejid = icq2jid(user.name)
		if type == "begin":
			self.session.sendTypingNotification(to=self.session.jabberID, fro=sourcejid, typing=True)
			self.session.sendChatStateNotification(to=self.session.jabberID, fro=sourcejid, state="composing")
		elif type == "idle":
			self.session.sendTypingNotification(to=self.session.jabberID, fro=sourcejid, typing=False)
			self.session.sendChatStateNotification(to=self.session.jabberID, fro=sourcejid, state="paused")
		elif type == "finish":
			self.session.sendTypingNotification(to=self.session.jabberID, fro=sourcejid, typing=False)
			self.session.sendChatStateNotification(to=self.session.jabberID, fro=sourcejid, state="active")
Пример #20
0
    def receiveMessage(self, user, multiparts, flags, delay=None):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID, "%s %s %s" % (user.name, multiparts, flags))
        sourcejid = icq2jid(user.name)
        text = multiparts[0][0]
        if len(multiparts[0]) > 1:
            if multiparts[0][1] == "unicode":
                encoding = "utf-16be"
            else:
                encoding = config.encoding
        else:
            encoding = config.encoding
        LogEvent(INFO, self.session.jabberID, "Using encoding %s" % (encoding))
        text = text.decode(encoding, "replace")
        xhtml = utils.prepxhtml(text)
        if not user.name[0].isdigit():
            text = oscar.dehtml(text)
        text = text.strip()
        mtype = "chat"
        if "auto" in flags:
            mtype = "headline"

        self.session.sendMessage(
            to=self.session.jabberID, fro=sourcejid, body=text, mtype=mtype, delay=delay, xhtml=xhtml
        )
        self.session.pytrans.serviceplugins["Statistics"].stats["IncomingMessages"] += 1
        self.session.pytrans.serviceplugins["Statistics"].sessionUpdate(self.session.jabberID, "IncomingMessages", 1)
        if not config.disableAwayMessage and self.awayMessage and not "auto" in flags:
            if not self.awayResponses.has_key(user.name) or self.awayResponses[user.name] < (time.time() - 900):
                # self.sendMessage(user.name, "Away message: "+self.awayMessage.encode("iso-8859-1", "replace"), autoResponse=1)
                self.sendMessage(user.name, "Away message: " + self.awayMessage, autoResponse=1)
                self.awayResponses[user.name] = time.time()

        if "icon" in flags and not config.disableAvatars:
            if self.oscarcon.legacyList.diffAvatar(user.name, numHash=user.iconcksum):
                LogEvent(
                    INFO,
                    self.session.jabberID,
                    "User %s has a buddy icon we want, will ask for it next message." % user.name,
                )
                self.requesticon[user.name] = 1
            else:
                LogEvent(INFO, self.session.jabberID, "User %s has a icon that we already have." % user.name)

        if "iconrequest" in flags and hasattr(self.oscarcon, "myavatar") and not config.disableAvatars:
            LogEvent(INFO, self.session.jabberID, "User %s wants our icon, so we're sending it." % user.name)
            icondata = self.oscarcon.myavatar
            self.sendIconDirect(user.name, icondata, wantAck=1)
Пример #21
0
	def newResourceOnline(self, resource):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		try:
			for c in self.legacyList.ssicontacts.keys( ):
				LogEvent(INFO, self.session.jabberID, "Resending buddy %r" % c)
				jid = icq2jid(c)
				show = self.legacyList.ssicontacts[c]['show']
				status = self.legacyList.ssicontacts[c]['status']
				ptype = self.legacyList.ssicontacts[c]['presence']
				url = self.legacyList.ssicontacts[c]['url']
				#FIXME, needs to be contact based updatePresence
				self.session.sendPresence(to=self.session.jabberID, fro=jid, show=show, status=status, ptype=ptype, url=url)
		except AttributeError:
			return
Пример #22
0
 def gotAuthorizationResponse(self, uin, success):
     from glue import icq2jid
     LogEvent(INFO, self.session.jabberID)
     if success:
         for g in self.ssigroups:
             for u in g.users:
                 if u.name == uin:
                     u.authorized = True
                     u.authorizationRequestSent = False
                     self.session.sendPresence(to=self.session.jabberID,
                                               fro=icq2jid(uin),
                                               show=None,
                                               ptype="subscribed")
                     return
     else:
         for g in self.ssigroups:
             for u in g.users:
                 if u.name == uin:
                     u.authorizationRequestSent = False
         self.session.sendPresence(to=self.session.jabberID,
                                   fro=icq2jid(uin),
                                   show=None,
                                   status=None,
                                   ptype="unsubscribed")
Пример #23
0
	def resourceOffline(self, resource):
		LogEvent(INFO, self.session.jabberID)
		from glue import icq2jid
		try:
			show = None
			status = None
			ptype = "unavailable"
			for c in self.legacyList.ssicontacts.keys( ):
				LogEvent(INFO, self.session.jabberID, "Sending offline %r" % c)
				jid = icq2jid(c)

				self.session.sendPresence(to=self.session.jabberID+"/"+resource, fro=jid, ptype=ptype, show=show, status=status)
			self.session.sendPresence(to=self.session.jabberID+"/"+resource, fro=config.jid, ptype=ptype, show=show, status=status)
		except AttributeError:
			return
Пример #24
0
	def offlineBuddy(self, user):
		from glue import icq2jid 
		LogEvent(INFO, self.session.jabberID, user.name)
		buddyjid = icq2jid(user.name)
                c = self.session.contactList.findContact(buddyjid)
                if not c: return
		show = None
		status = None
		ptype = "unavailable"
		c.updatePresence(show=show, status=status, ptype=ptype)
		self.oscarcon.legacyList.updateSSIContact(user.name, presence=ptype, show=show, status=status)
		
		s_mood, s_act, s_subact, s_text, s_usetune = self.oscarcon.getPersonalEvents(user.name) # get Personal Events
		self.sendPersonalEventsStop(buddyjid, s_mood, s_act, s_subact, s_usetune) # stop them
		self.oscarcon.legacyList.delCustomStatus(user.name) # del custom status struct for user
		self.oscarcon.setPersonalEvents(user.name, None, None, None) # reset personal events struct
		self.oscarcon.legacyList.delUserVars(user.name) # del custom user vars
Пример #25
0
	def gotSearchResults(self, results, iq, d):
		LogEvent(INFO, self.session.jabberID)
		from glue import icq2jid

		x = None
		for query in iq.elements():
			if query.name == "query":
				for child in query.elements():
					if child.name == "x":
						x = child
						break
				break

		if x:
			for r in results:
				if r.has_key("screenname"):
					r["jid"] = icq2jid(r["screenname"])
				else:
					r["jid"] = "Unknown"
				item = x.addElement("item")
				for k in ["jid","first","middle","last","maiden","nick","email","address","city","state","country","zip","region"]:
					item.addChild(utils.makeDataFormElement(None, k, value=r.get(k,None)))
		d.callback(iq)
Пример #26
0
 def __init__(self, session):
     self.session = session
     self.ssicontacts = {}
     self.usercaps = {}
     self.xdbcontacts = self.getBuddyList()
     for c in self.xdbcontacts:
         from glue import icq2jid
         jabContact = self.session.contactList.createContact(
             icq2jid(c), "both")
         if self.xdbcontacts[c].has_key("nickname"):
             jabContact.updateNickname(self.xdbcontacts[c]["nickname"],
                                       push=False)
         if not config.disableAvatars:
             if self.xdbcontacts[c].has_key("shahash"):
                 LogEvent(INFO, self.session.jabberID,
                          "Setting custom avatar for %s" % (c))
                 avatarData = avatar.AvatarCache().getAvatar(
                     self.xdbcontacts[c]["shahash"])
                 jabContact.updateAvatar(avatarData, push=False)
             elif self.xdbcontacts[c].has_key("localhash"):
                 # Temporary
                 LogEvent(INFO, self.session.jabberID,
                          "Setting custom avatar for %s" % (c))
                 avatarData = avatar.AvatarCache().getAvatar(
                     self.xdbcontacts[c]["localhash"])
                 jabContact.updateAvatar(avatarData, push=False)
             else:
                 if not config.disableDefaultAvatar:
                     LogEvent(INFO, self.session.jabberID,
                              "Setting default avatar for %s" % (c))
                     if c[0].isdigit():
                         jabContact.updateAvatar(glue.defaultICQAvatar,
                                                 push=False)
                     else:
                         jabContact.updateAvatar(glue.defaultAIMAvatar,
                                                 push=False)
Пример #27
0
Файл: glue.py Проект: 2mf/pyicqt
 def updatePresence(self, userHandle, ptype):  # Convenience
     from glue import icq2jid
     to = icq2jid(userHandle)
     self.session.sendPresence(
         to=self.session.jabberID, fro=to, ptype=ptype)
Пример #28
0
    def updateSSIContact(self,
                         contact,
                         presence="unavailable",
                         show=None,
                         status=None,
                         nick=None,
                         ipaddr=None,
                         lanipaddr=None,
                         lanipport=None,
                         icqprotocol=None,
                         url=None):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID)
        self.ssicontacts[contact.lower()] = {
            'presence': presence,
            'show': show,
            'status': status,
            'url': url,
            'ipaddr': ipaddr,
            'lanipaddr': lanipaddr,
            'lanipport': lanipport,
            'icqprotocol': icqprotocol
        }

        c = self.session.contactList.findContact(icq2jid(contact))
        if not c:
            LogEvent(INFO, self.session.jabberID,
                     "Update setting default avatar for %s" % (contact))
            c = self.session.contactList.createContact(icq2jid(contact),
                                                       "both")
            if not config.disableAvatars:
                if contact[0].isdigit():
                    c.updateAvatar(glue.defaultICQAvatar, push=False)
                else:
                    c.updateAvatar(glue.defaultAIMAvatar, push=False)

        if not self.xdbcontacts.has_key(contact.lower()):
            self.xdbcontacts[contact.lower()] = {}
            if nick:
                self.xdbcontacts[contact.lower()]['nickname'] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(icq2jid(contact), "subscribe",
                                              "both", nick)
            else:
                self.session.sendRosterImport(icq2jid(contact), "subscribe",
                                              "both", contact)
            self.session.pytrans.xdb.setListEntry(
                "roster",
                self.session.jabberID,
                contact.lower(),
                payload=self.xdbcontacts[contact.lower()])
        else:
            decodednickname = self.xdbcontacts[contact.lower()].get(
                'nickname', '')
            try:
                decodednickname = unicode(decodednickname, errors='replace')
            except:
                pass
            if nick and decodednickname != nick:
                self.xdbcontacts[contact.lower()]['nickname'] = nick
                c.updateNickname(nick, push=True)
                self.session.sendRosterImport(icq2jid(contact), "subscribe",
                                              "both", nick)
Пример #29
0
    def updateBuddy(self, user):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID)
        buddyjid = icq2jid(user.name)
        c = self.session.contactList.findContact(buddyjid)
        if not c:
            return

        ptype = None
        if user.icqStatus.count("dnd"):
            show = "dnd"
        elif user.icqStatus.count("xa"):
            show = "xa"
        elif user.icqStatus.count("busy"):
            show = "dnd"
        elif user.icqStatus.count("chat"):
            show = "chat"
        elif user.icqStatus.count("dnd"):
            show = "dnd"
        elif user.icqStatus.count("away"):
            show = "away"
        else:
            show = None
        status = user.status
        encoding = user.statusencoding
        url = user.url
        if encoding:
            if encoding == "utf-16be":
                status = status.decode("utf-16be", "replace")
            if encoding == "unicode":
                status = status.decode("utf-16be", "replace")
            elif encoding == "iso-8859-1":
                status = status.decode("iso-8859-1", "replace")
            elif encoding == config.encoding:
                status = status.decode(config.encoding, "replace")
            elif encoding == "icq51pseudounicode":
                # XXX: stupid Unicode test
                # XXX: ICQ 5.1 CZ clients seem to wrap UTF-8 (assuming it's CP1250) into UTF-16
                #      while e.g. Miranda sends it as ascii
                ##if len(status) != 0 and ord(status[0]) == 0:
                if len(status) != 0:
                    status = str(status)
                    try:
                        status1 = status.decode("utf-16be", "strict")
                        status1 = status1.encode("cp1250", "strict")
                        status1 = status1.decode("utf-8", "strict")
                        status = status1
                    except:
                        try:
                            status1 = status.decode("utf-8", "strict")
                            status = status1
                        except:
                            try:
                                status1 = status.decode(config.encoding, "strict")
                                status = status1
                            except:
                                # status = "Wrong encoding:" + repr(status)
                                status = str(status).decode("iso-8859-1", "replace")
        else:
            # this is a fallback solution in case that the client status encoding has not been extracted, to avoid raising an exception
            status = status.decode("utf-8", "replace")
            LogEvent(WARN, self.session.jabberID, "Unknown status message encoding for %s" % user.name)
        status = oscar.dehtml(status)  # Removes any HTML tags
        if (
            status == "Away"
            or status == "I am currently away from the computer."
            or status == "I am away from my computer right now."
        ):
            status = ""
        if user.idleTime:
            if user.idleTime > 60 * 24:
                idle_time = "Idle %d days" % (user.idleTime / (60 * 24))
                if not show:
                    show = "xa"
            elif user.idleTime > 60:
                idle_time = "Idle %d hours" % (user.idleTime / (60))
                if not show:
                    show = "away"
            else:
                idle_time = "Idle %d minutes" % (user.idleTime)
            if status:
                status = "%s - %s" % (idle_time, status)
            else:
                status = idle_time

        if user.iconmd5sum != None and not config.disableAvatars and not config.avatarsOnlyOnChat:
            if self.oscarcon.legacyList.diffAvatar(user.name, md5Hash=binascii.hexlify(user.iconmd5sum)):
                LogEvent(INFO, self.session.jabberID, "Retrieving buddy icon for %s" % user.name)
                self.retrieveBuddyIconFromServer(user.name, user.iconmd5sum, user.icontype).addCallback(
                    self.gotBuddyIconFromServer
                )
            else:
                LogEvent(INFO, self.session.jabberID, "Buddy icon is the same, using what we have for %s" % user.name)

        if user.caps:
            self.oscarcon.legacyList.setCapabilities(user.name, user.caps)
        LogEvent(WARN, self.session.jabberID, "Status message before crash %s" % status)
        status = status.encode("utf-8", "replace")
        # status = status.encode(config.encoding, "replace")
        if user.flags.count("away"):
            self.getAway(user.name).addCallback(self.sendAwayPresence, user)
        else:
            c.updatePresence(show=show, status=status, ptype=ptype, url=url)
            self.oscarcon.legacyList.updateSSIContact(
                user.name,
                presence=ptype,
                show=show,
                status=status,
                ipaddr=user.icqIPaddy,
                lanipaddr=user.icqLANIPaddy,
                lanipport=user.icqLANIPport,
                icqprotocol=user.icqProtocolVersion,
                url=url,
            )
Пример #30
0
    def sendAwayPresence(self, msg, user):
        from glue import icq2jid

        buddyjid = icq2jid(user.name)

        c = self.session.contactList.findContact(buddyjid)
        if not c:
            return

        ptype = None
        if user.icqStatus.count("dnd"):
            show = "dnd"
        elif user.icqStatus.count("xa"):
            show = "xa"
        elif user.icqStatus.count("busy"):
            show = "dnd"
        elif user.icqStatus.count("chat"):
            show = "chat"
        elif user.icqStatus.count("dnd"):
            show = "dnd"
        elif user.icqStatus.count("away"):
            show = "away"
        else:
            show = "away"

        status = msg[1]
        url = user.url

        if status != None:
            charset = "iso-8859-1"
            m = None
            if msg[0]:
                m = re.search('charset="(.+)"', msg[0])
            if m != None:
                charset = m.group(1)
                if charset == "unicode-2-0":
                    charset = "utf-16be"
                elif charset == "utf-8":
                    pass
                elif charset == "us-ascii":
                    charset = "iso-8859-1"
                elif charset == "iso-8859-1":
                    pass
                else:
                    LogEvent(INFO, self.session.jabberID, "Unknown charset (%s) of buddy's away message" % msg[0])
                    charset = config.encoding
                    status = msg[0] + ": " + status

            try:
                status = status.decode(charset, "strict")
            except:
                pass
            try:
                status1 = status.encode(config.encoding, "strict")
                status = status1.decode("utf-8", "strict")
            except:
                if ord(status[0]) == 0 and ord(status[len(status) - 1]) == 0:
                    status = str(status[1 : len(status) - 1])
                try:
                    status = str(status).decode("utf-8", "strict")
                except:
                    try:
                        status = str(status).decode(config.encoding, "strict")
                    except:
                        status = "Status decoding failed: " + status
            try:
                utfmsg = unicode(msg[0], errors="replace")
            except:
                utfmsg = msg[0]
            status = oscar.dehtml(status)
            LogEvent(INFO, self.session.jabberID, "Away (%s, %s) message %s" % (charset, utfmsg, status))

        if (
            status == "Away"
            or status == "I am currently away from the computer."
            or status == "I am away from my computer right now."
        ):
            status = ""
        if user.idleTime:
            if user.idleTime > 60 * 24:
                idle_time = "Idle %d days" % (user.idleTime / (60 * 24))
            elif user.idleTime > 60:
                idle_time = "Idle %d hours" % (user.idleTime / (60))
            else:
                idle_time = "Idle %d minutes" % (user.idleTime)
            if status:
                status = "%s - %s" % (idle_time, status)
            else:
                status = idle_time

        c.updatePresence(show=show, status=status, ptype=ptype)
        self.oscarcon.legacyList.updateSSIContact(
            user.name,
            presence=ptype,
            show=show,
            status=status,
            ipaddr=user.icqIPaddy,
            lanipaddr=user.icqLANIPaddy,
            lanipport=user.icqLANIPport,
            icqprotocol=user.icqProtocolVersion,
            url=url,
        )
Пример #31
0
    def sendAwayPresence(self, msg, user):
        from glue import icq2jid
        buddyjid = icq2jid(user.name)

        c = self.session.contactList.findContact(buddyjid)
        if not c: return

        ptype = None
        if user.icqStatus.count('dnd'):
            show = 'dnd'
        elif user.icqStatus.count('xa'):
            show = 'xa'
        elif user.icqStatus.count('busy'):
            show = 'dnd'
        elif user.icqStatus.count('chat'):
            show = 'chat'
        elif user.icqStatus.count('dnd'):
            show = 'dnd'
        elif user.icqStatus.count('away'):
            show = 'away'
        else:
            show = 'away'

        status = msg[1]
        url = user.url

        if status != None:
            charset = "iso-8859-1"
            m = None
            if msg[0]:
                m = re.search('charset="(.+)"', msg[0])
            if m != None:
                charset = m.group(1)
                if charset == 'unicode-2-0':
                    charset = 'utf-16be'
                elif charset == 'utf-8':
                    pass
                elif charset == "us-ascii":
                    charset = "iso-8859-1"
                elif charset == "iso-8859-1":
                    pass
                else:
                    LogEvent(
                        INFO, self.session.jabberID,
                        "Unknown charset (%s) of buddy's away message" %
                        msg[0])
                    charset = config.encoding
                    status = msg[0] + ": " + status

            try:
                status = status.decode(charset, 'strict')
            except:
                pass
            try:
                status1 = status.encode(config.encoding, 'strict')
                status = status1.decode('utf-8', 'strict')
            except:
                if ord(status[0]) == 0 and ord(status[len(status) - 1]) == 0:
                    status = str(status[1:len(status) - 1])
                try:
                    status = str(status).decode('utf-8', 'strict')
                except:
                    try:
                        status = str(status).decode(config.encoding, 'strict')
                    except:
                        status = "Status decoding failed: " + status
            try:
                utfmsg = unicode(msg[0], errors='replace')
            except:
                utfmsg = msg[0]
            status = oscar.dehtml(status)
            LogEvent(INFO, self.session.jabberID,
                     "Away (%s, %s) message %s" % (charset, utfmsg, status))

        if status == "Away" or status == "I am currently away from the computer." or status == "I am away from my computer right now.":
            status = ""
        if user.idleTime:
            if user.idleTime > 60 * 24:
                idle_time = "Idle %d days" % (user.idleTime / (60 * 24))
            elif user.idleTime > 60:
                idle_time = "Idle %d hours" % (user.idleTime / (60))
            else:
                idle_time = "Idle %d minutes" % (user.idleTime)
            if status:
                status = "%s - %s" % (idle_time, status)
            else:
                status = idle_time

        c.updatePresence(show=show, status=status, ptype=ptype)
        self.oscarcon.legacyList.updateSSIContact(
            user.name,
            presence=ptype,
            show=show,
            status=status,
            ipaddr=user.icqIPaddy,
            lanipaddr=user.icqLANIPaddy,
            lanipport=user.icqLANIPport,
            icqprotocol=user.icqProtocolVersion,
            url=url)
Пример #32
0
	def youWereAdded(self, uin):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		self.session.sendPresence(to=self.session.jabberID, fro=icq2jid(uin), ptype="subscribe")
Пример #33
0
    def receiveMessage(self, user, multiparts, flags, delay=None):
        from glue import icq2jid

        LogEvent(INFO, self.session.jabberID,
                 "%s %s %s" % (user.name, multiparts, flags))
        sourcejid = icq2jid(user.name)
        text = multiparts[0][0]
        if len(multiparts[0]) > 1:
            if multiparts[0][1] == 'unicode':
                encoding = "utf-16be"
            else:
                encoding = config.encoding
        else:
            encoding = config.encoding
        LogEvent(INFO, self.session.jabberID, "Using encoding %s" % (encoding))
        text = text.decode(encoding, "replace")
        xhtml = utils.prepxhtml(text)
        if not user.name[0].isdigit():
            text = oscar.dehtml(text)
        text = text.strip()
        mtype = "chat"
        if "auto" in flags:
            mtype = "headline"

        self.session.sendMessage(to=self.session.jabberID,
                                 fro=sourcejid,
                                 body=text,
                                 mtype=mtype,
                                 delay=delay,
                                 xhtml=xhtml)
        self.session.pytrans.serviceplugins['Statistics'].stats[
            'IncomingMessages'] += 1
        self.session.pytrans.serviceplugins['Statistics'].sessionUpdate(
            self.session.jabberID, 'IncomingMessages', 1)
        if not config.disableAwayMessage and self.awayMessage and not "auto" in flags:
            if not self.awayResponses.has_key(user.name) or self.awayResponses[
                    user.name] < (time.time() - 900):
                #self.sendMessage(user.name, "Away message: "+self.awayMessage.encode("iso-8859-1", "replace"), autoResponse=1)
                self.sendMessage(user.name,
                                 "Away message: " + self.awayMessage,
                                 autoResponse=1)
                self.awayResponses[user.name] = time.time()

        if "icon" in flags and not config.disableAvatars:
            if self.oscarcon.legacyList.diffAvatar(user.name,
                                                   numHash=user.iconcksum):
                LogEvent(
                    INFO, self.session.jabberID,
                    "User %s has a buddy icon we want, will ask for it next message."
                    % user.name)
                self.requesticon[user.name] = 1
            else:
                LogEvent(
                    INFO, self.session.jabberID,
                    "User %s has a icon that we already have." % user.name)

        if "iconrequest" in flags and hasattr(
                self.oscarcon, "myavatar") and not config.disableAvatars:
            LogEvent(
                INFO, self.session.jabberID,
                "User %s wants our icon, so we're sending it." % user.name)
            icondata = self.oscarcon.myavatar
            self.sendIconDirect(user.name, icondata, wantAck=1)
Пример #34
0
    def updateBuddy(self, user):
        from glue import icq2jid
        LogEvent(INFO, self.session.jabberID)
        buddyjid = icq2jid(user.name)
        c = self.session.contactList.findContact(buddyjid)
        if not c: return

        ptype = None
        if user.icqStatus.count('dnd'):
            show = 'dnd'
        elif user.icqStatus.count('xa'):
            show = 'xa'
        elif user.icqStatus.count('busy'):
            show = 'dnd'
        elif user.icqStatus.count('chat'):
            show = 'chat'
        elif user.icqStatus.count('dnd'):
            show = 'dnd'
        elif user.icqStatus.count('away'):
            show = 'away'
        else:
            show = None
        status = user.status
        encoding = user.statusencoding
        url = user.url
        if encoding:
            if encoding == "utf-16be":
                status = status.decode("utf-16be", "replace")
            if encoding == "unicode":
                status = status.decode("utf-16be", "replace")
            elif encoding == "iso-8859-1":
                status = status.decode("iso-8859-1", "replace")
            elif encoding == config.encoding:
                status = status.decode(config.encoding, "replace")
            elif encoding == "icq51pseudounicode":
                # XXX: stupid Unicode test
                # XXX: ICQ 5.1 CZ clients seem to wrap UTF-8 (assuming it's CP1250) into UTF-16
                #      while e.g. Miranda sends it as ascii
                ##if len(status) != 0 and ord(status[0]) == 0:
                if len(status) != 0:
                    status = str(status)
                    try:
                        status1 = status.decode('utf-16be', 'strict')
                        status1 = status1.encode('cp1250', 'strict')
                        status1 = status1.decode('utf-8', 'strict')
                        status = status1
                    except:
                        try:
                            status1 = status.decode('utf-8', 'strict')
                            status = status1
                        except:
                            try:
                                status1 = status.decode(
                                    config.encoding, "strict")
                                status = status1
                            except:
                                #status = "Wrong encoding:" + repr(status)
                                status = str(status).decode(
                                    "iso-8859-1", "replace")
        else:
            # this is a fallback solution in case that the client status encoding has not been extracted, to avoid raising an exception
            status = status.decode('utf-8', 'replace')
            LogEvent(WARN, self.session.jabberID,
                     "Unknown status message encoding for %s" % user.name)
        status = oscar.dehtml(status)  # Removes any HTML tags
        if status == "Away" or status == "I am currently away from the computer." or status == "I am away from my computer right now.":
            status = ""
        if user.idleTime:
            if user.idleTime > 60 * 24:
                idle_time = "Idle %d days" % (user.idleTime / (60 * 24))
                if not show: show = "xa"
            elif user.idleTime > 60:
                idle_time = "Idle %d hours" % (user.idleTime / (60))
                if not show: show = "away"
            else:
                idle_time = "Idle %d minutes" % (user.idleTime)
            if status:
                status = "%s - %s" % (idle_time, status)
            else:
                status = idle_time

        if user.iconmd5sum != None and not config.disableAvatars and not config.avatarsOnlyOnChat:
            if self.oscarcon.legacyList.diffAvatar(user.name,
                                                   md5Hash=binascii.hexlify(
                                                       user.iconmd5sum)):
                LogEvent(INFO, self.session.jabberID,
                         "Retrieving buddy icon for %s" % user.name)
                self.retrieveBuddyIconFromServer(
                    user.name, user.iconmd5sum,
                    user.icontype).addCallback(self.gotBuddyIconFromServer)
            else:
                LogEvent(
                    INFO, self.session.jabberID,
                    "Buddy icon is the same, using what we have for %s" %
                    user.name)

        if user.caps:
            self.oscarcon.legacyList.setCapabilities(user.name, user.caps)
        LogEvent(WARN, self.session.jabberID,
                 "Status message before crash %s" % status)
        status = status.encode("utf-8", "replace")
        # status = status.encode(config.encoding, "replace")
        if user.flags.count("away"):
            self.getAway(user.name).addCallback(self.sendAwayPresence, user)
        else:
            c.updatePresence(show=show, status=status, ptype=ptype, url=url)
            self.oscarcon.legacyList.updateSSIContact(
                user.name,
                presence=ptype,
                show=show,
                status=status,
                ipaddr=user.icqIPaddy,
                lanipaddr=user.icqLANIPaddy,
                lanipport=user.icqLANIPport,
                icqprotocol=user.icqProtocolVersion,
                url=url)
Пример #35
0
 def youWereAdded(self, uin):
     from glue import icq2jid
     LogEvent(INFO, self.session.jabberID)
     self.session.sendPresence(to=self.session.jabberID,
                               fro=icq2jid(uin),
                               ptype="subscribe")
Пример #36
0
	def updateBuddy(self, user, selfcall = False):
		from glue import icq2jid
		LogEvent(INFO, self.session.jabberID)
		
		buddyjid = icq2jid(user.name)
                c = self.session.contactList.findContact(buddyjid)
                if not c: return

		ptype = None
		
		show, anstatus = self.detectAdditionalNormalStatus(user.icqStatus)
		status = user.status
		encoding = user.statusencoding
		url = user.url
		if encoding and status:
			if encoding == "utf-16be":
				status = status.decode("utf-16be", "replace")
			if encoding == "unicode":
				status = status.decode("utf-16be", "replace")
			elif encoding == "iso-8859-1":
				status = status.decode("iso-8859-1", "replace")
			elif encoding == self.userEncoding:
				status = status.decode(self.userEncoding, "replace")
			elif encoding == config.encoding:
				status = status.decode(config.encoding, "replace")
			elif encoding == "icq51pseudounicode":
				# XXX: stupid Unicode test
				# XXX: ICQ 5.1 CZ clients seem to wrap UTF-8 (assuming it's CP1250) into UTF-16
				#      while e.g. Miranda sends it as ascii
				##if len(status) != 0 and ord(status[0]) == 0:
				if len(status) != 0:
					status = str(status)
					try:
						status1 = status.decode('utf-16be', 'strict')
						status1 = status1.encode('cp1250', 'strict')
						status1 = status1.decode('utf-8', 'strict')
						status = status1
					except:
						try:
							status1 = status.decode('utf-8', 'strict')
							status = status1
						except:
							try:
								status1 = status.decode(config.encoding, "strict")
								status = status1
							except:
								#status = "Wrong encoding:" + repr(status)
								status = str(status).decode("iso-8859-1", "replace")
		elif status:
			# this is a fallback solution in case that the client status encoding has not been extracted, to avoid raising an exception
			status = status.decode('utf-8', 'replace')
			LogEvent(WARN, self.session.jabberID, "Unknown status message encoding for %s" % user.name)
		else: # no status text
		    pass
		status = oscar.dehtml(status) # Removes any HTML tags

		if user.iconmd5sum != None and not config.disableAvatars and not config.avatarsOnlyOnChat:
			if self.oscarcon.legacyList.diffAvatar(user.name, md5Hash=binascii.hexlify(user.iconmd5sum)):
				LogEvent(INFO, self.session.jabberID, "Retrieving buddy icon for %s" % user.name)
				self.retrieveBuddyIconFromServer(user.name, user.iconmd5sum, user.icontype).addCallback(self.gotBuddyIconFromServer)
			else:
				LogEvent(INFO, self.session.jabberID, "Buddy icon is the same, using what we have for %s" % user.name)
			
		if user.caps:
			self.oscarcon.legacyList.setCapabilities(user.name, user.caps)
		if (user.customStatus and len(user.customStatus) > 0) or anstatus:
			self.oscarcon.legacyList.setCustomStatus(user.name, user.customStatus)
		else:
			mask = ('mood', 'activity', 'subactivity', 'text', 'usetune') # keep values for mood/activity
			self.oscarcon.legacyList.delCustomStatus(user.name, savemask=mask)
			
		LogEvent(INFO, self.session.jabberID, "Status message: %s" % status)
		
		if config.xstatusessupport:		
			if int(self.settingsOptionValue('xstatus_receiving_mode')) != 0:
				status5 = '' # status for ICQ5.1 mode
				status6 = '' # status for ICQ6 mode
				x_status_name = None
				requestForXStatus = True # need request for x-status details
				# icon
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 1 and int(self.settingsOptionEnabled('xstatus_option_smooth')) == 0: # in ICQ5.1 strict mode
					if 'icqmood' in user.customStatus: # ICQ6 mood
						del user.customStatus['icqmood'] # don't needed
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 2 and int(self.settingsOptionEnabled('xstatus_option_smooth')) == 0: # in ICQ6 strict mode
					if 'x-status' in user.customStatus: # ICQ5.1 x-status icon
						del user.customStatus['x-status'] # don't needed
				# get x-status name
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 2: # in ICQ 6 mode
					x_status_name = self.oscarcon.getXStatus(user.name, True)
				else:
					x_status_name = self.oscarcon.getXStatus(user.name)
				# text	
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 2:
					status6 = status
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 3: # mixed
					if 'icqmood' in user.customStatus and status != '': # already have icon and text of a status
						requestForXStatus = False
						status6 = status
					if selfcall == True:
						status6 = ''
				if int(self.settingsOptionValue('xstatus_receiving_mode')) in (1,3):
					x_status_title, x_status_desc = self.oscarcon.getXStatusDetails(user.name)
					if x_status_title != '' and x_status_desc != '':
						if x_status_title == ' ':
							status5 = x_status_desc
						elif x_status_desc == ' ':
							status5 = x_status_title
						else:
							status5 = x_status_title + ' ' + x_status_desc
					elif x_status_title == '' and x_status_desc != '':
						status5 = x_status_desc
					elif x_status_title != '' and x_status_desc == '':
						status5 = x_status_title
				# need choose status now
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 1:
					status = status5
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 2:
					status = status6
				if int(self.settingsOptionValue('xstatus_receiving_mode')) == 3:
					if len(status5) > len (status6):
						status = status5
					else:
						status = status6
				# displaying status icon as mood/activity
				mood = None
				act = None
				subact = None
				text = None
				usetune = False
				
				s_mood, s_act, s_subact, s_text, s_usetune = self.oscarcon.getPersonalEvents(user.name) # get Personal Events
				# ok. displaying via PEP enabled
				if self.settingsOptionEnabled('xstatus_display_text_as_PEP') or self.settingsOptionEnabled('xstatus_display_icon_as_PEP'):
					# mapping x-status -> mood/activity
					if self.settingsOptionEnabled('xstatus_display_icon_as_PEP'):
						if x_status_name != '' or anstatus: # x-status or additional normal status presents 
							mood_a = None
							act_a = None
							subact_a = None
							if anstatus in AN_STATUS_MAP:
								mood_a, act_a, subact_a = AN_STATUS_MAP[anstatus]
							if x_status_name in X_STATUS_MAP and x_status_name != 'xstatus_listening_to_music':	
								mood, act, subact = X_STATUS_MAP[x_status_name]
							elif x_status_name == 'xstatus_listening_to_music':
								usetune = True
						
							if not mood and mood_a: # if no mood from x-status
								mood = mood_a # get mood from additional normal status
							if not act and act_a: # if no activity from x-status
								act = act_a # get activity
								subact = subact_a # get subactivity
					# status text parsing and displaying as mood/activity
					if self.settingsOptionEnabled('xstatus_display_text_as_PEP'):
						if status != '' and int(self.settingsOptionValue('xstatus_receiving_mode')) in (2,3):
							mood_p = None
							act_p = None
							subact_p = None
									
							mood_p = self.parseAndSearchForMood(status)
							act_p, subact_p = self.parseAndSearchForActivity(status)
							
							if mood_p: # mood found in status text
								mood = mood_p # use mood from text
							if act_p: # activity found in status text
								act = act_p # use activity from text
								subact = subact_p # and subactivity from text too
					# additional text for mood/activity
					if status6 != '':
						text = status6
					elif status5 != '':
						text = status5
					# send personal events	
					mood, act, subact, usetune = self.sendPersonalEvents(buddyjid, mood, s_mood, act, s_act, subact, s_subact, text, s_text, usetune, s_usetune)	
				else:  # displaying disabled
					self.sendPersonalEventsStop(buddyjid, s_mood, s_act, s_subact, s_usetune)
					
				# no icon in roster. Impossible recognize or displaying disabled 
				if not mood and not act and not subact and not usetune: 
					if int(self.settingsOptionValue('xstatus_receiving_mode')) in (1,2,3):
						if status == '' and x_status_name != '':
							status = lang.get(x_status_name) # write standart name
						elif status != '' and x_status_name != '':
							if status != lang.get(x_status_name):
								status = lang.get(x_status_name) + ': ' + status # or add it as prefix
						if anstatus and anstatus != '':
							if status != '':
								status = '\n' + status
							status = lang.get(anstatus) + status
				
				self.oscarcon.setPersonalEvents(user.name, mood, act, subact, text, usetune) # set personal events
				# need send request for x-status details	
				if selfcall == False and requestForXStatus == True:
					if int(self.settingsOptionValue('xstatus_receiving_mode')) in (1,3):
						self.sendXstatusMessageRequestWithDelay(user.name) # request Xstatus message
			else:
				# x-status support disabled
				status = ''
				
		requestForAwayMsg = False
		if user.flags.count("away"):
			if int(self.settingsOptionEnabled('away_messages_receiving')):
				requestForAwayMsg = True
				
		if requestForAwayMsg == True:
			self.getAway(user.name).addCallback(self.sendAwayPresence, user, show, status)	
		else:
			if user.idleTime:
				if user.idleTime>60*24:
					idle_time = "Idle %d days"%(user.idleTime/(60*24))
					if not show: show = "xa"
				elif user.idleTime>60:
					idle_time = "Idle %d hours"%(user.idleTime/(60))
					if not show: show = "away"
				else:
					idle_time = "Idle %d minutes"%(user.idleTime)
				if status and status != '' and status != ' ':
					status="%s\n%s"%(idle_time,status)
				else:
					status=idle_time
					
			c.updatePresence(show=show, status=status, ptype=ptype, url=url)
			self.oscarcon.legacyList.updateSSIContact(user.name, presence=ptype, show=show, status=status, ipaddr=user.icqIPaddy, lanipaddr=user.icqLANIPaddy, lanipport=user.icqLANIPport, icqprotocol=user.icqProtocolVersion, url=url)
Пример #37
0
	def receiveMessage(self, user, multiparts, flags, delay=None):
		from glue import icq2jid

		LogEvent(INFO, self.session.jabberID, "%s %s %s" % (user.name, multiparts, flags))
		sourcejid = icq2jid(user.name)
		if len(multiparts) == 0:
			return # no data, illegal formed message
		if len(multiparts[0]) >= 1:
			text = multiparts[0][0]
		if len(multiparts[0]) > 1:
			if multiparts[0][1] == 'unicode':
				encoding = 'utf-16be'
			elif multiparts[0][1] == 'utf8':
				encoding = 'utf-8'
			elif multiparts[0][1] == 'custom': # can be any
				encoding = utils.guess_encoding_by_decode(text, self.userEncoding, 'minimal')[1] # try guess
			else:
				encoding = config.encoding
		else:
			encoding = self.userEncoding
		LogEvent(INFO, self.session.jabberID, "Using encoding %s" % (encoding))
		text = text.decode(encoding, "replace")
		xhtml = utils.prepxhtml(text)
		if not user.name[0].isdigit():
			text = oscar.dehtml(text)
		text = text.strip()
		mtype = "chat"
		if "auto" in flags:
			mtype = "headline"
 
 		offlinemessage = False
	    	for flag in flags:	
			if flag == 'offline':
				offlinemessage = True
		if offlinemessage == False:
			delay = None # Send timestamp to user if offline message

		if not (self.settingsOptionEnabled('autoanswer_enable') and self.settingsOptionEnabled('autoanswer_hide_dialog')): # send incoming message to jabber client
			self.session.sendMessage(to=self.session.jabberID, fro=sourcejid, body=text, mtype=mtype, delay=delay, xhtml=xhtml)
		self.session.pytrans.serviceplugins['Statistics'].stats['IncomingMessages'] += 1
		self.session.pytrans.serviceplugins['Statistics'].sessionUpdate(self.session.jabberID, 'IncomingMessages', 1)
		if self.settingsOptionEnabled('autoanswer_enable'):
			if self.settingsOptionExists('autoanswer_text'): # custom text
				autoanswer_text = self.settingsOptionValue('autoanswer_text')
			else: # text by default
				autoanswer_text = lang.get('autoanswer_text_content')
			if not self.settingsOptionEnabled('autoanswer_hide_dialog'): # send autoanswer reply to user
				self.session.sendMessage(to=self.session.jabberID, fro=sourcejid, body='%s %s' % (lang.get('autoanswer_prefix'), autoanswer_text), mtype=mtype, delay=delay, xhtml=xhtml)
			self.sendMessage(user.name, autoanswer_text) # send auto-answer text to contact
		if not config.disableAwayMessage and self.awayMessage and not "auto" in flags:
			if not self.awayResponses.has_key(user.name) or self.awayResponses[user.name] < (time.time() - 900):
				#self.sendMessage(user.name, "Away message: "+self.awayMessage.encode("iso-8859-1", "replace"), autoResponse=1)
				self.sendMessage(user.name, "Away message: "+self.awayMessage, autoResponse=1)
				self.awayResponses[user.name] = time.time()

		if "icon" in flags and not config.disableAvatars:
			if self.oscarcon.legacyList.diffAvatar(user.name, numHash=user.iconcksum):
				LogEvent(INFO, self.session.jabberID, "User %s has a buddy icon we want, will ask for it next message." % user.name)
				self.requesticon[user.name] = 1
			else:
				LogEvent(INFO, self.session.jabberID, "User %s has a icon that we already have." % user.name)

		if "iconrequest" in flags and hasattr(self.oscarcon, "myavatar") and not config.disableAvatars:
			LogEvent(INFO, self.session.jabberID, "User %s wants our icon, so we're sending it." % user.name)
			icondata = self.oscarcon.myavatar
			self.sendIconDirect(user.name, icondata, wantAck=1)
Пример #38
0
	def sendAwayPresence(self, msg, user, show, pstatus):
		from glue import icq2jid
		buddyjid = icq2jid(user.name)
		LogEvent(INFO, self.session.jabberID)

		c = self.session.contactList.findContact(buddyjid)
		if not c: return
		
		ptype = None
		idleTime = 0
		status = None
		url = None
		
		if msg[0] and msg[1] and len(msg[0]) == 4 and len(msg[1]) == 2: # online since time and idle time
			onlineSince = datetime.datetime.utcfromtimestamp(struct.unpack('!I',msg[0])[0])
			log.msg('User %s online since %sZ' % (user.name, onlineSince.isoformat()))
			idleTime = struct.unpack('!H',msg[1])[0]
			log.msg('User %s idle %s minutes' % (user.name, idleTime))
		else:
			status = msg[1]
			url = user.url

			if status != None:
				charset = "iso-8859-1"
				m = None
				if msg[0]:
					m = re.search('charset="(.+)"', msg[0])
				if m != None:
					charset = m.group(1)
					if charset == 'unicode-2-0':
						charset = 'utf-16be'
					elif charset == 'utf-8': pass
					elif charset == "us-ascii":
						charset = "iso-8859-1"
					elif charset == "iso-8859-1": pass
					elif charset == self.userEncoding: pass
					else:
						LogEvent(INFO, self.session.jabberID, "Unknown charset (%s) of buddy's away message" % msg[0]);
						charset = config.encoding
						status = msg[0] + ": " + status
	
				try:
					status = status.decode(charset, 'strict')
				except:
					pass
				try:
					status1 = status.encode(config.encoding, 'strict')
					status = status1.decode('utf-8', 'strict')
				except:
					if ord(status[0]) == 0 and ord(status[len(status)-1]) == 0:
						status = str(status[1:len(status)-1])
					try :
						status = str(status).decode('utf-8', 'strict')
					except:
						try:
							status = str(status).decode(config.encoding, 'strict')
						except:
							status = "Status decoding failed: " + status
				try:
					utfmsg = unicode(msg[0], errors='replace')
				except:
					utfmsg = msg[0]
				status = oscar.dehtml(status)
				LogEvent(INFO, self.session.jabberID, "Away (%s, %s) message %s" % (charset, utfmsg, status))
	
			if status == "Away" or status=="I am currently away from the computer." or status=="I am away from my computer right now.":
				status = ""
				
			if user.idleTime:
				idleTime = user.idleTime
				
		if idleTime:
			if idleTime>60*24:
				idle_time = "Idle %d days"%(idleTime/(60*24))
			elif idleTime>60:
				idle_time = "Idle %d hours"%(idleTime/(60))
			else:
				idle_time = "Idle %d minutes"%(idleTime)
			if status and status != '' and status != ' ':
				status="%s\n%s"%(idle_time,status)
			else:
				status=idle_time

		if status:
			if pstatus:
				status = status + '\n' + pstatus
		else:
			status = pstatus

		c.updatePresence(show=show, status=status, ptype=ptype)
		self.oscarcon.legacyList.updateSSIContact(user.name, presence=ptype, show=show, status=status, ipaddr=user.icqIPaddy, lanipaddr=user.icqLANIPaddy, lanipport=user.icqLANIPport, icqprotocol=user.icqProtocolVersion, url=url)