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.

301 lines
9.6 KiB

16 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright © 2009-2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  4. *
  5. * Mumble-Django is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This package is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. """
  15. import socket
  16. import re
  17. from django import forms
  18. from django.conf import settings
  19. from django.forms import Form, ModelForm
  20. from django.utils.translation import ugettext_lazy as _
  21. from mumble.models import MumbleServer, Mumble, MumbleUser
  22. class PropertyModelForm( ModelForm ):
  23. """ ModelForm that gets/sets fields that are not within the model's
  24. fields as model attributes. Necessary to get forms that manipulate
  25. properties.
  26. """
  27. def __init__( self, *args, **kwargs ):
  28. ModelForm.__init__( self, *args, **kwargs );
  29. if self.instance:
  30. instfields = self.instance._meta.get_all_field_names()
  31. for fldname in self.fields:
  32. if fldname in instfields:
  33. continue
  34. self.fields[fldname].initial = getattr( self.instance, fldname )
  35. prop = getattr( self.instance.__class__, fldname )
  36. if prop.__doc__:
  37. self.fields[fldname].label = prop.__doc__
  38. def save( self, commit=True ):
  39. inst = ModelForm.save( self, commit=commit )
  40. if commit:
  41. self.save_to_model( inst )
  42. else:
  43. # Update when the model has been saved.
  44. from django.db.models import signals
  45. self._update_inst = inst
  46. signals.post_save.connect( self.save_listener, sender=inst.__class__ )
  47. return inst
  48. def save_listener( self, **kwargs ):
  49. if kwargs['instance'] is self._update_inst:
  50. self.save_to_model( self._update_inst )
  51. def save_to_model( self, inst ):
  52. instfields = inst._meta.get_all_field_names()
  53. for fldname in self.fields:
  54. if fldname not in instfields:
  55. setattr( inst, fldname, self.cleaned_data[fldname] )
  56. class MumbleForm( PropertyModelForm ):
  57. """ The Mumble Server admin form that allows to configure settings which do
  58. not necessarily have to be reserved to the server hoster.
  59. Server hosters are expected to use the Django admin application instead,
  60. where everything can be configured freely.
  61. """
  62. url = forms.CharField( required=False )
  63. motd = forms.CharField( required=False, widget=forms.Textarea )
  64. passwd = forms.CharField( required=False, help_text=_(
  65. "Password required to join. Leave empty for public servers.") )
  66. supw = forms.CharField( required=False )
  67. obfsc = forms.BooleanField( required=False, help_text=_(
  68. "If on, IP adresses of the clients are not logged.") )
  69. player = forms.CharField( required=False )
  70. channel = forms.CharField( required=False )
  71. defchan = forms.TypedChoiceField( choices=(), coerce=int, required=False )
  72. timeout = forms.IntegerField( required=False )
  73. certreq = forms.BooleanField( required=False )
  74. textlen = forms.IntegerField( required=False )
  75. html = forms.BooleanField( required=False )
  76. def __init__( self, *args, **kwargs ):
  77. PropertyModelForm.__init__( self, *args, **kwargs )
  78. # Populate the `default channel' field's choices
  79. choices = [ ('', '----------') ]
  80. if self.instance and self.instance.srvid is not None and self.instance.booted:
  81. def add_item( item, level ):
  82. if item.is_server or item.is_channel:
  83. choices.append( ( str(item.chanid), ( "-"*level + " " + item.name ) ) )
  84. self.instance.rootchan.visit(add_item)
  85. self.fields['defchan'].choices = choices
  86. class Meta:
  87. model = Mumble;
  88. fields = ['name'];
  89. class MumbleAdminForm( MumbleForm ):
  90. """ A Mumble Server admin form intended to be used by the server hoster. """
  91. users = forms.IntegerField( required=False )
  92. bwidth = forms.IntegerField( required=False )
  93. sslcrt = forms.CharField( required=False, widget=forms.Textarea )
  94. sslkey = forms.CharField( required=False, widget=forms.Textarea )
  95. booted = forms.BooleanField( required=False )
  96. autoboot = forms.BooleanField( required=False )
  97. bonjour = forms.BooleanField( required=False )
  98. class Meta:
  99. fields = None
  100. exclude = None
  101. def clean_port( self ):
  102. """ Check if the port number is valid. """
  103. port = self.cleaned_data['port'];
  104. if port is not None and port != '':
  105. if port < 1 or port >= 2**16:
  106. raise forms.ValidationError(
  107. _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  108. 'portno': port,
  109. 'minrange': 1,
  110. 'maxrange': 2**16,
  111. });
  112. return port;
  113. return None
  114. class MumbleServerForm( ModelForm ):
  115. defaultconf = forms.CharField( required=False, widget=forms.Textarea )
  116. def __init__( self, *args, **kwargs ):
  117. ModelForm.__init__( self, *args, **kwargs )
  118. if self.instance:
  119. confstr = ""
  120. conf = self.instance.defaultconf
  121. for field in conf:
  122. confstr += "%s: %s\n" % ( field, conf[field] )
  123. self.fields["defaultconf"].initial = confstr
  124. class Meta:
  125. model = MumbleServer
  126. class MumbleUserForm( ModelForm ):
  127. """ The user registration form used to register an account. """
  128. def __init__( self, *args, **kwargs ):
  129. ModelForm.__init__( self, *args, **kwargs );
  130. self.server = None;
  131. def clean_name( self ):
  132. """ Check if the desired name is forbidden or taken. """
  133. name = self.cleaned_data['name'];
  134. if self.server is None:
  135. raise AttributeError( "You need to set the form's server attribute to the server instance "
  136. "for validation to work." );
  137. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  138. raise forms.ValidationError( _( "That name is forbidden by the server." ) );
  139. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  140. raise forms.ValidationError( _( "Another player already registered that name." ) );
  141. return name;
  142. def clean_password( self ):
  143. """ Verify a password has been given. """
  144. passwd = self.cleaned_data['password'];
  145. if not passwd:
  146. raise forms.ValidationError( _( "Cannot register player without a password!" ) );
  147. return passwd;
  148. class Meta:
  149. model = MumbleUser;
  150. fields = ( 'name', 'password' );
  151. class MumbleUserPasswordForm( MumbleUserForm ):
  152. """ The user registration form used to register an account on a private server in protected mode. """
  153. serverpw = forms.CharField(
  154. label=_('Server Password'),
  155. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  156. widget=forms.PasswordInput(render_value=False)
  157. );
  158. def clean_serverpw( self ):
  159. """ Validate the password """
  160. serverpw = self.cleaned_data['serverpw'];
  161. if self.server.passwd != serverpw:
  162. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  163. return serverpw;
  164. def clean( self ):
  165. """ prevent save() from trying to store the password in the Model instance. """
  166. # clean() will be called after clean_serverpw(), so it has already been validated here.
  167. if 'serverpw' in self.cleaned_data:
  168. del( self.cleaned_data['serverpw'] );
  169. return self.cleaned_data;
  170. class MumbleUserLinkForm( MumbleUserForm ):
  171. """ Special registration form to either register or link an account. """
  172. linkacc = forms.BooleanField(
  173. label=_('Link account'),
  174. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  175. required=False,
  176. );
  177. def __init__( self, *args, **kwargs ):
  178. MumbleUserForm.__init__( self, *args, **kwargs );
  179. self.mumbleid = None;
  180. def clean_name( self ):
  181. """ Check if the target account exists in Murmur. """
  182. if 'linkacc' not in self.data:
  183. return MumbleUserForm.clean_name( self );
  184. # Check if user exists
  185. name = self.cleaned_data['name'];
  186. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  187. raise forms.ValidationError( _( "No such user found." ) );
  188. return name;
  189. def clean_password( self ):
  190. """ Verify that the password is correct. """
  191. if 'linkacc' not in self.data:
  192. return MumbleUserForm.clean_password( self );
  193. if 'name' not in self.cleaned_data:
  194. # keep clean() from trying to find a user that CAN'T exist
  195. self.mumbleid = -10;
  196. return '';
  197. # Validate password with Murmur
  198. passwd = self.cleaned_data['password'];
  199. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  200. if self.mumbleid <= 0:
  201. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  202. return passwd;
  203. def clean( self ):
  204. """ Create the MumbleUser instance to save in. """
  205. if 'linkacc' not in self.data or self.mumbleid <= 0:
  206. return self.cleaned_data;
  207. try:
  208. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid );
  209. except MumbleUser.DoesNotExist:
  210. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid );
  211. m_user.save( dontConfigureMurmur=True );
  212. else:
  213. if m_user.owner is not None:
  214. raise forms.ValidationError( _( "That account belongs to someone else." ) );
  215. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  216. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) );
  217. self.instance = m_user;
  218. return self.cleaned_data;
  219. class MumbleUserAdminForm( PropertyModelForm ):
  220. aclAdmin = forms.BooleanField( required=False );
  221. class Meta:
  222. model = Mumble;
  223. class MumbleTextureForm( Form ):
  224. """ The form used to upload a new image to be set as texture. """
  225. texturefile = forms.ImageField();