Forked mumble-django project from https://bitbucket.org/Svedrin/mumble-django
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

460 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright (C) 200, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * Mumble-Django is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This package is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. """
  16. import simplejson
  17. import inspect
  18. import functools
  19. import traceback
  20. from sys import stderr
  21. from django import forms
  22. from django.http import HttpResponse
  23. from django.conf import settings
  24. from django.conf.urls.defaults import patterns, url
  25. from django.core.urlresolvers import reverse
  26. from django.utils.datastructures import MultiValueDictKeyError
  27. from django.views.decorators.csrf import csrf_exempt
  28. from django.utils.safestring import mark_safe
  29. def getname( cls_or_name ):
  30. if type(cls_or_name) not in ( str, unicode ):
  31. return cls_or_name.__name__
  32. return cls_or_name
  33. # Template used for the auto-generated form classes
  34. EXT_CLASS_TEMPLATE = """
  35. Ext.namespace('Ext.ux');
  36. Ext.ux.%(clsname)s = function( config ){
  37. Ext.apply( this, config );
  38. var defaultconf = %(defaultconf)s;
  39. Ext.applyIf( this, defaultconf );
  40. this.initialConfig = defaultconf;
  41. Ext.ux.%(clsname)s.superclass.constructor.call( this );
  42. this.form.api = %(apiconf)s;
  43. this.form.paramsAsHash = true;
  44. }
  45. Ext.extend( Ext.ux.%(clsname)s, Ext.form.FormPanel, {} );
  46. Ext.reg( '%(clslowername)s', Ext.ux.%(clsname)s );
  47. """
  48. # About the this.form.* lines, see
  49. # http://www.sencha.com/forum/showthread.php?96001-solved-Ext.Direct-load-data-in-extended-Form-fails-%28scope-issue%29
  50. class Provider( object ):
  51. """ Provider for Ext.Direct. This class handles building API information and
  52. routing requests to the appropriate functions, and serializing their
  53. response and exceptions - if any.
  54. Instantiation:
  55. >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )
  56. If autoadd is True, the api.js will include a line like such:
  57. Ext.Direct.addProvider( Ext.app.REMOTING_API );
  58. After instantiating the Provider, register functions to it like so:
  59. >>> @EXT_JS_PROVIDER.register_method("myclass")
  60. ... def myview( request, possibly, some, other, arguments ):
  61. ... " does something with all those args and returns something "
  62. ... return 13.37
  63. Note that those views **MUST NOT** return an HttpResponse but simply
  64. the plain result, as the Provider will build a response from whatever
  65. your view returns!
  66. To be able to access the Provider, include its URLs in an arbitrary
  67. URL pattern, like so:
  68. >>> from views import EXT_JS_PROVIDER # import our provider instance
  69. >>> urlpatterns = patterns(
  70. ... # other patterns go here
  71. ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  72. ... )
  73. This way, the Provider will define the URLs "api/api.js" and "api/router".
  74. If you then access the "api/api.js" URL, you will get a response such as::
  75. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  76. "url": "/mumble/api/router",
  77. "type": "remoting",
  78. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  79. }
  80. You can then use this code in ExtJS to define the Provider there.
  81. """
  82. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  83. self.name = name
  84. self.autoadd = autoadd
  85. self.classes = {}
  86. self.forms = {}
  87. def register_method( self, cls_or_name, flags={} ):
  88. """ Return a function that takes a method as an argument and adds that
  89. to cls_or_name.
  90. The flags parameter is for additional information, e.g. formHandler=True.
  91. Note: This decorator does not replace the method by a new function,
  92. it returns the original function as-is.
  93. """
  94. return functools.partial( self._register_method, cls_or_name, flags=flags )
  95. def _register_method( self, cls_or_name, method, flags={} ):
  96. """ Actually registers the given function as a method of cls_or_name. """
  97. clsname = getname(cls_or_name)
  98. if clsname not in self.classes:
  99. self.classes[clsname] = {}
  100. self.classes[ clsname ][ method.__name__ ] = method
  101. method.EXT_argnames = inspect.getargspec( method ).args[1:]
  102. method.EXT_len = len( method.EXT_argnames )
  103. method.EXT_flags = flags
  104. return method
  105. def register_form( self, formclass ):
  106. """ Register a Django Form class for handling teh stuffz, yoo know. """
  107. formname = formclass.__name__.lower()
  108. self.forms[formname] = formclass
  109. getfunc = functools.partial( self.get_form_data, formname )
  110. getfunc.EXT_len = 1
  111. getfunc.EXT_argnames = ["pk"]
  112. getfunc.EXT_flags = {}
  113. updatefunc = functools.partial( self.update_form_data, formname )
  114. updatefunc.EXT_len = 1
  115. updatefunc.EXT_argnames = ["pk"]
  116. updatefunc.EXT_flags = { 'formHandler': True }
  117. self.classes["XD_%s"%formclass.__name__] = {
  118. "get": getfunc,
  119. "update": updatefunc,
  120. }
  121. return formclass
  122. @csrf_exempt
  123. def get_api( self, request ):
  124. """ Introspect the methods and get a JSON description of this API. """
  125. actdict = {}
  126. for clsname in self.classes:
  127. actdict[clsname] = []
  128. for methodname in self.classes[clsname]:
  129. methinfo = {
  130. "name": methodname,
  131. "len": self.classes[clsname][methodname].EXT_len
  132. }
  133. methinfo.update( self.classes[clsname][methodname].EXT_flags )
  134. actdict[clsname].append( methinfo )
  135. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  136. "url": reverse( self.request ),
  137. "type": "remoting",
  138. "actions": actdict
  139. }))]
  140. if self.autoadd:
  141. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  142. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  143. @csrf_exempt
  144. def request( self, request ):
  145. """ Implements the Router part of the Ext.Direct specification.
  146. It handles decoding requests, calling the appropriate function (if
  147. found) and encoding the response / exceptions.
  148. """
  149. try:
  150. rawjson = simplejson.loads( request.raw_post_data )
  151. except simplejson.JSONDecodeError:
  152. # possibly a form submit / upload
  153. try:
  154. jsoninfo = {
  155. 'action': request.POST['extAction'],
  156. 'method': request.POST['extMethod'],
  157. 'type': request.POST['extType'],
  158. 'upload': request.POST['extUpload'],
  159. 'tid': request.POST['extTID'],
  160. }
  161. except (MultiValueDictKeyError, KeyError):
  162. # malformed request
  163. return HttpResponse( simplejson.dumps({
  164. 'type': 'exception',
  165. 'message': 'malformed request',
  166. 'where': 'router',
  167. "tid": tid,
  168. }), mimetype="text/javascript" )
  169. else:
  170. return self.process_form_request( request, jsoninfo )
  171. if not isinstance( rawjson, list ):
  172. rawjson = [rawjson]
  173. responses = []
  174. for reqinfo in rawjson:
  175. cls, methname, data, rtype, tid = (reqinfo['action'],
  176. reqinfo['method'],
  177. reqinfo['data'],
  178. reqinfo['type'],
  179. reqinfo['tid'])
  180. if cls not in self.classes:
  181. responses.append({
  182. 'type': 'exception',
  183. 'message': 'no such action',
  184. 'where': cls,
  185. "tid": tid,
  186. })
  187. continue
  188. if methname not in self.classes[cls]:
  189. responses.append({
  190. 'type': 'exception',
  191. 'message': 'no such method',
  192. 'where': methname,
  193. "tid": tid,
  194. })
  195. continue
  196. func = self.classes[cls][methname]
  197. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  198. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  199. args = []
  200. for argname in func.EXT_argnames:
  201. if argname in data[0]:
  202. args.append( data[0][argname] )
  203. else:
  204. args = None
  205. break
  206. if args:
  207. data = args
  208. try:
  209. if data:
  210. result = func( request, *data )
  211. else:
  212. result = func( request )
  213. except Exception, err:
  214. errinfo = {
  215. 'type': 'exception',
  216. "tid": tid,
  217. }
  218. if settings.DEBUG:
  219. traceback.print_exc( file=stderr )
  220. errinfo['message'] = unicode(err)
  221. errinfo['where'] = traceback.format_exc()
  222. else:
  223. errinfo['message'] = 'The socket packet pocket has an error to report.'
  224. errinfo['where'] = ''
  225. responses.append(errinfo)
  226. else:
  227. responses.append({
  228. "type": rtype,
  229. "tid": tid,
  230. "action": cls,
  231. "method": methname,
  232. "result": result
  233. })
  234. if len(responses) == 1:
  235. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  236. else:
  237. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  238. def process_form_request( self, request, reqinfo ):
  239. """ Router for POST requests that submit form data and/or file uploads. """
  240. cls, methname, rtype, tid = (reqinfo['action'],
  241. reqinfo['method'],
  242. reqinfo['type'],
  243. reqinfo['tid'])
  244. if cls not in self.classes:
  245. response = {
  246. 'type': 'exception',
  247. 'message': 'no such action',
  248. 'where': cls,
  249. "tid": tid,
  250. }
  251. elif methname not in self.classes[cls]:
  252. response = {
  253. 'type': 'exception',
  254. 'message': 'no such method',
  255. 'where': methname,
  256. "tid": tid,
  257. }
  258. else:
  259. func = self.classes[cls][methname]
  260. try:
  261. result = func( request )
  262. except Exception, err:
  263. errinfo = {
  264. 'type': 'exception',
  265. "tid": tid,
  266. }
  267. if settings.DEBUG:
  268. traceback.print_exc( file=stderr )
  269. errinfo['message'] = unicode(err)
  270. errinfo['where'] = traceback.format_exc()
  271. else:
  272. errinfo['message'] = 'The socket packet pocket has an error to report.'
  273. errinfo['where'] = ''
  274. response = errinfo
  275. else:
  276. response = {
  277. "type": rtype,
  278. "tid": tid,
  279. "action": cls,
  280. "method": methname,
  281. "result": result
  282. }
  283. if reqinfo['upload'] == "true":
  284. return HttpResponse(
  285. "<html><body><textarea>%s</textarea></body></html>" % simplejson.dumps(response),
  286. mimetype="text/javascript"
  287. )
  288. else:
  289. return HttpResponse( simplejson.dumps( response ), mimetype="text/javascript" )
  290. def get_form( self, request, formname ):
  291. """ Convert the form given in "formname" to an ExtJS FormPanel. """
  292. items = []
  293. clsname = self.forms[formname].__name__
  294. for fldname in self.forms[formname].base_fields:
  295. field = self.forms[formname].base_fields[fldname]
  296. extfld = {
  297. "fieldLabel": field.label is not None and unicode(field.label) or fldname,
  298. "name": fldname,
  299. "xtype": "textfield",
  300. #"allowEmpty": field.required,
  301. }
  302. if hasattr( field, "choices" ) and field.choices:
  303. extfld.update({
  304. "name": fldname,
  305. "hiddenName": fldname,
  306. "xtype": "combo",
  307. "store": field.choices,
  308. "typeAhead": True,
  309. "emptyText": 'Select...',
  310. "triggerAction": 'all',
  311. "selectOnFocus": True,
  312. })
  313. elif isinstance( field, forms.BooleanField ):
  314. extfld.update({
  315. "xtype": "checkbox"
  316. })
  317. elif isinstance( field, forms.IntegerField ):
  318. extfld.update({
  319. "xtype": "numberfield",
  320. })
  321. elif isinstance( field, forms.FileField ) or isinstance( field, forms.ImageField ):
  322. extfld.update({
  323. "xtype": "textfield",
  324. "inputType": "file"
  325. })
  326. elif isinstance( field.widget, forms.Textarea ):
  327. extfld.update({
  328. "xtype": "textarea",
  329. })
  330. elif isinstance( field.widget, forms.PasswordInput ):
  331. extfld.update({
  332. "xtype": "textfield",
  333. "inputType": "password"
  334. })
  335. items.append( extfld )
  336. if field.help_text:
  337. items.append({
  338. "xtype": "label",
  339. "text": unicode(field.help_text),
  340. "cls": "form_hint_label",
  341. })
  342. clscode = EXT_CLASS_TEMPLATE % {
  343. 'clsname': clsname,
  344. 'clslowername': formname,
  345. 'defaultconf': simplejson.dumps({
  346. 'items': items,
  347. 'defaults': { "anchor": "-20px" },
  348. 'paramsAsHash': True,
  349. }, indent=4 ),
  350. 'apiconf': ('{'
  351. 'load: ' + ("XD_%s.get" % clsname) + ","
  352. 'submit:' + ("XD_%s.update" % clsname) + ","
  353. "}"),
  354. }
  355. return HttpResponse( mark_safe( clscode ), mimetype="text/javascript" )
  356. def get_form_data( self, formname, request, pk ):
  357. formcls = self.forms[formname]
  358. instance = formcls.Meta.model.objects.get( pk=pk )
  359. forminst = formcls( instance=instance )
  360. data = {}
  361. for fld in forminst.fields:
  362. data[fld] = getattr( instance, fld )
  363. return { 'data': data, 'success': True }
  364. def update_form_data( self, formname, request ):
  365. pk = request.POST['pk']
  366. formcls = self.forms[formname]
  367. instance = formcls.Meta.model.objects.get( pk=pk )
  368. forminst = formcls( request.POST, instance=instance )
  369. if forminst.is_valid():
  370. forminst.save()
  371. return { 'success': True }
  372. else:
  373. errdict = {}
  374. for errfld in forminst.errors:
  375. errdict[errfld] = "\n".join( forminst.errors[errfld] )
  376. return { 'success': False, 'errors': errdict }
  377. @property
  378. def urls(self):
  379. """ Return the URL patterns. """
  380. pat = patterns('',
  381. (r'api.js$', self.get_api ),
  382. (r'router/?', self.request ),
  383. )
  384. if self.forms:
  385. pat.append( url( r'(?P<formname>\w+).js$', self.get_form ) )
  386. return pat