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.

519 lines
19 KiB

  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright (C) 2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * djExtDirect 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, Http404
  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. __author__ = "Michael Ziegler"
  30. __copyright__ = "Copyright (C) 2010, Michael Ziegler"
  31. __license__ = "GPL"
  32. __version__ = "0.1"
  33. __email__ = "diese-addy@funzt-halt.net"
  34. __status__ = "Development"
  35. def getname( cls_or_name ):
  36. if type(cls_or_name) not in ( str, unicode ):
  37. return cls_or_name.__name__
  38. return cls_or_name
  39. # Template used for the auto-generated form classes
  40. EXT_CLASS_TEMPLATE = """
  41. Ext.namespace('Ext.ux');
  42. Ext.ux.%(clsname)s = function( config ){
  43. Ext.apply( this, config );
  44. var defaultconf = %(defaultconf)s;
  45. Ext.applyIf( this, defaultconf );
  46. this.initialConfig = defaultconf;
  47. Ext.ux.%(clsname)s.superclass.constructor.call( this );
  48. this.form.api = %(apiconf)s;
  49. this.form.paramsAsHash = true;
  50. if( typeof config.pk != "undefined" ){
  51. this.load();
  52. }
  53. }
  54. Ext.extend( Ext.ux.%(clsname)s, Ext.form.FormPanel, {
  55. load: function(){
  56. this.getForm().load({ params: {pk: this.pk} });
  57. },
  58. submit: function(){
  59. this.getForm().submit({ params: {pk: this.pk} });
  60. },
  61. } );
  62. Ext.reg( '%(clslowername)s', Ext.ux.%(clsname)s );
  63. """
  64. # About the this.form.* lines, see
  65. # http://www.sencha.com/forum/showthread.php?96001-solved-Ext.Direct-load-data-in-extended-Form-fails-%28scope-issue%29
  66. class Provider( object ):
  67. """ Provider for Ext.Direct. This class handles building API information and
  68. routing requests to the appropriate functions, and serializing their
  69. response and exceptions - if any.
  70. Instantiation:
  71. >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )
  72. If autoadd is True, the api.js will include a line like such::
  73. Ext.Direct.addProvider( Ext.app.REMOTING_API );
  74. After instantiating the Provider, register functions to it like so:
  75. >>> @EXT_JS_PROVIDER.register_method("myclass")
  76. ... def myview( request, possibly, some, other, arguments ):
  77. ... " does something with all those args and returns something "
  78. ... return 13.37
  79. Note that those views **MUST NOT** return an HttpResponse but simply
  80. the plain result, as the Provider will build a response from whatever
  81. your view returns!
  82. To be able to access the Provider, include its URLs in an arbitrary
  83. URL pattern, like so:
  84. >>> from views import EXT_JS_PROVIDER # import our provider instance
  85. >>> urlpatterns = patterns(
  86. ... # other patterns go here
  87. ... ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
  88. ... )
  89. This way, the Provider will define the URLs "api/api.js" and "api/router".
  90. If you then access the "api/api.js" URL, you will get a response such as::
  91. Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
  92. "url": "/mumble/api/router",
  93. "type": "remoting",
  94. "actions": {"myclass": [{"name": "myview", "len": 4}]}
  95. }
  96. You can then use this code in ExtJS to define the Provider there.
  97. """
  98. def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
  99. self.name = name
  100. self.autoadd = autoadd
  101. self.classes = {}
  102. self.forms = {}
  103. def register_method( self, cls_or_name, flags={} ):
  104. """ Return a function that takes a method as an argument and adds that
  105. to cls_or_name.
  106. The flags parameter is for additional information, e.g. formHandler=True.
  107. Note: This decorator does not replace the method by a new function,
  108. it returns the original function as-is.
  109. """
  110. return functools.partial( self._register_method, cls_or_name, flags=flags )
  111. def _register_method( self, cls_or_name, method, flags={} ):
  112. """ Actually registers the given function as a method of cls_or_name. """
  113. clsname = getname(cls_or_name)
  114. if clsname not in self.classes:
  115. self.classes[clsname] = {}
  116. self.classes[ clsname ][ method.__name__ ] = method
  117. method.EXT_argnames = inspect.getargspec( method ).args[1:]
  118. method.EXT_len = len( method.EXT_argnames )
  119. method.EXT_flags = flags
  120. return method
  121. def register_form( self, formclass ):
  122. """ Register a Django Form class.
  123. After registration, you will be able to retrieve an ExtJS form class
  124. definition for this form under the URL "<formname>.js". Include this
  125. script via a <script> tag just like the "api.js" for Ext.Direct.
  126. The form class will then be created as Ext.ux.<FormName> and will
  127. have a registered xtype of "formname".
  128. When registering a form, the Provider will automatically generate and
  129. export objects and methods for data transfer, so the form will be
  130. ready to use.
  131. To ensure that validation error messages are displayed properly, be
  132. sure to call Ext.QuickTips.init() somewhere in your code.
  133. In order to do extra validation, the Provider checks if your form class
  134. has a method called EXT_validate, and if so, calls that method with the
  135. request as parameter before calling is_valid() or save(). If EXT_validate
  136. returns False, the form will not be saved and an error will be returned
  137. instead. EXT_validate should update form.errors before returning False.
  138. """
  139. if not issubclass( formclass, forms.ModelForm ):
  140. raise TypeError( "Ext.Direct provider can only handle ModelForms, '%s' is something else." % formclass.__name__ )
  141. formname = formclass.__name__.lower()
  142. self.forms[formname] = formclass
  143. getfunc = functools.partial( self.get_form_data, formname )
  144. getfunc.EXT_len = 1
  145. getfunc.EXT_argnames = ["pk"]
  146. getfunc.EXT_flags = {}
  147. updatefunc = functools.partial( self.update_form_data, formname )
  148. updatefunc.EXT_len = 1
  149. updatefunc.EXT_argnames = ["pk"]
  150. updatefunc.EXT_flags = { 'formHandler': True }
  151. self.classes["XD_%s"%formclass.__name__] = {
  152. "get": getfunc,
  153. "update": updatefunc,
  154. }
  155. return formclass
  156. @csrf_exempt
  157. def get_api( self, request ):
  158. """ Introspect the methods and get a JSON description of this API. """
  159. actdict = {}
  160. for clsname in self.classes:
  161. actdict[clsname] = []
  162. for methodname in self.classes[clsname]:
  163. methinfo = {
  164. "name": methodname,
  165. "len": self.classes[clsname][methodname].EXT_len
  166. }
  167. methinfo.update( self.classes[clsname][methodname].EXT_flags )
  168. actdict[clsname].append( methinfo )
  169. lines = ["%s = %s;" % ( self.name, simplejson.dumps({
  170. "url": reverse( self.request ),
  171. "type": "remoting",
  172. "actions": actdict
  173. }))]
  174. if self.autoadd:
  175. lines.append( "Ext.Direct.addProvider( %s );" % self.name )
  176. return HttpResponse( "\n".join( lines ), mimetype="text/javascript" )
  177. @csrf_exempt
  178. def request( self, request ):
  179. """ Implements the Router part of the Ext.Direct specification.
  180. It handles decoding requests, calling the appropriate function (if
  181. found) and encoding the response / exceptions.
  182. """
  183. try:
  184. rawjson = simplejson.loads( request.raw_post_data )
  185. except simplejson.JSONDecodeError:
  186. # possibly a form submit / upload
  187. try:
  188. jsoninfo = {
  189. 'action': request.POST['extAction'],
  190. 'method': request.POST['extMethod'],
  191. 'type': request.POST['extType'],
  192. 'upload': request.POST['extUpload'],
  193. 'tid': request.POST['extTID'],
  194. }
  195. except (MultiValueDictKeyError, KeyError):
  196. # malformed request
  197. return HttpResponse( simplejson.dumps({
  198. 'type': 'exception',
  199. 'message': 'malformed request',
  200. 'where': 'router',
  201. "tid": tid,
  202. }), mimetype="text/javascript" )
  203. else:
  204. return self.process_form_request( request, jsoninfo )
  205. if not isinstance( rawjson, list ):
  206. rawjson = [rawjson]
  207. responses = []
  208. for reqinfo in rawjson:
  209. cls, methname, data, rtype, tid = (reqinfo['action'],
  210. reqinfo['method'],
  211. reqinfo['data'],
  212. reqinfo['type'],
  213. reqinfo['tid'])
  214. if cls not in self.classes:
  215. responses.append({
  216. 'type': 'exception',
  217. 'message': 'no such action',
  218. 'where': cls,
  219. "tid": tid,
  220. })
  221. continue
  222. if methname not in self.classes[cls]:
  223. responses.append({
  224. 'type': 'exception',
  225. 'message': 'no such method',
  226. 'where': methname,
  227. "tid": tid,
  228. })
  229. continue
  230. func = self.classes[cls][methname]
  231. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  232. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  233. args = []
  234. for argname in func.EXT_argnames:
  235. if argname in data[0]:
  236. args.append( data[0][argname] )
  237. else:
  238. args = None
  239. break
  240. if args:
  241. data = args
  242. try:
  243. if data:
  244. result = func( request, *data )
  245. else:
  246. result = func( request )
  247. except Exception, err:
  248. errinfo = {
  249. 'type': 'exception',
  250. "tid": tid,
  251. }
  252. if settings.DEBUG:
  253. traceback.print_exc( file=stderr )
  254. errinfo['message'] = unicode(err)
  255. errinfo['where'] = traceback.format_exc()
  256. else:
  257. errinfo['message'] = 'The socket packet pocket has an error to report.'
  258. errinfo['where'] = ''
  259. responses.append(errinfo)
  260. else:
  261. responses.append({
  262. "type": rtype,
  263. "tid": tid,
  264. "action": cls,
  265. "method": methname,
  266. "result": result
  267. })
  268. if len(responses) == 1:
  269. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  270. else:
  271. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  272. def process_form_request( self, request, reqinfo ):
  273. """ Router for POST requests that submit form data and/or file uploads. """
  274. cls, methname, rtype, tid = (reqinfo['action'],
  275. reqinfo['method'],
  276. reqinfo['type'],
  277. reqinfo['tid'])
  278. if cls not in self.classes:
  279. response = {
  280. 'type': 'exception',
  281. 'message': 'no such action',
  282. 'where': cls,
  283. "tid": tid,
  284. }
  285. elif methname not in self.classes[cls]:
  286. response = {
  287. 'type': 'exception',
  288. 'message': 'no such method',
  289. 'where': methname,
  290. "tid": tid,
  291. }
  292. else:
  293. func = self.classes[cls][methname]
  294. try:
  295. result = func( request )
  296. except Exception, err:
  297. errinfo = {
  298. 'type': 'exception',
  299. "tid": tid,
  300. }
  301. if settings.DEBUG:
  302. traceback.print_exc( file=stderr )
  303. errinfo['message'] = unicode(err)
  304. errinfo['where'] = traceback.format_exc()
  305. else:
  306. errinfo['message'] = 'The socket packet pocket has an error to report.'
  307. errinfo['where'] = ''
  308. response = errinfo
  309. else:
  310. response = {
  311. "type": rtype,
  312. "tid": tid,
  313. "action": cls,
  314. "method": methname,
  315. "result": result
  316. }
  317. if reqinfo['upload'] == "true":
  318. return HttpResponse(
  319. "<html><body><textarea>%s</textarea></body></html>" % simplejson.dumps(response),
  320. mimetype="text/javascript"
  321. )
  322. else:
  323. return HttpResponse( simplejson.dumps( response ), mimetype="text/javascript" )
  324. def get_form( self, request, formname ):
  325. """ Convert the form given in "formname" to an ExtJS FormPanel. """
  326. if formname not in self.forms:
  327. raise Http404(formname)
  328. items = []
  329. clsname = self.forms[formname].__name__
  330. hasfiles = False
  331. for fldname in self.forms[formname].base_fields:
  332. field = self.forms[formname].base_fields[fldname]
  333. extfld = {
  334. "fieldLabel": field.label is not None and unicode(field.label) or fldname,
  335. "name": fldname,
  336. "xtype": "textfield",
  337. #"allowEmpty": field.required,
  338. }
  339. if hasattr( field, "choices" ) and field.choices:
  340. extfld.update({
  341. "name": fldname,
  342. "hiddenName": fldname,
  343. "xtype": "combo",
  344. "store": field.choices,
  345. "typeAhead": True,
  346. "emptyText": 'Select...',
  347. "triggerAction": 'all',
  348. "selectOnFocus": True,
  349. })
  350. elif isinstance( field, forms.BooleanField ):
  351. extfld.update({
  352. "xtype": "checkbox"
  353. })
  354. elif isinstance( field, forms.IntegerField ):
  355. extfld.update({
  356. "xtype": "numberfield",
  357. })
  358. elif isinstance( field, forms.FileField ) or isinstance( field, forms.ImageField ):
  359. hasfiles = True
  360. extfld.update({
  361. "xtype": "textfield",
  362. "inputType": "file"
  363. })
  364. elif isinstance( field.widget, forms.Textarea ):
  365. extfld.update({
  366. "xtype": "textarea",
  367. })
  368. elif isinstance( field.widget, forms.PasswordInput ):
  369. extfld.update({
  370. "xtype": "textfield",
  371. "inputType": "password"
  372. })
  373. items.append( extfld )
  374. if field.help_text:
  375. items.append({
  376. "xtype": "label",
  377. "text": unicode(field.help_text),
  378. "cls": "form_hint_label",
  379. })
  380. clscode = EXT_CLASS_TEMPLATE % {
  381. 'clsname': clsname,
  382. 'clslowername': formname,
  383. 'defaultconf': '{'
  384. 'items:' + simplejson.dumps(items, indent=4) + ','
  385. 'fileUpload: ' + simplejson.dumps(hasfiles) + ','
  386. 'defaults: { "anchor": "-20px" },'
  387. 'paramsAsHash: true,'
  388. """buttons: [{
  389. text: "Submit",
  390. handler: this.submit,
  391. scope: this
  392. }]"""
  393. '}',
  394. 'apiconf': ('{'
  395. 'load: ' + ("XD_%s.get" % clsname) + ","
  396. 'submit:' + ("XD_%s.update" % clsname) + ","
  397. "}"),
  398. }
  399. return HttpResponse( mark_safe( clscode ), mimetype="text/javascript" )
  400. def get_form_data( self, formname, request, pk ):
  401. formcls = self.forms[formname]
  402. instance = formcls.Meta.model.objects.get( pk=pk )
  403. forminst = formcls( instance=instance )
  404. data = {}
  405. for fld in forminst.fields:
  406. data[fld] = getattr( instance, fld )
  407. return { 'data': data, 'success': True }
  408. def update_form_data( self, formname, request ):
  409. pk = request.POST['pk']
  410. formcls = self.forms[formname]
  411. instance = formcls.Meta.model.objects.get( pk=pk )
  412. if request.POST['extUpload'] == "true":
  413. forminst = formcls( request.POST, request.FILES, instance=instance )
  414. else:
  415. forminst = formcls( request.POST, instance=instance )
  416. # save if either no usable validation method available or validation passes; and form.is_valid
  417. if ( not hasattr( forminst, "EXT_validate" ) or not callable( forminst.EXT_validate )
  418. or forminst.EXT_validate( request ) ) \
  419. and forminst.is_valid():
  420. forminst.save()
  421. return { 'success': True }
  422. else:
  423. errdict = {}
  424. for errfld in forminst.errors:
  425. errdict[errfld] = "\n".join( forminst.errors[errfld] )
  426. return { 'success': False, 'errors': errdict }
  427. @property
  428. def urls(self):
  429. """ Return the URL patterns. """
  430. pat = patterns('',
  431. (r'api.js$', self.get_api ),
  432. (r'router/?', self.request ),
  433. )
  434. if self.forms:
  435. pat.append( url( r'(?P<formname>\w+).js$', self.get_form ) )
  436. return pat