Package xmpp :: Module roster

[hide private]
[frames] | no frames]

# Source Code for Module xmpp.roster

      1  ##   roster.py
      2  ##
      3  ##   Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
      4  ##
      5  ##   This program is free software; you can redistribute it and/or modify
      6  ##   it under the terms of the GNU General Public License as published by
      7  ##   the Free Software Foundation; either version 2, or (at your option)
      8  ##   any later version.
      9  ##
     10  ##   This program is distributed in the hope that it will be useful,
     11  ##   but WITHOUT ANY WARRANTY; without even the implied warranty of
     12  ##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13  ##   GNU General Public License for more details.
     14
     15  # $Id: roster.py,v 1.20 2005/07/13 13:22:52 snakeru Exp $
     16
     17  """
     18  Simple roster implementation. Can be used though for different tasks like
     19  mass-renaming of contacts.
     20  """
     21
     22  from protocol import *
     23  from client import PlugIn
     24
     25 -class Roster(PlugIn):
     26      """ Defines a plenty of methods that will allow you to manage roster.
     27          Also automatically track presences from remote JIDs taking into
     28          account that every JID can have multiple resources connected. Does not
     29          currently support 'error' presences.
     30          You can also use mapping interface for access to the internal representation of
     31          contacts in roster.
     32          """
     33 -    def __init__(self):
     34          """ Init internal variables. """
     35          PlugIn.__init__(self)
     36          self.DBG_LINE='roster'
     37          self._data = {}
     38          self.set=None
     39          self._exported_methods=[self.getRoster]
     40
     41 -    def plugin(self,owner,request=1):
     42          """ Register presence and subscription trackers in the owner's dispatcher.
     43              Also request roster from server if the 'request' argument is set.
     44              Used internally."""
     45          self._owner.RegisterHandler('iq',self.RosterIqHandler,'result',NS_ROSTER)
     46          self._owner.RegisterHandler('iq',self.RosterIqHandler,'set',NS_ROSTER)
     47          self._owner.RegisterHandler('presence',self.PresenceHandler)
     48          if request: self.Request()
     49
     50 -    def Request(self,force=0):
     51          """ Request roster from server if it were not yet requested
     52              (or if the 'force' argument is set). """
     53          if self.set is None: self.set=0
     54          elif not force: return
     55          self._owner.send(Iq('get',NS_ROSTER))
     56          self.DEBUG('Roster requested from server','start')
     57
     58 -    def getRoster(self):
     59          """ Requests roster from server if neccessary and returns self."""
     60          if not self.set: self.Request()
     61          while not self.set: self._owner.Process(10)
     62          return self
     63
     64 -    def RosterIqHandler(self,dis,stanza):
     65          """ Subscription tracker. Used internally for setting items state in
     66              internal roster representation. """
     67          for item in stanza.getTag('query').getTags('item'):
     68              jid=item.getAttr('jid')
     69              if item.getAttr('subscription')=='remove':
     70                  if self._data.has_key(jid): del self._data[jid]
     71                  raise NodeProcessed             # a MUST
     72              self.DEBUG('Setting roster item %s...'%jid,'ok')
     73              if not self._data.has_key(jid): self._data[jid]={}
     74              self._data[jid]['name']=item.getAttr('name')
     75              self._data[jid]['ask']=item.getAttr('ask')
     76              self._data[jid]['subscription']=item.getAttr('subscription')
     77              self._data[jid]['groups']=[]
     78              if not self._data[jid].has_key('resources'): self._data[jid]['resources']={}
     79              for group in item.getTags('group'): self._data[jid]['groups'].append(group.getData())
     80          self._data[self._owner.User+'@'+self._owner.Server]={'resources':{},'name':None,'ask':None,'subscription':None,'groups':None,}
     81          self.set=1
     82          raise NodeProcessed   # a MUST. Otherwise you'll get back an <iq type='error'/>
     83
     84 -    def PresenceHandler(self,dis,pres):
     85          """ Presence tracker. Used internally for setting items' resources state in
     86              internal roster representation. """
     87          jid=JID(pres.getFrom())
     88          if not self._data.has_key(jid.getStripped()): self._data[jid.getStripped()]={'name':None,'ask':None,'subscription':'none','groups':['Not in roster'],'resources':{}}
     89
     90          item=self._data[jid.getStripped()]
     91          typ=pres.getType()
     92
     93          if not typ:
     94              self.DEBUG('Setting roster item %s for resource %s...'%(jid.getStripped(),jid.getResource()),'ok')
     95              item['resources'][jid.getResource()]=res={'show':None,'status':None,'priority':'0','timestamp':None}
     96              if pres.getTag('show'): res['show']=pres.getShow()
     97              if pres.getTag('status'): res['status']=pres.getStatus()
     98              if pres.getTag('priority'): res['priority']=pres.getPriority()
     99              if not pres.getTimestamp(): pres.setTimestamp()
    100              res['timestamp']=pres.getTimestamp()
    101          elif typ=='unavailable' and item['resources'].has_key(jid.getResource()): del item['resources'][jid.getResource()]
    102          # Need to handle type='error' also
    103
    104 -    def _getItemData(self,jid,dataname):
    105          """ Return specific jid's representation in internal format. Used internally. """
    106          jid=jid[:(jid+'/').find('/')]
    107          return self._data[jid][dataname]
    108 -    def _getResourceData(self,jid,dataname):
    109          """ Return specific jid's resource representation in internal format. Used internally. """
    110          if jid.find('/')+1:
    111              jid,resource=jid.split('/',1)
    112              if self._data[jid]['resources'].has_key(resource): return self._data[jid]['resources'][resource][dataname]
    113          elif self._data[jid]['resources'].keys():
    114              lastpri=-129
    115              for r in self._data[jid]['resources'].keys():
    116                  if int(self._data[jid]['resources'][r]['priority'])>lastpri: resource,lastpri=r,int(self._data[jid]['resources'][r]['priority'])
    117              return self._data[jid]['resources'][resource][dataname]
    118 -    def delItem(self,jid):
    119          """ Delete contact 'jid' from roster."""
    120          self._owner.send(Iq('set',NS_ROSTER,payload=[Node('item',{'jid':jid,'subscription':'remove'})]))
    121 -    def getAsk(self,jid):
    122          """ Returns 'ask' value of contact 'jid'."""
    123          return self._getItemData(jid,'ask')
    124 -    def getGroups(self,jid):
    125          """ Returns groups list that contact 'jid' belongs to."""
    126          return self._getItemData(jid,'groups')
    127 -    def getName(self,jid):
    128          """ Returns name of contact 'jid'."""
    129          return self._getItemData(jid,'name')
    130 -    def getPriority(self,jid):
    131          """ Returns priority of contact 'jid'. 'jid' should be a full (not bare) JID."""
    132          return self._getResourceData(jid,'priority')
    133 -    def getRawRoster(self):
    134          """ Returns roster representation in internal format. """
    135          return self._data
    136 -    def getRawItem(self,jid):
    137          """ Returns roster item 'jid' representation in internal format. """
    138          return self._data[jid[:(jid+'/').find('/')]]
    139 -    def getShow(self, jid):
    140          """ Returns 'show' value of contact 'jid'. 'jid' should be a full (not bare) JID."""
    141          return self._getResourceData(jid,'show')
    142 -    def getStatus(self, jid):
    143          """ Returns 'status' value of contact 'jid'. 'jid' should be a full (not bare) JID."""
    144          return self._getResourceData(jid,'status')
    145 -    def getSubscription(self,jid):
    146          """ Returns 'subscription' value of contact 'jid'."""
    147          return self._getItemData(jid,'subscription')
    148 -    def getResources(self,jid):
    149          """ Returns list of connected resources of contact 'jid'."""
    150          return self._data[jid[:(jid+'/').find('/')]]['resources'].keys()
    151 -    def setItem(self,jid,name=None,groups=[]):
    152          """ Creates/renames contact 'jid' and sets the groups list that it now belongs to."""
    153          iq=Iq('set',NS_ROSTER)
    154          query=iq.getTag('query')
    155          attrs={'jid':jid}
    156          if name: attrs['name']=name
    157          item=query.setTag('item',attrs)
    158          for group in groups: item.addChild(node=Node('group',payload=[group]))
    159          self._owner.send(iq)
    160 -    def getItems(self):
    161          """ Return list of all [bare] JIDs that the roster is currently tracks."""
    162          return self._data.keys()
    163 -    def keys(self):
    164          """ Same as getItems. Provided for the sake of dictionary interface."""
    165          return self._data.keys()
    166 -    def __getitem__(self,item):
    167          """ Get the contact in the internal format. Raises KeyError if JID 'item' is not in roster."""
    168          return self._data[item]
    169 -    def getItem(self,item):
    170          """ Get the contact in the internal format (or None if JID 'item' is not in roster)."""
    171          if self._data.has_key(item): return self._data[item]
    172 -    def Subscribe(self,jid):
    173          """ Send subscription request to JID 'jid'."""
    174          self._owner.send(Presence(jid,'subscribe'))
    175 -    def Unsubscribe(self,jid):
    176          """ Ask for removing our subscription for JID 'jid'."""
    177          self._owner.send(Presence(jid,'unsubscribe'))
    178 -    def Authorize(self,jid):
    179          """ Authorise JID 'jid'. Works only if these JID requested auth previously. """
    180          self._owner.send(Presence(jid,'subscribed'))
    181 -    def Unauthorize(self,jid):
    182          """ Unauthorise JID 'jid'. Use for declining authorisation request
    183              or for removing existing authorization. """
    184          self._owner.send(Presence(jid,'unsubscribed'))
    185