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.

431 lines
17 KiB

  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 _
  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 )
  86. motd = forms.CharField( required=False, widget=forms.Textarea )
  87. passwd = forms.CharField( required=False, help_text=_(
  88. "Password required to join. Leave empty for public servers.") )
  89. supw = forms.CharField( required=False, widget=forms.PasswordInput )
  90. player = forms.CharField( required=False )
  91. channel = forms.CharField( required=False )
  92. defchan = forms.TypedChoiceField( choices=(), coerce=int, required=False )
  93. timeout = forms.IntegerField( required=False )
  94. certreq = forms.BooleanField( required=False )
  95. textlen = forms.IntegerField( required=False )
  96. imglen = forms.IntegerField( required=False, help_text=_("In case of messages containing Base64 encoded images this overrides textmessagelength.") )
  97. html = forms.BooleanField( required=False )
  98. rememchn= forms.BooleanField( required=False, help_text=_(
  99. "Remember the channel users were in when they quit, and automatically move them to "
  100. "that channel when they join.") )
  101. sgversion= forms.CharField( required=False )
  102. sgpositional = forms.BooleanField( required=False )
  103. sgptt = forms.BooleanField( required=False )
  104. opusthres = forms.IntegerField( required=False, initial=100, help_text=_("Force Opus-Codec if this percentage of clients support it. Enter without % character.") )
  105. reghostname = forms.CharField( required=False, help_text=_("Server hostname (domain name) that is used to connect to the server from the server list. This must be a A or AAAA record.") )
  106. regpasswd = forms.CharField( required=False, help_text=_("Password used to register the server in the server list") )
  107. regloc = forms.CharField( required=False, help_text=_("Location of the server as ISO_3166-1 country code. In order to work you must have a strong server certificate. Additionally the C= field of the used server certificate must have the same country code OR the used tld in registerhostname must contain the same location code FIXME schoen machen.") )
  108. allowping = forms.BooleanField( required=False, initial=True, help_text=_("Allow ping packets from the server (to show usercount and slots in the server browser). This must not be disabled if the server should be listed in the serverlist.") )
  109. sendversion = forms.BooleanField( required=False, initial=True, help_text=_("Allow server to send system version to the client.") )
  110. def __init__( self, *args, **kwargs ):
  111. PropertyModelForm.__init__( self, *args, **kwargs )
  112. # Populate the `default channel' field's choices
  113. choices = [ ('', '----------') ]
  114. if self.instance and self.instance.srvid is not None:
  115. if self.instance.booted:
  116. def add_item( item, level ):
  117. if item.is_server or item.is_channel:
  118. choices.append( ( item.chanid, ( "-"*level + " " + item.name ) ) )
  119. self.instance.rootchan.visit(add_item)
  120. else:
  121. current = self.instance.defchan
  122. if current is not None:
  123. choices.append( ( current, "Current value: %d" % current ) )
  124. self.fields['defchan'].choices = choices
  125. class Meta:
  126. model = Mumble
  127. fields = ['name']
  128. def EXT_authorize( self, request, action ):
  129. return self.instance.isUserAdmin( request.user )
  130. EXT_FORMS_PROVIDER.register_form( MumbleForm )
  131. class MumbleAdminForm( MumbleForm ):
  132. """ A Mumble Server admin form intended to be used by the server hoster. """
  133. users = forms.IntegerField( required=False )
  134. usersperchannel = forms.IntegerField( required=False )
  135. channestlim = forms.IntegerField( required=False, help_text=_("Limit channel nesting to this level.") )
  136. bwidth = forms.IntegerField( required=False )
  137. sslca = forms.CharField( required=False, widget=forms.Textarea, help_text=_("Can be a path or the file content in PEM format.") )
  138. sslcrt = forms.CharField( required=False, widget=forms.Textarea )
  139. sslkey = forms.CharField( required=False, widget=forms.Textarea )
  140. sslpass = forms.CharField( required=False, help_text=_("Key passphrase of the SSL certificate, if any.") )
  141. booted = forms.BooleanField( required=False, initial=True )
  142. autoboot = forms.BooleanField( required=False, initial=True )
  143. bonjour = forms.BooleanField( required=False )
  144. class Meta:
  145. fields = None
  146. exclude = None
  147. def clean_port( self ):
  148. """ Check if the port number is valid. """
  149. port = self.cleaned_data['port']
  150. if port is not None and port != '':
  151. if port < 1 or port >= 2**16:
  152. raise forms.ValidationError(
  153. _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  154. 'portno': port,
  155. 'minrange': 1,
  156. 'maxrange': 2**16,
  157. })
  158. return port
  159. return None
  160. class MumbleServerForm( ModelForm ):
  161. defaultconf = forms.CharField( label=_("Default config"), required=False, widget=forms.Textarea )
  162. def __init__( self, *args, **kwargs ):
  163. ModelForm.__init__( self, *args, **kwargs )
  164. # self.instance = instance of MumbleServer, NOT a server instance
  165. if self.instance and self.instance.id:
  166. if self.instance.online:
  167. confstr = ""
  168. conf = self.instance.defaultconf
  169. for field in conf:
  170. confstr += "%s: %s\n" % ( field, conf[field] )
  171. self.fields["defaultconf"].initial = confstr
  172. else:
  173. self.fields["defaultconf"].initial = _("This server is currently offline.")
  174. class Meta:
  175. model = MumbleServer
  176. class MumbleUserForm( ModelForm ):
  177. """ The user registration form used to register an account. """
  178. password = forms.CharField( label=_("Password"), widget=forms.PasswordInput, required=False )
  179. def __init__( self, *args, **kwargs ):
  180. ModelForm.__init__( self, *args, **kwargs )
  181. self.server = None
  182. def EXT_authorize( self, request, action ):
  183. if not request.user.is_authenticated():
  184. return False
  185. if action == "update" and settings.PROTECTED_MODE and self.instance.id is None:
  186. # creating new user in protected mode -> need UserPasswordForm
  187. return False
  188. if self.instance.id is not None and request.user != self.instance.owner:
  189. # editing another account
  190. return False
  191. return True
  192. def EXT_validate( self, request ):
  193. self.instance.owner = request.user
  194. if "serverid" in request.POST:
  195. try:
  196. self.server = Mumble.objects.get( id=int(request.POST['serverid']) )
  197. except Mumble.DoesNotExist:
  198. return False
  199. else:
  200. return True
  201. return False
  202. def clean_name( self ):
  203. """ Check if the desired name is forbidden or taken. """
  204. name = self.cleaned_data['name']
  205. if self.server is None:
  206. raise AttributeError( "You need to set the form's server attribute to the server instance "
  207. "for validation to work." )
  208. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  209. raise forms.ValidationError( _( "That name is forbidden by the server." ) )
  210. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  211. raise forms.ValidationError( _( "Another player already registered that name." ) )
  212. return name
  213. def clean_password( self ):
  214. """ Verify a password has been given. """
  215. passwd = self.cleaned_data['password']
  216. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  217. raise forms.ValidationError( _( "Cannot register player without a password!" ) )
  218. return passwd
  219. def save(self):
  220. self.instance.server = self.server
  221. ModelForm.save(self)
  222. class Meta:
  223. model = MumbleUser
  224. fields = ( 'name', 'password' )
  225. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  226. class MumbleUserPasswordForm( MumbleUserForm ):
  227. """ The user registration form used to register an account on a private server in protected mode. """
  228. serverpw = forms.CharField(
  229. label=_('Server Password'),
  230. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  231. widget=forms.PasswordInput(render_value=False)
  232. )
  233. def EXT_authorize( self, request, action ):
  234. if not request.user.is_authenticated():
  235. return False
  236. if self.instance.id is not None and request.user != self.instance.owner:
  237. # editing another account
  238. return False
  239. return True
  240. def clean_serverpw( self ):
  241. """ Validate the password """
  242. serverpw = self.cleaned_data['serverpw']
  243. if self.server.passwd != serverpw:
  244. raise forms.ValidationError( _( "The password you entered is incorrect." ) )
  245. return serverpw
  246. def clean( self ):
  247. """ prevent save() from trying to store the password in the Model instance. """
  248. # clean() will be called after clean_serverpw(), so it has already been validated here.
  249. if 'serverpw' in self.cleaned_data:
  250. del( self.cleaned_data['serverpw'] )
  251. return self.cleaned_data
  252. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  253. class MumbleUserLinkForm( MumbleUserForm ):
  254. """ Special registration form to either register or link an account. """
  255. linkacc = forms.BooleanField(
  256. label=_('Link account'),
  257. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  258. required=False,
  259. )
  260. def __init__( self, *args, **kwargs ):
  261. MumbleUserForm.__init__( self, *args, **kwargs )
  262. self.mumbleid = None
  263. def EXT_authorize( self, request, action ):
  264. if not request.user.is_authenticated() or action == "get":
  265. return False
  266. if self.instance.id is not None and request.user != self.instance.owner:
  267. # editing another account
  268. return False
  269. return settings.ALLOW_ACCOUNT_LINKING
  270. def clean_name( self ):
  271. """ Check if the target account exists in Murmur. """
  272. if 'linkacc' not in self.data:
  273. return MumbleUserForm.clean_name( self )
  274. # Check if user exists
  275. name = self.cleaned_data['name']
  276. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  277. raise forms.ValidationError( _( "No such user found." ) )
  278. return name
  279. def clean_password( self ):
  280. """ Verify that the password is correct. """
  281. if 'linkacc' not in self.data:
  282. return MumbleUserForm.clean_password( self )
  283. if 'name' not in self.cleaned_data:
  284. # keep clean() from trying to find a user that CAN'T exist
  285. self.mumbleid = -10
  286. return ''
  287. # Validate password with Murmur
  288. passwd = self.cleaned_data['password']
  289. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  290. if self.mumbleid <= 0:
  291. raise forms.ValidationError( _( "The password you entered is incorrect." ) )
  292. return passwd
  293. def clean( self ):
  294. """ Create the MumbleUser instance to save in. """
  295. if 'linkacc' not in self.data or self.mumbleid <= 0:
  296. return self.cleaned_data
  297. # Store the owner that EXT_validate told us
  298. owner = self.instance.owner
  299. # try to find a MumbleUser instance for the target user, if none create it
  300. try:
  301. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid )
  302. except MumbleUser.DoesNotExist:
  303. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid )
  304. m_user.save( dontConfigureMurmur=True )
  305. else:
  306. if m_user.owner is not None:
  307. raise forms.ValidationError( _( "That account belongs to someone else." ) )
  308. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  309. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) )
  310. # replace our instance with the mumbleuser found above and reinstate the owner
  311. self.instance = m_user
  312. self.instance.owner = owner
  313. return self.cleaned_data
  314. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  315. class MumbleUserAdminForm( PropertyModelForm ):
  316. aclAdmin = forms.BooleanField( required=False )
  317. password = forms.CharField( widget=forms.PasswordInput, required=False )
  318. def clean_password( self ):
  319. """ Verify a password has been given. """
  320. passwd = self.cleaned_data['password']
  321. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  322. raise forms.ValidationError( _( "Cannot register player without a password!" ) )
  323. return passwd
  324. class Meta:
  325. model = MumbleUser
  326. class MumbleKickForm( Form ):
  327. session = forms.IntegerField()
  328. ban = forms.BooleanField( required=False )
  329. reason = forms.CharField( required=False )
  330. class MumbleTextureForm( Form ):
  331. """ The form used to upload a new image to be set as texture. """
  332. usegravatar = forms.BooleanField( required=False, label=_("Use my Gravatar as my Texture") )
  333. texturefile = forms.ImageField( required=False, label=_("User Texture") )