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.

317 lines
10 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. password = forms.CharField( widget=forms.PasswordInput, required=False )
  129. def __init__( self, *args, **kwargs ):
  130. ModelForm.__init__( self, *args, **kwargs );
  131. self.server = None;
  132. def clean_name( self ):
  133. """ Check if the desired name is forbidden or taken. """
  134. name = self.cleaned_data['name'];
  135. if self.server is None:
  136. raise AttributeError( "You need to set the form's server attribute to the server instance "
  137. "for validation to work." );
  138. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  139. raise forms.ValidationError( _( "That name is forbidden by the server." ) );
  140. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  141. raise forms.ValidationError( _( "Another player already registered that name." ) );
  142. return name;
  143. def clean_password( self ):
  144. """ Verify a password has been given. """
  145. passwd = self.cleaned_data['password'];
  146. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  147. raise forms.ValidationError( _( "Cannot register player without a password!" ) );
  148. return passwd;
  149. class Meta:
  150. model = MumbleUser;
  151. fields = ( 'name', 'password' );
  152. class MumbleUserPasswordForm( MumbleUserForm ):
  153. """ The user registration form used to register an account on a private server in protected mode. """
  154. serverpw = forms.CharField(
  155. label=_('Server Password'),
  156. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  157. widget=forms.PasswordInput(render_value=False)
  158. );
  159. def clean_serverpw( self ):
  160. """ Validate the password """
  161. serverpw = self.cleaned_data['serverpw'];
  162. if self.server.passwd != serverpw:
  163. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  164. return serverpw;
  165. def clean( self ):
  166. """ prevent save() from trying to store the password in the Model instance. """
  167. # clean() will be called after clean_serverpw(), so it has already been validated here.
  168. if 'serverpw' in self.cleaned_data:
  169. del( self.cleaned_data['serverpw'] );
  170. return self.cleaned_data;
  171. class MumbleUserLinkForm( MumbleUserForm ):
  172. """ Special registration form to either register or link an account. """
  173. linkacc = forms.BooleanField(
  174. label=_('Link account'),
  175. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  176. required=False,
  177. );
  178. def __init__( self, *args, **kwargs ):
  179. MumbleUserForm.__init__( self, *args, **kwargs );
  180. self.mumbleid = None;
  181. def clean_name( self ):
  182. """ Check if the target account exists in Murmur. """
  183. if 'linkacc' not in self.data:
  184. return MumbleUserForm.clean_name( self );
  185. # Check if user exists
  186. name = self.cleaned_data['name'];
  187. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  188. raise forms.ValidationError( _( "No such user found." ) );
  189. return name;
  190. def clean_password( self ):
  191. """ Verify that the password is correct. """
  192. if 'linkacc' not in self.data:
  193. return MumbleUserForm.clean_password( self );
  194. if 'name' not in self.cleaned_data:
  195. # keep clean() from trying to find a user that CAN'T exist
  196. self.mumbleid = -10;
  197. return '';
  198. # Validate password with Murmur
  199. passwd = self.cleaned_data['password'];
  200. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  201. if self.mumbleid <= 0:
  202. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  203. return passwd;
  204. def clean( self ):
  205. """ Create the MumbleUser instance to save in. """
  206. if 'linkacc' not in self.data or self.mumbleid <= 0:
  207. return self.cleaned_data;
  208. try:
  209. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid );
  210. except MumbleUser.DoesNotExist:
  211. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid );
  212. m_user.save( dontConfigureMurmur=True );
  213. else:
  214. if m_user.owner is not None:
  215. raise forms.ValidationError( _( "That account belongs to someone else." ) );
  216. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  217. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) );
  218. self.instance = m_user;
  219. return self.cleaned_data;
  220. class MumbleUserAdminForm( PropertyModelForm ):
  221. aclAdmin = forms.BooleanField( required=False );
  222. password = forms.CharField( widget=forms.PasswordInput, required=False )
  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. class Meta:
  230. model = Mumble;
  231. class MumbleKickForm( Form ):
  232. session = forms.IntegerField();
  233. ban = forms.BooleanField( required=False );
  234. reason = forms.CharField( required=False );
  235. class MumbleTextureForm( Form ):
  236. """ The form used to upload a new image to be set as texture. """
  237. texturefile = forms.ImageField();