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.

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