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.

310 lines
10 KiB

15 years ago
15 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 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. docstr = getattr( self.instance.__class__, fldname ).__doc__
  36. if docstr:
  37. self.fields[fldname].label = _( docstr )
  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, help_text=_(
  72. "Enter the ID of the default channel here. The Channel viewer displays the ID to "
  73. "server admins on the channel detail page.") )
  74. def __init__( self, *args, **kwargs ):
  75. PropertyModelForm.__init__( self, *args, **kwargs )
  76. # Populate the `default channel' field's choices
  77. choices = [ ('', '----------') ]
  78. if self.instance and self.instance.srvid is not None and self.instance.booted:
  79. def add_item( item, level ):
  80. if item.is_server or item.is_channel:
  81. choices.append( ( str(item.chanid), ( "-"*level + " " + item.name ) ) )
  82. self.instance.rootchan.visit(add_item)
  83. self.fields['defchan'].choices = choices
  84. class Meta:
  85. model = Mumble;
  86. fields = ['name'];
  87. class MumbleAdminForm( MumbleForm ):
  88. """ A Mumble Server admin form intended to be used by the server hoster. """
  89. users = forms.IntegerField( required=False )
  90. bwidth = forms.IntegerField( required=False )
  91. sslcrt = forms.CharField( required=False, widget=forms.Textarea )
  92. sslkey = forms.CharField( required=False, widget=forms.Textarea )
  93. booted = forms.BooleanField( required=False )
  94. class Meta:
  95. fields = None
  96. exclude = None
  97. def clean_port( self ):
  98. """ If portno == -1 autoassign, and check if the port number is valid. """
  99. port = self.cleaned_data['port'];
  100. if port == -1:
  101. port = max( [ rec['port'] for rec in Mumble.objects.values('port') ] ) + 1;
  102. if port < 1 or port >= 2**16:
  103. raise forms.ValidationError(
  104. _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  105. 'portno': port,
  106. 'minrange': 1,
  107. 'maxrange': 2**16,
  108. });
  109. return port;
  110. def clean( self ):
  111. """ Try to bind to the addr and port to verify that they are available. """
  112. if self.instance.id is not None or 'addr' not in self.cleaned_data or 'port' not in self.cleaned_data:
  113. # Editing old instance or previous validation failed already, don't try to bind
  114. return self.cleaned_data;
  115. addr = socket.gethostbyname( self.cleaned_data['addr'] );
  116. port = self.cleaned_data['port'];
  117. try:
  118. socktcp = socket.socket( socket.AF_INET, socket.SOCK_STREAM );
  119. socktcp.bind( ( addr, port ) );
  120. except socket.error, err:
  121. raise forms.ValidationError( err.args[1] );
  122. finally:
  123. socktcp.close();
  124. try:
  125. sockudp = socket.socket( socket.AF_INET, socket.SOCK_DGRAM );
  126. sockudp.bind( ( addr, port ) );
  127. except socket.error, err:
  128. raise forms.ValidationError( err.args[1] );
  129. finally:
  130. sockudp.close();
  131. return self.cleaned_data;
  132. class MumbleUserForm( ModelForm ):
  133. """ The user registration form used to register an account. """
  134. def __init__( self, *args, **kwargs ):
  135. ModelForm.__init__( self, *args, **kwargs );
  136. self.server = None;
  137. def clean_name( self ):
  138. """ Check if the desired name is forbidden or taken. """
  139. name = self.cleaned_data['name'];
  140. if self.server is None:
  141. raise AttributeError( "You need to set the form's server attribute to the server instance "
  142. "for validation to work." );
  143. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  144. raise forms.ValidationError( _( "That name is forbidden by the server." ) );
  145. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  146. raise forms.ValidationError( _( "Another player already registered that name." ) );
  147. return name;
  148. def clean_password( self ):
  149. """ Verify a password has been given. """
  150. passwd = self.cleaned_data['password'];
  151. if not passwd:
  152. raise forms.ValidationError( _( "Cannot register player without a password!" ) );
  153. return passwd;
  154. class Meta:
  155. model = MumbleUser;
  156. fields = ( 'name', 'password' );
  157. class MumbleUserPasswordForm( MumbleUserForm ):
  158. """ The user registration form used to register an account on a private server in protected mode. """
  159. serverpw = forms.CharField(
  160. label=_('Server Password'),
  161. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  162. widget=forms.PasswordInput(render_value=False)
  163. );
  164. def clean_serverpw( self ):
  165. """ Validate the password """
  166. serverpw = self.cleaned_data['serverpw'];
  167. if self.server.passwd != serverpw:
  168. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  169. return serverpw;
  170. def clean( self ):
  171. """ prevent save() from trying to store the password in the Model instance. """
  172. # clean() will be called after clean_serverpw(), so it has already been validated here.
  173. if 'serverpw' in self.cleaned_data:
  174. del( self.cleaned_data['serverpw'] );
  175. return self.cleaned_data;
  176. class MumbleUserLinkForm( MumbleUserForm ):
  177. """ Special registration form to either register or link an account. """
  178. linkacc = forms.BooleanField(
  179. label=_('Link account'),
  180. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  181. required=False,
  182. );
  183. def __init__( self, *args, **kwargs ):
  184. MumbleUserForm.__init__( self, *args, **kwargs );
  185. self.mumbleid = None;
  186. def clean_name( self ):
  187. """ Check if the target account exists in Murmur. """
  188. if 'linkacc' not in self.data:
  189. return MumbleUserForm.clean_name( self );
  190. # Check if user exists
  191. name = self.cleaned_data['name'];
  192. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  193. raise forms.ValidationError( _( "No such user found." ) );
  194. return name;
  195. def clean_password( self ):
  196. """ Verify that the password is correct. """
  197. if 'linkacc' not in self.data:
  198. return MumbleUserForm.clean_password( self );
  199. if 'name' not in self.cleaned_data:
  200. # keep clean() from trying to find a user that CAN'T exist
  201. self.mumbleid = -10;
  202. return '';
  203. # Validate password with Murmur
  204. passwd = self.cleaned_data['password'];
  205. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  206. if self.mumbleid <= 0:
  207. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  208. return passwd;
  209. def clean( self ):
  210. """ Create the MumbleUser instance to save in. """
  211. if 'linkacc' not in self.data or self.mumbleid <= 0:
  212. return self.cleaned_data;
  213. try:
  214. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid );
  215. except MumbleUser.DoesNotExist:
  216. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid );
  217. m_user.isAdmin = m_user.getAdmin();
  218. m_user.save( dontConfigureMurmur=True );
  219. else:
  220. if m_user.owner is not None:
  221. raise forms.ValidationError( _( "That account belongs to someone else." ) );
  222. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  223. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) );
  224. self.instance = m_user;
  225. return self.cleaned_data;
  226. class MumbleUserAdminForm( PropertyModelForm ):
  227. aclAdmin = forms.BooleanField( required=False );
  228. class Meta:
  229. model = Mumble;
  230. class MumbleTextureForm( Form ):
  231. """ The form used to upload a new image to be set as texture. """
  232. texturefile = forms.ImageField();