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.

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