commands.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. ## $Id$
  2. ## Ad-Hoc Command manager
  3. ## Mike Albon (c) 5th January 2005
  4. ## This program is free software; you can redistribute it and/or modify
  5. ## it under the terms of the GNU General Public License as published by
  6. ## the Free Software Foundation; either version 2, or (at your option)
  7. ## any later version.
  8. ##
  9. ## This program is distributed in the hope that it will be useful,
  10. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ## GNU General Public License for more details.
  13. """This module is a ad-hoc command processor for xmpppy. It uses the plug-in mechanism like most of the core library. It depends on a DISCO browser manager.
  14. There are 3 classes here, a command processor Commands like the Browser, and a command template plugin Command, and an example command.
  15. To use this module:
  16. Instansiate the module with the parent transport and disco browser manager as parameters.
  17. 'Plug in' commands using the command template.
  18. The command feature must be added to existing disco replies where neccessary.
  19. What it supplies:
  20. Automatic command registration with the disco browser manager.
  21. Automatic listing of commands in the public command list.
  22. A means of handling requests, by redirection though the command manager.
  23. """
  24. from .protocol import *
  25. from .client import PlugIn
  26. class Commands(PlugIn):
  27. """Commands is an ancestor of PlugIn and can be attached to any session.
  28. The commands class provides a lookup and browse mechnism. It follows the same priciple of the Browser class, for Service Discovery to provide the list of commands, it adds the 'list' disco type to your existing disco handler function.
  29. How it works:
  30. The commands are added into the existing Browser on the correct nodes. When the command list is built the supplied discovery handler function needs to have a 'list' option in type. This then gets enumerated, all results returned as None are ignored.
  31. The command executed is then called using it's Execute method. All session management is handled by the command itself.
  32. """
  33. def __init__(self, browser):
  34. """Initialises class and sets up local variables"""
  35. PlugIn.__init__(self)
  36. DBG_LINE='commands'
  37. self._exported_methods=[]
  38. self._handlers={'':{}}
  39. self._browser = browser
  40. def plugin(self, owner):
  41. """Makes handlers within the session"""
  42. # Plug into the session and the disco manager
  43. # We only need get and set, results are not needed by a service provider, only a service user.
  44. owner.RegisterHandler('iq',self._CommandHandler,typ='set',ns=NS_COMMANDS)
  45. owner.RegisterHandler('iq',self._CommandHandler,typ='get',ns=NS_COMMANDS)
  46. self._browser.setDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid='')
  47. def plugout(self):
  48. """Removes handlers from the session"""
  49. # unPlug from the session and the disco manager
  50. self._owner.UnregisterHandler('iq',self._CommandHandler,ns=NS_COMMANDS)
  51. for jid in self._handlers:
  52. self._browser.delDiscoHandler(self._DiscoHandler,node=NS_COMMANDS)
  53. def _CommandHandler(self,conn,request):
  54. """The internal method to process the routing of command execution requests"""
  55. # This is the command handler itself.
  56. # We must:
  57. # Pass on command execution to command handler
  58. # (Do we need to keep session details here, or can that be done in the command?)
  59. jid = str(request.getTo())
  60. try:
  61. node = request.getTagAttr('command','node')
  62. except:
  63. conn.send(Error(request,ERR_BAD_REQUEST))
  64. raise NodeProcessed
  65. if jid in self._handlers:
  66. if node in self._handlers[jid]:
  67. self._handlers[jid][node]['execute'](conn,request)
  68. else:
  69. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  70. raise NodeProcessed
  71. elif node in self._handlers['']:
  72. self._handlers[''][node]['execute'](conn,request)
  73. else:
  74. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  75. raise NodeProcessed
  76. def _DiscoHandler(self,conn,request,typ):
  77. """The internal method to process service discovery requests"""
  78. # This is the disco manager handler.
  79. if typ == 'items':
  80. # We must:
  81. # Generate a list of commands and return the list
  82. # * This handler does not handle individual commands disco requests.
  83. # Pseudo:
  84. # Enumerate the 'item' disco of each command for the specified jid
  85. # Build responce and send
  86. # To make this code easy to write we add an 'list' disco type, it returns a tuple or 'none' if not advertised
  87. list = []
  88. items = []
  89. jid = str(request.getTo())
  90. # Get specific jid based results
  91. if jid in self._handlers:
  92. for each in list(self._handlers[jid].keys()):
  93. items.append((jid,each))
  94. else:
  95. # Get generic results
  96. for each in list(self._handlers[''].keys()):
  97. items.append(('',each))
  98. if items != []:
  99. for each in items:
  100. i = self._handlers[each[0]][each[1]]['disco'](conn,request,'list')
  101. if i != None:
  102. list.append(Node(tag='item',attrs={'jid':i[0],'node':i[1],'name':i[2]}))
  103. iq = request.buildReply('result')
  104. if request.getQuerynode(): iq.setQuerynode(request.getQuerynode())
  105. iq.setQueryPayload(list)
  106. conn.send(iq)
  107. else:
  108. conn.send(Error(request,ERR_ITEM_NOT_FOUND))
  109. raise NodeProcessed
  110. elif typ == 'info':
  111. return {'ids':[{'category':'automation','type':'command-list'}],'features':[]}
  112. def addCommand(self,name,cmddisco,cmdexecute,jid=''):
  113. """The method to call if adding a new command to the session, the requred parameters of cmddisco and cmdexecute are the methods to enable that command to be executed"""
  114. # This command takes a command object and the name of the command for registration
  115. # We must:
  116. # Add item into disco
  117. # Add item into command list
  118. if jid not in self._handlers:
  119. self._handlers[jid]={}
  120. self._browser.setDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid=jid)
  121. if name in self._handlers[jid]:
  122. raise NameError('Command Exists')
  123. else:
  124. self._handlers[jid][name]={'disco':cmddisco,'execute':cmdexecute}
  125. # Need to add disco stuff here
  126. self._browser.setDiscoHandler(cmddisco,node=name,jid=jid)
  127. def delCommand(self,name,jid=''):
  128. """Removed command from the session"""
  129. # This command takes a command object and the name used for registration
  130. # We must:
  131. # Remove item from disco
  132. # Remove item from command list
  133. if jid not in self._handlers:
  134. raise NameError('Jid not found')
  135. if name not in self._handlers[jid]:
  136. raise NameError('Command not found')
  137. else:
  138. #Do disco removal here
  139. command = self.getCommand(name,jid)['disco']
  140. del self._handlers[jid][name]
  141. self._browser.delDiscoHandler(command,node=name,jid=jid)
  142. def getCommand(self,name,jid=''):
  143. """Returns the command tuple"""
  144. # This gets the command object with name
  145. # We must:
  146. # Return item that matches this name
  147. if jid not in self._handlers:
  148. raise NameError('Jid not found')
  149. elif name not in self._handlers[jid]:
  150. raise NameError('Command not found')
  151. else:
  152. return self._handlers[jid][name]
  153. class Command_Handler_Prototype(PlugIn):
  154. """This is a prototype command handler, as each command uses a disco method
  155. and execute method you can implement it any way you like, however this is
  156. my first attempt at making a generic handler that you can hang process
  157. stages on too. There is an example command below.
  158. The parameters are as follows:
  159. name : the name of the command within the XMPP environment
  160. description : the natural language description
  161. discofeatures : the features supported by the command
  162. initial : the initial command in the from of {'execute':commandname}
  163. All stages set the 'actions' dictionary for each session to represent the possible options available.
  164. """
  165. name = 'examplecommand'
  166. count = 0
  167. description = 'an example command'
  168. discofeatures = [NS_COMMANDS,NS_DATA]
  169. # This is the command template
  170. def __init__(self,jid=''):
  171. """Set up the class"""
  172. PlugIn.__init__(self)
  173. DBG_LINE='command'
  174. self.sessioncount = 0
  175. self.sessions = {}
  176. # Disco information for command list pre-formatted as a tuple
  177. self.discoinfo = {'ids':[{'category':'automation','type':'command-node','name':self.description}],'features': self.discofeatures}
  178. self._jid = jid
  179. def plugin(self,owner):
  180. """Plug command into the commands class"""
  181. # The owner in this instance is the Command Processor
  182. self._commands = owner
  183. self._owner = owner._owner
  184. self._commands.addCommand(self.name,self._DiscoHandler,self.Execute,jid=self._jid)
  185. def plugout(self):
  186. """Remove command from the commands class"""
  187. self._commands.delCommand(self.name,self._jid)
  188. def getSessionID(self):
  189. """Returns an id for the command session"""
  190. self.count = self.count+1
  191. return 'cmd-%s-%d'%(self.name,self.count)
  192. def Execute(self,conn,request):
  193. """The method that handles all the commands, and routes them to the correct method for that stage."""
  194. # New request or old?
  195. try:
  196. session = request.getTagAttr('command','sessionid')
  197. except:
  198. session = None
  199. try:
  200. action = request.getTagAttr('command','action')
  201. except:
  202. action = None
  203. if action == None: action = 'execute'
  204. # Check session is in session list
  205. if session in self.sessions:
  206. if self.sessions[session]['jid']==request.getFrom():
  207. # Check action is vaild
  208. if action in self.sessions[session]['actions']:
  209. # Execute next action
  210. self.sessions[session]['actions'][action](conn,request)
  211. else:
  212. # Stage not presented as an option
  213. self._owner.send(Error(request,ERR_BAD_REQUEST))
  214. raise NodeProcessed
  215. else:
  216. # Jid and session don't match. Go away imposter
  217. self._owner.send(Error(request,ERR_BAD_REQUEST))
  218. raise NodeProcessed
  219. elif session != None:
  220. # Not on this sessionid you won't.
  221. self._owner.send(Error(request,ERR_BAD_REQUEST))
  222. raise NodeProcessed
  223. else:
  224. # New session
  225. self.initial[action](conn,request)
  226. def _DiscoHandler(self,conn,request,type):
  227. """The handler for discovery events"""
  228. if type == 'list':
  229. return (request.getTo(),self.name,self.description)
  230. elif type == 'items':
  231. return []
  232. elif type == 'info':
  233. return self.discoinfo
  234. class TestCommand(Command_Handler_Prototype):
  235. """ Example class. You should read source if you wish to understate how it works.
  236. Generally, it presents a "master" that giudes user through to calculate something.
  237. """
  238. name = 'testcommand'
  239. description = 'a noddy example command'
  240. def __init__(self,jid=''):
  241. """ Init internal constants. """
  242. Command_Handler_Prototype.__init__(self,jid)
  243. self.initial = {'execute':self.cmdFirstStage}
  244. def cmdFirstStage(self,conn,request):
  245. """ Determine """
  246. # This is the only place this should be repeated as all other stages should have SessionIDs
  247. try:
  248. session = request.getTagAttr('command','sessionid')
  249. except:
  250. session = None
  251. if session == None:
  252. session = self.getSessionID()
  253. self.sessions[session]={'jid':request.getFrom(),'actions':{'cancel':self.cmdCancel,'next':self.cmdSecondStage,'execute':self.cmdSecondStage},'data':{'type':None}}
  254. # As this is the first stage we only send a form
  255. reply = request.buildReply('result')
  256. form = DataForm(title='Select type of operation',data=['Use the combobox to select the type of calculation you would like to do, then click Next',DataField(name='calctype',desc='Calculation Type',value=self.sessions[session]['data']['type'],options=[['circlediameter','Calculate the Diameter of a circle'],['circlearea','Calculate the area of a circle']],typ='list-single',required=1)])
  257. replypayload = [Node('actions',attrs={'execute':'next'},payload=[Node('next')]),form]
  258. reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':session,'status':'executing'},payload=replypayload)
  259. self._owner.send(reply)
  260. raise NodeProcessed
  261. def cmdSecondStage(self,conn,request):
  262. form = DataForm(node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA))
  263. self.sessions[request.getTagAttr('command','sessionid')]['data']['type']=form.getField('calctype').getValue()
  264. self.sessions[request.getTagAttr('command','sessionid')]['actions']={'cancel':self.cmdCancel,None:self.cmdThirdStage,'previous':self.cmdFirstStage,'execute':self.cmdThirdStage,'next':self.cmdThirdStage}
  265. # The form generation is split out to another method as it may be called by cmdThirdStage
  266. self.cmdSecondStageReply(conn,request)
  267. def cmdSecondStageReply(self,conn,request):
  268. reply = request.buildReply('result')
  269. form = DataForm(title = 'Enter the radius', data=['Enter the radius of the circle (numbers only)',DataField(desc='Radius',name='radius',typ='text-single')])
  270. replypayload = [Node('actions',attrs={'execute':'complete'},payload=[Node('complete'),Node('prev')]),form]
  271. reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'executing'},payload=replypayload)
  272. self._owner.send(reply)
  273. raise NodeProcessed
  274. def cmdThirdStage(self,conn,request):
  275. form = DataForm(node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA))
  276. try:
  277. num = float(form.getField('radius').getValue())
  278. except:
  279. self.cmdSecondStageReply(conn,request)
  280. from math import pi
  281. if self.sessions[request.getTagAttr('command','sessionid')]['data']['type'] == 'circlearea':
  282. result = (num**2)*pi
  283. else:
  284. result = num*2*pi
  285. reply = request.buildReply('result')
  286. form = DataForm(typ='result',data=[DataField(desc='result',name='result',value=result)])
  287. reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'completed'},payload=[form])
  288. self._owner.send(reply)
  289. raise NodeProcessed
  290. def cmdCancel(self,conn,request):
  291. reply = request.buildReply('result')
  292. reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'cancelled'})
  293. self._owner.send(reply)
  294. del self.sessions[request.getTagAttr('command','sessionid')]