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.

442 lines
18 KiB

12 years ago
  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright © 2009-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 socket
  17. import re
  18. from django import forms
  19. from django.conf import settings
  20. from django.forms import Form, ModelForm
  21. from django.forms.models import ModelFormMetaclass
  22. from django.utils.translation import ugettext_lazy as _, ugettext
  23. from mumble.models import MumbleServer, Mumble, MumbleUser
  24. from djextdirect.formprovider import FormProvider
  25. EXT_FORMS_PROVIDER = FormProvider(name="Ext.app.MUMBLE_FORMS_API")
  26. class PropertyModelFormMeta( ModelFormMetaclass ):
  27. """ Metaclass that updates the property generated fields with the
  28. docstrings from their model counterparts.
  29. """
  30. def __init__( cls, name, bases, attrs ):
  31. ModelFormMetaclass.__init__( cls, name, bases, attrs )
  32. if cls._meta.model:
  33. model = cls._meta.model
  34. elif hasattr( bases[0], '_meta' ) and bases[0]._meta.model:
  35. # apparently, _meta has not been created yet if inherited, so use parent's (if any)
  36. model = bases[0]._meta.model
  37. else:
  38. model = None
  39. if model:
  40. mdlfields = model._meta.get_all_field_names()
  41. for fldname in cls.base_fields:
  42. if fldname in mdlfields:
  43. continue
  44. prop = getattr( model, fldname )
  45. if prop.__doc__:
  46. cls.base_fields[fldname].label = _(prop.__doc__)
  47. class PropertyModelForm( ModelForm ):
  48. """ ModelForm that gets/sets fields that are not within the model's
  49. fields as model attributes. Necessary to get forms that manipulate
  50. properties.
  51. """
  52. __metaclass__ = PropertyModelFormMeta
  53. def __init__( self, *args, **kwargs ):
  54. ModelForm.__init__( self, *args, **kwargs )
  55. if self.instance:
  56. instfields = self.instance._meta.get_all_field_names()
  57. for fldname in self.fields:
  58. if fldname in instfields:
  59. continue
  60. self.fields[fldname].initial = getattr( self.instance, fldname )
  61. def save( self, commit=True ):
  62. inst = ModelForm.save( self, commit=commit )
  63. if commit:
  64. self.save_to_model( inst )
  65. else:
  66. # Update when the model has been saved.
  67. from django.db.models import signals
  68. self._update_inst = inst
  69. signals.post_save.connect( self.save_listener, sender=inst.__class__ )
  70. return inst
  71. def save_listener( self, **kwargs ):
  72. if kwargs['instance'] is self._update_inst:
  73. self.save_to_model( self._update_inst )
  74. def save_to_model( self, inst ):
  75. instfields = inst._meta.get_all_field_names()
  76. for fldname in self.fields:
  77. if fldname not in instfields:
  78. setattr( inst, fldname, self.cleaned_data[fldname] )
  79. class MumbleForm( PropertyModelForm ):
  80. """ The Mumble Server admin form that allows to configure settings which do
  81. not necessarily have to be reserved to the server hoster.
  82. Server hosters are expected to use the Django admin application instead,
  83. where everything can be configured freely.
  84. """
  85. url = forms.CharField( required=False, help_text=_(
  86. "Website URL. Required for the server to be listed in the server list."))
  87. motd = forms.CharField( required=False, widget=forms.Textarea )
  88. passwd = forms.CharField( required=False, help_text=_(
  89. "Password required to join. Leave empty for public servers. Private servers cannot be listed in the server list.") )
  90. supw = forms.CharField( required=False, widget=forms.PasswordInput )
  91. player = forms.CharField( required=False )
  92. channel = forms.CharField( required=False )
  93. defchan = forms.TypedChoiceField( choices=(), coerce=int, required=False )
  94. timeout = forms.IntegerField( required=False )
  95. certrequired = forms.BooleanField( required=False )
  96. textmessagelength = forms.IntegerField( required=False )
  97. imagemessagelength = forms.IntegerField( required=False, help_text=_(
  98. "In case of messages containing Base64 encoded images this overrides textmessagelength.") )
  99. allowhtml = forms.BooleanField( required=False )
  100. rememberchannel = forms.BooleanField( required=False, help_text=_(
  101. "Remember the channel users were in when they quit, and automatically move them to "
  102. "that channel when they join.") )
  103. suggestversion = forms.CharField( required=False )
  104. suggestpositional = forms.ChoiceField( required=False, choices=( ('', ugettext('No suggestion')), ('true', ugettext('Suggest on')), ('false', ugettext('Suggest off')) ) )
  105. suggestpushtotalk = forms.ChoiceField( required=False, choices=( ('', ugettext('No suggestion')), ('true', ugettext('Suggest on')), ('false', ugettext('Suggest off')) ) )
  106. opusthreshold = forms.IntegerField( required=False, initial=100, help_text=_(
  107. "Force Opus-Codec if this percentage of clients support it. Enter without % character.") )
  108. registerlocation = forms.CharField( required=False, help_text=_(
  109. "Location of the server as ISO_3166-1 country code. In order for this to work, you must have "
  110. "a strong server certificate that carries the same country code. Alternatively, the TLD "
  111. "specified in the Display Address field must contain the same location code.") )
  112. registerpassword = forms.CharField( required=False, help_text=_(
  113. "Password used for the server list registration. Required for the server to be listed in the server list. "
  114. "Note that you will never need to enter this password anywhere. It is solely used by Murmur to update the registration.") )
  115. allowping = forms.BooleanField( required=False, initial=True, help_text=_(
  116. "Allow ping packets from the server (to show usercount and slots in the server browser). "
  117. "Required for the server to be listed in the server list.") )
  118. sendversion = forms.BooleanField( required=False, initial=True, help_text=_(
  119. "Allow server to send system version to the client.") )
  120. def __init__( self, *args, **kwargs ):
  121. PropertyModelForm.__init__( self, *args, **kwargs )
  122. # Populate the `default channel' field's choices
  123. choices = [ ('', '----------') ]
  124. if self.instance and self.instance.srvid is not None:
  125. if self.instance.booted:
  126. def add_item( item, level ):
  127. if item.is_server or item.is_channel:
  128. choices.append( ( item.chanid, ( "-"*level + " " + item.name ) ) )
  129. self.instance.rootchan.visit(add_item)
  130. else:
  131. current = self.instance.defchan
  132. if current is not None:
  133. choices.append( ( current, "Current value: %d" % current ) )
  134. self.fields['defchan'].choices = choices
  135. class Meta:
  136. model = Mumble
  137. fields = ['name', 'display']
  138. def EXT_authorize( self, request, action ):
  139. return self.instance.isUserAdmin( request.user )
  140. EXT_FORMS_PROVIDER.register_form( MumbleForm )
  141. class MumbleAdminForm( MumbleForm ):
  142. """ A Mumble Server admin form intended to be used by the server hoster. """
  143. users = forms.IntegerField( required=False )
  144. usersperchannel = forms.IntegerField( required=False )
  145. channelnestinglimit = forms.IntegerField( required=False, help_text=_("Limit channel nesting to this level.") )
  146. bwidth = forms.IntegerField( required=False )
  147. sslca = forms.CharField( required=False, widget=forms.Textarea, help_text=_("Can be a path or the file content in PEM format.") )
  148. sslcrt = forms.CharField( required=False, widget=forms.Textarea )
  149. sslkey = forms.CharField( required=False, widget=forms.Textarea )
  150. sslpassphrase = forms.CharField( required=False, help_text=_("Passphrase of the SSL Key file, if any.") )
  151. booted = forms.BooleanField( required=False, initial=True )
  152. autoboot = forms.BooleanField( required=False, initial=True )
  153. bonjour = forms.BooleanField( required=False )
  154. class Meta:
  155. fields = "__all__"
  156. def clean_port( self ):
  157. """ Check if the port number is valid. """
  158. port = self.cleaned_data['port']
  159. if port is not None and port != '':
  160. if port < 1 or port >= 2**16:
  161. raise forms.ValidationError(
  162. _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  163. 'portno': port,
  164. 'minrange': 1,
  165. 'maxrange': 2**16,
  166. })
  167. return port
  168. return None
  169. class MumbleServerForm( ModelForm ):
  170. defaultconf = forms.CharField( label=_("Default config"), required=False, widget=forms.Textarea )
  171. def __init__( self, *args, **kwargs ):
  172. ModelForm.__init__( self, *args, **kwargs )
  173. # self.instance = instance of MumbleServer, NOT a server instance
  174. if self.instance and self.instance.id:
  175. if self.instance.online:
  176. confstr = ""
  177. conf = self.instance.defaultconf
  178. for field in conf:
  179. confstr += "%s: %s\n" % ( field, conf[field] )
  180. self.fields["defaultconf"].initial = confstr
  181. else:
  182. self.fields["defaultconf"].initial = _("This server is currently offline.")
  183. class Meta:
  184. fields = "__all__"
  185. model = MumbleServer
  186. class MumbleUserForm( ModelForm ):
  187. """ The user registration form used to register an account. """
  188. password = forms.CharField( label=_("Password"), widget=forms.PasswordInput, required=False )
  189. def __init__( self, *args, **kwargs ):
  190. ModelForm.__init__( self, *args, **kwargs )
  191. self.server = None
  192. def EXT_authorize( self, request, action ):
  193. if not request.user.is_authenticated():
  194. return False
  195. if action == "update" and settings.PROTECTED_MODE and self.instance.id is None:
  196. # creating new user in protected mode -> need UserPasswordForm
  197. return False
  198. if self.instance.id is not None and request.user != self.instance.owner:
  199. # editing another account
  200. return False
  201. return True
  202. def EXT_validate( self, request ):
  203. self.instance.owner = request.user
  204. if "serverid" in request.POST:
  205. try:
  206. self.server = Mumble.objects.get( id=int(request.POST['serverid']) )
  207. except Mumble.DoesNotExist:
  208. return False
  209. else:
  210. return True
  211. return False
  212. def clean_name( self ):
  213. """ Check if the desired name is forbidden or taken. """
  214. name = self.cleaned_data['name']
  215. if self.server is None:
  216. raise AttributeError( "You need to set the form's server attribute to the server instance "
  217. "for validation to work." )
  218. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  219. raise forms.ValidationError( _( "That name is forbidden by the server." ) )
  220. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  221. raise forms.ValidationError( _( "Another player already registered that name." ) )
  222. return name
  223. def clean_password( self ):
  224. """ Verify a password has been given. """
  225. passwd = self.cleaned_data['password']
  226. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  227. raise forms.ValidationError( _( "Cannot register player without a password!" ) )
  228. return passwd
  229. def save(self):
  230. self.instance.server = self.server
  231. ModelForm.save(self)
  232. class Meta:
  233. model = MumbleUser
  234. fields = ( 'name', 'password' )
  235. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  236. class MumbleUserPasswordForm( MumbleUserForm ):
  237. """ The user registration form used to register an account on a private server in protected mode. """
  238. serverpw = forms.CharField(
  239. label=_('Server Password'),
  240. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  241. widget=forms.PasswordInput(render_value=False)
  242. )
  243. def EXT_authorize( self, request, action ):
  244. if not request.user.is_authenticated():
  245. return False
  246. if self.instance.id is not None and request.user != self.instance.owner:
  247. # editing another account
  248. return False
  249. return True
  250. def clean_serverpw( self ):
  251. """ Validate the password """
  252. serverpw = self.cleaned_data['serverpw']
  253. if self.server.passwd != serverpw:
  254. raise forms.ValidationError( _( "The password you entered is incorrect." ) )
  255. return serverpw
  256. def clean( self ):
  257. """ prevent save() from trying to store the password in the Model instance. """
  258. # clean() will be called after clean_serverpw(), so it has already been validated here.
  259. if 'serverpw' in self.cleaned_data:
  260. del( self.cleaned_data['serverpw'] )
  261. return self.cleaned_data
  262. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  263. class MumbleUserLinkForm( MumbleUserForm ):
  264. """ Special registration form to either register or link an account. """
  265. linkacc = forms.BooleanField(
  266. label=_('Link account'),
  267. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  268. required=False,
  269. )
  270. def __init__( self, *args, **kwargs ):
  271. MumbleUserForm.__init__( self, *args, **kwargs )
  272. self.mumbleid = None
  273. def EXT_authorize( self, request, action ):
  274. if not request.user.is_authenticated() or action == "get":
  275. return False
  276. if self.instance.id is not None and request.user != self.instance.owner:
  277. # editing another account
  278. return False
  279. return settings.ALLOW_ACCOUNT_LINKING
  280. def clean_name( self ):
  281. """ Check if the target account exists in Murmur. """
  282. if 'linkacc' not in self.data:
  283. return MumbleUserForm.clean_name( self )
  284. # Check if user exists
  285. name = self.cleaned_data['name']
  286. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  287. raise forms.ValidationError( _( "No such user found." ) )
  288. return name
  289. def clean_password( self ):
  290. """ Verify that the password is correct. """
  291. if 'linkacc' not in self.data:
  292. return MumbleUserForm.clean_password( self )
  293. if 'name' not in self.cleaned_data:
  294. # keep clean() from trying to find a user that CAN'T exist
  295. self.mumbleid = -10
  296. return ''
  297. # Validate password with Murmur
  298. passwd = self.cleaned_data['password']
  299. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  300. if self.mumbleid <= 0:
  301. raise forms.ValidationError( _( "The password you entered is incorrect." ) )
  302. return passwd
  303. def clean( self ):
  304. """ Create the MumbleUser instance to save in. """
  305. if 'linkacc' not in self.data or self.mumbleid <= 0:
  306. return self.cleaned_data
  307. # Store the owner that EXT_validate told us
  308. owner = self.instance.owner
  309. # try to find a MumbleUser instance for the target user, if none create it
  310. try:
  311. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid )
  312. except MumbleUser.DoesNotExist:
  313. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid )
  314. m_user.save( dontConfigureMurmur=True )
  315. else:
  316. if m_user.owner is not None:
  317. raise forms.ValidationError( _( "That account belongs to someone else." ) )
  318. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  319. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) )
  320. # replace our instance with the mumbleuser found above and reinstate the owner
  321. self.instance = m_user
  322. self.instance.owner = owner
  323. return self.cleaned_data
  324. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  325. class MumbleUserAdminForm( PropertyModelForm ):
  326. aclAdmin = forms.BooleanField( required=False )
  327. password = forms.CharField( widget=forms.PasswordInput, required=False )
  328. def clean_password( self ):
  329. """ Verify a password has been given. """
  330. passwd = self.cleaned_data['password']
  331. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  332. raise forms.ValidationError( _( "Cannot register player without a password!" ) )
  333. return passwd
  334. class Meta:
  335. model = MumbleUser
  336. fields = "__all__"
  337. class MumbleKickForm( Form ):
  338. session = forms.IntegerField()
  339. ban = forms.BooleanField( required=False )
  340. reason = forms.CharField( required=False )
  341. class MumbleTextureForm( Form ):
  342. """ The form used to upload a new image to be set as texture. """
  343. usegravatar = forms.BooleanField( required=False, label=_("Use my Gravatar as my Texture") )
  344. texturefile = forms.ImageField( required=False, label=_("User Texture") )