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.

557 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. # First try to use request.POST, if that doesn't work check for req.raw_post_data.
  184. # The other way round this might make more sense because the case that uses
  185. # raw_post_data is way more common, but accessing request.POST after raw_post_data
  186. # causes issues with Django's test client while accessing raw_post_data after
  187. # request.POST does not.
  188. try:
  189. jsoninfo = {
  190. 'action': request.POST['extAction'],
  191. 'method': request.POST['extMethod'],
  192. 'type': request.POST['extType'],
  193. 'upload': request.POST['extUpload'],
  194. 'tid': request.POST['extTID'],
  195. }
  196. except (MultiValueDictKeyError, KeyError), err:
  197. try:
  198. rawjson = simplejson.loads( request.raw_post_data )
  199. except simplejson.JSONDecodeError:
  200. return HttpResponse( simplejson.dumps({
  201. 'type': 'exception',
  202. 'message': 'malformed request',
  203. 'where': unicode(err),
  204. "tid": None, # dunno
  205. }), mimetype="text/javascript" )
  206. else:
  207. return self.process_normal_request( request, rawjson )
  208. else:
  209. return self.process_form_request( request, jsoninfo )
  210. def process_normal_request( self, request, rawjson ):
  211. if not isinstance( rawjson, list ):
  212. rawjson = [rawjson]
  213. responses = []
  214. for reqinfo in rawjson:
  215. cls, methname, data, rtype, tid = (reqinfo['action'],
  216. reqinfo['method'],
  217. reqinfo['data'],
  218. reqinfo['type'],
  219. reqinfo['tid'])
  220. if cls not in self.classes:
  221. responses.append({
  222. 'type': 'exception',
  223. 'message': 'no such action',
  224. 'where': cls,
  225. "tid": tid,
  226. })
  227. continue
  228. if methname not in self.classes[cls]:
  229. responses.append({
  230. 'type': 'exception',
  231. 'message': 'no such method',
  232. 'where': methname,
  233. "tid": tid,
  234. })
  235. continue
  236. func = self.classes[cls][methname]
  237. if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
  238. # data[0] seems to contain a dict with params. check if it does, and if so, unpack
  239. args = []
  240. for argname in func.EXT_argnames:
  241. if argname in data[0]:
  242. args.append( data[0][argname] )
  243. else:
  244. args = None
  245. break
  246. if args:
  247. data = args
  248. if data is not None:
  249. datalen = len(data)
  250. else:
  251. datalen = 0
  252. if datalen != len(func.EXT_argnames):
  253. responses.append({
  254. 'type': 'exception',
  255. 'tid': tid,
  256. 'message': 'invalid arguments',
  257. 'where': 'Expected %d, got %d' % ( len(func.EXT_argnames), len(data) )
  258. })
  259. continue
  260. try:
  261. if data:
  262. result = func( request, *data )
  263. else:
  264. result = func( request )
  265. except Exception, err:
  266. errinfo = {
  267. 'type': 'exception',
  268. "tid": tid,
  269. }
  270. if settings.DEBUG:
  271. traceback.print_exc( file=stderr )
  272. errinfo['message'] = unicode(err)
  273. errinfo['where'] = traceback.format_exc()
  274. else:
  275. errinfo['message'] = 'The socket packet pocket has an error to report.'
  276. errinfo['where'] = ''
  277. responses.append(errinfo)
  278. else:
  279. responses.append({
  280. "type": rtype,
  281. "tid": tid,
  282. "action": cls,
  283. "method": methname,
  284. "result": result
  285. })
  286. if len(responses) == 1:
  287. return HttpResponse( simplejson.dumps( responses[0] ), mimetype="text/javascript" )
  288. else:
  289. return HttpResponse( simplejson.dumps( responses ), mimetype="text/javascript" )
  290. def process_form_request( self, request, reqinfo ):
  291. """ Router for POST requests that submit form data and/or file uploads. """
  292. cls, methname, rtype, tid = (reqinfo['action'],
  293. reqinfo['method'],
  294. reqinfo['type'],
  295. reqinfo['tid'])
  296. if cls not in self.classes:
  297. response = {
  298. 'type': 'exception',
  299. 'message': 'no such action',
  300. 'where': cls,
  301. "tid": tid,
  302. }
  303. elif methname not in self.classes[cls]:
  304. response = {
  305. 'type': 'exception',
  306. 'message': 'no such method',
  307. 'where': methname,
  308. "tid": tid,
  309. }
  310. else:
  311. func = self.classes[cls][methname]
  312. try:
  313. result = func( request )
  314. except Exception, err:
  315. errinfo = {
  316. 'type': 'exception',
  317. "tid": tid,
  318. }
  319. if settings.DEBUG:
  320. traceback.print_exc( file=stderr )
  321. errinfo['message'] = unicode(err)
  322. errinfo['where'] = traceback.format_exc()
  323. else:
  324. errinfo['message'] = 'The socket packet pocket has an error to report.'
  325. errinfo['where'] = ''
  326. response = errinfo
  327. else:
  328. response = {
  329. "type": rtype,
  330. "tid": tid,
  331. "action": cls,
  332. "method": methname,
  333. "result": result
  334. }
  335. if reqinfo['upload'] == "true":
  336. return HttpResponse(
  337. "<html><body><textarea>%s</textarea></body></html>" % simplejson.dumps(response),
  338. mimetype="text/javascript"
  339. )
  340. else:
  341. return HttpResponse( simplejson.dumps( response ), mimetype="text/javascript" )
  342. def get_form( self, request, formname ):
  343. """ Convert the form given in "formname" to an ExtJS FormPanel. """
  344. if formname not in self.forms:
  345. raise Http404(formname)
  346. items = []
  347. clsname = self.forms[formname].__name__
  348. hasfiles = False
  349. for fldname in self.forms[formname].base_fields:
  350. field = self.forms[formname].base_fields[fldname]
  351. extfld = {
  352. "fieldLabel": field.label is not None and unicode(field.label) or fldname,
  353. "name": fldname,
  354. "xtype": "textfield",
  355. #"allowEmpty": field.required,
  356. }
  357. if hasattr( field, "choices" ) and field.choices:
  358. extfld.update({
  359. "name": fldname,
  360. "hiddenName": fldname,
  361. "xtype": "combo",
  362. "store": field.choices,
  363. "typeAhead": True,
  364. "emptyText": 'Select...',
  365. "triggerAction": 'all',
  366. "selectOnFocus": True,
  367. })
  368. elif isinstance( field, forms.BooleanField ):
  369. extfld.update({
  370. "xtype": "checkbox"
  371. })
  372. elif isinstance( field, forms.IntegerField ):
  373. extfld.update({
  374. "xtype": "numberfield",
  375. })
  376. elif isinstance( field, forms.FileField ) or isinstance( field, forms.ImageField ):
  377. hasfiles = True
  378. extfld.update({
  379. "xtype": "textfield",
  380. "inputType": "file"
  381. })
  382. elif isinstance( field.widget, forms.Textarea ):
  383. extfld.update({
  384. "xtype": "textarea",
  385. })
  386. elif isinstance( field.widget, forms.PasswordInput ):
  387. extfld.update({
  388. "xtype": "textfield",
  389. "inputType": "password"
  390. })
  391. items.append( extfld )
  392. if field.help_text:
  393. items.append({
  394. "xtype": "label",
  395. "text": unicode(field.help_text),
  396. "cls": "form_hint_label",
  397. })
  398. clscode = EXT_CLASS_TEMPLATE % {
  399. 'clsname': clsname,
  400. 'clslowername': formname,
  401. 'defaultconf': '{'
  402. 'items:' + simplejson.dumps(items, indent=4) + ','
  403. 'fileUpload: ' + simplejson.dumps(hasfiles) + ','
  404. 'defaults: { "anchor": "-20px" },'
  405. 'paramsAsHash: true,'
  406. 'autoScroll: true,'
  407. """buttons: [{
  408. text: "Submit",
  409. handler: this.submit,
  410. scope: this
  411. }]"""
  412. '}',
  413. 'apiconf': ('{'
  414. 'load: ' + ("XD_%s.get" % clsname) + ","
  415. 'submit:' + ("XD_%s.update" % clsname) + ","
  416. "}"),
  417. }
  418. return HttpResponse( mark_safe( clscode ), mimetype="text/javascript" )
  419. def get_form_data( self, formname, request, pk ):
  420. formcls = self.forms[formname]
  421. if pk != -1:
  422. instance = formcls.Meta.model.objects.get( pk=pk )
  423. else:
  424. instance = None
  425. forminst = formcls( instance=instance )
  426. if hasattr( forminst, "EXT_authorize" ) and \
  427. forminst.EXT_authorize( request, "get" ) is False:
  428. return { 'success': False, 'errors': {'': 'access denied'} }
  429. data = {}
  430. for fld in forminst.fields:
  431. data[fld] = getattr( instance, fld )
  432. return { 'data': data, 'success': True }
  433. def update_form_data( self, formname, request ):
  434. pk = request.POST['pk']
  435. formcls = self.forms[formname]
  436. if pk != -1:
  437. instance = formcls.Meta.model.objects.get( pk=pk )
  438. else:
  439. instance = None
  440. if request.POST['extUpload'] == "true":
  441. forminst = formcls( request.POST, request.FILES, instance=instance )
  442. else:
  443. forminst = formcls( request.POST, instance=instance )
  444. if hasattr( forminst, "EXT_authorize" ) and \
  445. forminst.EXT_authorize( request, "update" ) is False:
  446. return { 'success': False, 'errors': {'': 'access denied'} }
  447. # save if either no usable validation method available or validation passes; and form.is_valid
  448. if ( hasattr( forminst, "EXT_validate" ) and callable( forminst.EXT_validate )
  449. and not forminst.EXT_validate( request ) ):
  450. return { 'success': False, 'errors': {'': 'pre-validation failed'} }
  451. if forminst.is_valid():
  452. forminst.save()
  453. return { 'success': True }
  454. else:
  455. errdict = {}
  456. for errfld in forminst.errors:
  457. errdict[errfld] = "\n".join( forminst.errors[errfld] )
  458. return { 'success': False, 'errors': errdict }
  459. @property
  460. def urls(self):
  461. """ Return the URL patterns. """
  462. pat = patterns('',
  463. (r'api.js$', self.get_api ),
  464. (r'router/?', self.request ),
  465. )
  466. if self.forms:
  467. pat.append( url( r'(?P<formname>\w+).js$', self.get_form ) )
  468. return pat