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.

543 lines
20 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. if data is not None:
  243. datalen = len(data)
  244. else:
  245. datalen = 0
  246. if datalen != len(func.EXT_argnames):
  247. responses.append({
  248. 'type': 'exception',
  249. 'tid': tid,
  250. 'message': 'invalid arguments',
  251. 'where': 'Expected %d, got %d' % ( len(func.EXT_argnames), len(data) )
  252. })
  253. continue
  254. try:
  255. if data:
  256. result = func( request, *data )
  257. else:
  258. result = func( request )
  259. except Exception, err:
  260. errinfo = {
  261. 'type': 'exception',
  262. "tid": tid,
  263. }
  264. if settings.DEBUG:
  265. traceback.print_exc( file=stderr )
  266. errinfo['message'] = unicode(err)
  267. errinfo['where'] = traceback.format_exc()
  268. else:
  269. errinfo['message'] = 'The socket packet pocket has an error to report.'
  270. errinfo['where'] = ''
  271. responses.append(errinfo)
  272. else:
  273. responses.append({
  274. "type": rtype,
  275. "tid": tid,
  276. "action": cls,
  277. "method": methname,
  278. "result": result
  279. })
  280. if len(responses) == 1:
  281. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  282. else:
  283. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  284. def process_form_request( self, request, reqinfo ):
  285. """ Router for POST requests that submit form data and/or file uploads. """
  286. cls, methname, rtype, tid = (reqinfo['action'],
  287. reqinfo['method'],
  288. reqinfo['type'],
  289. reqinfo['tid'])
  290. if cls not in self.classes:
  291. response = {
  292. 'type': 'exception',
  293. 'message': 'no such action',
  294. 'where': cls,
  295. "tid": tid,
  296. }
  297. elif methname not in self.classes[cls]:
  298. response = {
  299. 'type': 'exception',
  300. 'message': 'no such method',
  301. 'where': methname,
  302. "tid": tid,
  303. }
  304. else:
  305. func = self.classes[cls][methname]
  306. try:
  307. result = func( request )
  308. except Exception, err:
  309. errinfo = {
  310. 'type': 'exception',
  311. "tid": tid,
  312. }
  313. if settings.DEBUG:
  314. traceback.print_exc( file=stderr )
  315. errinfo['message'] = unicode(err)
  316. errinfo['where'] = traceback.format_exc()
  317. else:
  318. errinfo['message'] = 'The socket packet pocket has an error to report.'
  319. errinfo['where'] = ''
  320. response = errinfo
  321. else:
  322. response = {
  323. "type": rtype,
  324. "tid": tid,
  325. "action": cls,
  326. "method": methname,
  327. "result": result
  328. }
  329. if reqinfo['upload'] == "true":
  330. return HttpResponse(
  331. "<html><body><textarea>%s</textarea></body></html>" % simplejson.dumps(response),
  332. mimetype="text/javascript"
  333. )
  334. else:
  335. return HttpResponse( simplejson.dumps( response ), mimetype="text/javascript" )
  336. def get_form( self, request, formname ):
  337. """ Convert the form given in "formname" to an ExtJS FormPanel. """
  338. if formname not in self.forms:
  339. raise Http404(formname)
  340. items = []
  341. clsname = self.forms[formname].__name__
  342. hasfiles = False
  343. for fldname in self.forms[formname].base_fields:
  344. field = self.forms[formname].base_fields[fldname]
  345. extfld = {
  346. "fieldLabel": field.label is not None and unicode(field.label) or fldname,
  347. "name": fldname,
  348. "xtype": "textfield",
  349. #"allowEmpty": field.required,
  350. }
  351. if hasattr( field, "choices" ) and field.choices:
  352. extfld.update({
  353. "name": fldname,
  354. "hiddenName": fldname,
  355. "xtype": "combo",
  356. "store": field.choices,
  357. "typeAhead": True,
  358. "emptyText": 'Select...',
  359. "triggerAction": 'all',
  360. "selectOnFocus": True,
  361. })
  362. elif isinstance( field, forms.BooleanField ):
  363. extfld.update({
  364. "xtype": "checkbox"
  365. })
  366. elif isinstance( field, forms.IntegerField ):
  367. extfld.update({
  368. "xtype": "numberfield",
  369. })
  370. elif isinstance( field, forms.FileField ) or isinstance( field, forms.ImageField ):
  371. hasfiles = True
  372. extfld.update({
  373. "xtype": "textfield",
  374. "inputType": "file"
  375. })
  376. elif isinstance( field.widget, forms.Textarea ):
  377. extfld.update({
  378. "xtype": "textarea",
  379. })
  380. elif isinstance( field.widget, forms.PasswordInput ):
  381. extfld.update({
  382. "xtype": "textfield",
  383. "inputType": "password"
  384. })
  385. items.append( extfld )
  386. if field.help_text:
  387. items.append({
  388. "xtype": "label",
  389. "text": unicode(field.help_text),
  390. "cls": "form_hint_label",
  391. })
  392. clscode = EXT_CLASS_TEMPLATE % {
  393. 'clsname': clsname,
  394. 'clslowername': formname,
  395. 'defaultconf': '{'
  396. 'items:' + simplejson.dumps(items, indent=4) + ','
  397. 'fileUpload: ' + simplejson.dumps(hasfiles) + ','
  398. 'defaults: { "anchor": "-20px" },'
  399. 'paramsAsHash: true,'
  400. """buttons: [{
  401. text: "Submit",
  402. handler: this.submit,
  403. scope: this
  404. }]"""
  405. '}',
  406. 'apiconf': ('{'
  407. 'load: ' + ("XD_%s.get" % clsname) + ","
  408. 'submit:' + ("XD_%s.update" % clsname) + ","
  409. "}"),
  410. }
  411. return HttpResponse( mark_safe( clscode ), mimetype="text/javascript" )
  412. def get_form_data( self, formname, request, pk ):
  413. formcls = self.forms[formname]
  414. instance = formcls.Meta.model.objects.get( pk=pk )
  415. forminst = formcls( instance=instance )
  416. if hasattr( forminst, "EXT_authorize" ) and \
  417. forminst.EXT_authorize( request, "get" ) is False:
  418. return { 'success': False, 'errors': {'': 'access denied'} }
  419. data = {}
  420. for fld in forminst.fields:
  421. data[fld] = getattr( instance, fld )
  422. return { 'data': data, 'success': True }
  423. def update_form_data( self, formname, request ):
  424. pk = request.POST['pk']
  425. formcls = self.forms[formname]
  426. instance = formcls.Meta.model.objects.get( pk=pk )
  427. if request.POST['extUpload'] == "true":
  428. forminst = formcls( request.POST, request.FILES, instance=instance )
  429. else:
  430. forminst = formcls( request.POST, instance=instance )
  431. if hasattr( forminst, "EXT_authorize" ) and \
  432. forminst.EXT_authorize( request, "update" ) is False:
  433. return { 'success': False, 'errors': {'': 'access denied'} }
  434. # save if either no usable validation method available or validation passes; and form.is_valid
  435. if ( not hasattr( forminst, "EXT_validate" ) or not callable( forminst.EXT_validate )
  436. or forminst.EXT_validate( request ) ) \
  437. and forminst.is_valid():
  438. forminst.save()
  439. return { 'success': True }
  440. else:
  441. errdict = {}
  442. for errfld in forminst.errors:
  443. errdict[errfld] = "\n".join( forminst.errors[errfld] )
  444. return { 'success': False, 'errors': errdict }
  445. @property
  446. def urls(self):
  447. """ Return the URL patterns. """
  448. pat = patterns('',
  449. (r'api.js$', self.get_api ),
  450. (r'router/?', self.request ),
  451. )
  452. if self.forms:
  453. pat.append( url( r'(?P<formname>\w+).js$', self.get_form ) )
  454. return pat