features.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. ## features.py
  2. ##
  3. ## Copyright (C) 2003-2004 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. # $Id$
  15. """
  16. This module contains variable stuff that is not worth splitting into separate modules.
  17. Here is:
  18. DISCO client and agents-to-DISCO and browse-to-DISCO emulators.
  19. IBR and password manager.
  20. jabber:iq:privacy methods
  21. All these methods takes 'disp' first argument that should be already connected
  22. (and in most cases already authorised) dispatcher instance.
  23. """
  24. from .protocol import *
  25. REGISTER_DATA_RECEIVED='REGISTER DATA RECEIVED'
  26. ### DISCO ### http://jabber.org/protocol/disco ### XEP-0030 ####################
  27. ### Browse ### jabber:iq:browse ### XEP-0030 ###################################
  28. ### Agents ### jabber:iq:agents ### XEP-0030 ###################################
  29. def _discover(disp,ns,jid,node=None,fb2b=0,fb2a=1):
  30. """ Try to obtain info from the remote object.
  31. If remote object doesn't support disco fall back to browse (if fb2b is true)
  32. and if it doesnt support browse (or fb2b is not true) fall back to agents protocol
  33. (if gb2a is true). Returns obtained info. Used internally. """
  34. iq=Iq(to=jid,typ='get',queryNS=ns)
  35. if node: iq.setQuerynode(node)
  36. rep=disp.SendAndWaitForResponse(iq)
  37. if fb2b and not isResultNode(rep): rep=disp.SendAndWaitForResponse(Iq(to=jid,typ='get',queryNS=NS_BROWSE)) # Fallback to browse
  38. if fb2a and not isResultNode(rep): rep=disp.SendAndWaitForResponse(Iq(to=jid,typ='get',queryNS=NS_AGENTS)) # Fallback to agents
  39. if isResultNode(rep): return [n for n in rep.getQueryPayload() if isinstance(n, Node)]
  40. return []
  41. def discoverItems(disp,jid,node=None):
  42. """ Query remote object about any items that it contains. Return items list. """
  43. """ According to XEP-0030:
  44. query MAY have node attribute
  45. item: MUST HAVE jid attribute and MAY HAVE name, node, action attributes.
  46. action attribute of item can be either of remove or update value."""
  47. ret=[]
  48. for i in _discover(disp,NS_DISCO_ITEMS,jid,node):
  49. if i.getName()=='agent' and i.getTag('name'): i.setAttr('name',i.getTagData('name'))
  50. ret.append(i.attrs)
  51. return ret
  52. def discoverInfo(disp,jid,node=None):
  53. """ Query remote object about info that it publishes. Returns identities and features lists."""
  54. """ According to XEP-0030:
  55. query MAY have node attribute
  56. identity: MUST HAVE category and name attributes and MAY HAVE type attribute.
  57. feature: MUST HAVE var attribute"""
  58. identities , features = [] , []
  59. for i in _discover(disp,NS_DISCO_INFO,jid,node):
  60. if i.getName()=='identity': identities.append(i.attrs)
  61. elif i.getName()=='feature': features.append(i.getAttr('var'))
  62. elif i.getName()=='agent':
  63. if i.getTag('name'): i.setAttr('name',i.getTagData('name'))
  64. if i.getTag('description'): i.setAttr('name',i.getTagData('description'))
  65. identities.append(i.attrs)
  66. if i.getTag('groupchat'): features.append(NS_GROUPCHAT)
  67. if i.getTag('register'): features.append(NS_REGISTER)
  68. if i.getTag('search'): features.append(NS_SEARCH)
  69. return identities , features
  70. ### Registration ### jabber:iq:register ### XEP-0077 ###########################
  71. def getRegInfo(disp,host,info={},sync=True):
  72. """ Gets registration form from remote host.
  73. You can pre-fill the info dictionary.
  74. F.e. if you are requesting info on registering user joey than specify
  75. info as {'username':'joey'}. See XEP-0077 for details.
  76. 'disp' must be connected dispatcher instance."""
  77. iq=Iq('get',NS_REGISTER,to=host)
  78. for i in list(info.keys()): iq.setTagData(i,info[i])
  79. if sync:
  80. resp=disp.SendAndWaitForResponse(iq)
  81. _ReceivedRegInfo(disp.Dispatcher,resp, host)
  82. return resp
  83. else: disp.SendAndCallForResponse(iq,_ReceivedRegInfo, {'agent': host})
  84. def _ReceivedRegInfo(con, resp, agent):
  85. iq=Iq('get',NS_REGISTER,to=agent)
  86. if not isResultNode(resp): return
  87. df=resp.getTag('query',namespace=NS_REGISTER).getTag('x',namespace=NS_DATA)
  88. if df:
  89. con.Event(NS_REGISTER,REGISTER_DATA_RECEIVED,(agent, DataForm(node=df)))
  90. return
  91. df=DataForm(typ='form')
  92. for i in resp.getQueryPayload():
  93. if type(i)!=type(iq): pass
  94. elif i.getName()=='instructions': df.addInstructions(i.getData())
  95. else: df.setField(i.getName()).setValue(i.getData())
  96. con.Event(NS_REGISTER,REGISTER_DATA_RECEIVED,(agent, df))
  97. def register(disp,host,info):
  98. """ Perform registration on remote server with provided info.
  99. disp must be connected dispatcher instance.
  100. Returns true or false depending on registration result.
  101. If registration fails you can get additional info from the dispatcher's owner
  102. attributes lastErrNode, lastErr and lastErrCode.
  103. """
  104. iq=Iq('set',NS_REGISTER,to=host)
  105. if type(info)!=type({}): info=info.asDict()
  106. for i in list(info.keys()): iq.setTag('query').setTagData(i,info[i])
  107. resp=disp.SendAndWaitForResponse(iq)
  108. if isResultNode(resp): return 1
  109. def unregister(disp,host):
  110. """ Unregisters with host (permanently removes account).
  111. disp must be connected and authorized dispatcher instance.
  112. Returns true on success."""
  113. resp=disp.SendAndWaitForResponse(Iq('set',NS_REGISTER,to=host,payload=[Node('remove')]))
  114. if isResultNode(resp): return 1
  115. def changePasswordTo(disp,newpassword,host=None):
  116. """ Changes password on specified or current (if not specified) server.
  117. disp must be connected and authorized dispatcher instance.
  118. Returns true on success."""
  119. if not host: host=disp._owner.Server
  120. resp=disp.SendAndWaitForResponse(Iq('set',NS_REGISTER,to=host,payload=[Node('username',payload=[disp._owner.Server]),Node('password',payload=[newpassword])]))
  121. if isResultNode(resp): return 1
  122. ### Privacy ### jabber:iq:privacy ### draft-ietf-xmpp-im-19 ####################
  123. #type=[jid|group|subscription]
  124. #action=[allow|deny]
  125. def getPrivacyLists(disp):
  126. """ Requests privacy lists from connected server.
  127. Returns dictionary of existing lists on success."""
  128. try:
  129. dict={'lists':[]}
  130. resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY))
  131. if not isResultNode(resp): return
  132. for list in resp.getQueryPayload():
  133. if list.getName()=='list': dict['lists'].append(list.getAttr('name'))
  134. else: dict[list.getName()]=list.getAttr('name')
  135. return dict
  136. except: pass
  137. def getPrivacyList(disp,listname):
  138. """ Requests specific privacy list listname. Returns list of XML nodes (rules)
  139. taken from the server responce."""
  140. try:
  141. resp=disp.SendAndWaitForResponse(Iq('get',NS_PRIVACY,payload=[Node('list',{'name':listname})]))
  142. if isResultNode(resp): return resp.getQueryPayload()[0]
  143. except: pass
  144. def setActivePrivacyList(disp,listname=None,typ='active'):
  145. """ Switches privacy list 'listname' to specified type.
  146. By default the type is 'active'. Returns true on success."""
  147. if listname: attrs={'name':listname}
  148. else: attrs={}
  149. resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[Node(typ,attrs)]))
  150. if isResultNode(resp): return 1
  151. def setDefaultPrivacyList(disp,listname=None):
  152. """ Sets the default privacy list as 'listname'. Returns true on success."""
  153. return setActivePrivacyList(disp,listname,'default')
  154. def setPrivacyList(disp,list):
  155. """ Set the ruleset. 'list' should be the simpleXML node formatted
  156. according to RFC 3921 (XMPP-IM) (I.e. Node('list',{'name':listname},payload=[...]) )
  157. Returns true on success."""
  158. resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[list]))
  159. if isResultNode(resp): return 1
  160. def delPrivacyList(disp,listname):
  161. """ Deletes privacy list 'listname'. Returns true on success."""
  162. resp=disp.SendAndWaitForResponse(Iq('set',NS_PRIVACY,payload=[Node('list',{'name':listname})]))
  163. if isResultNode(resp): return 1