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.

312 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 )
  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. bonjour = forms.BooleanField( required=False )
  97. class Meta:
  98. fields = None
  99. exclude = None
  100. def clean_port( self ):
  101. """ If portno == -1 autoassign, and check if the port number is valid. """
  102. port = self.cleaned_data['port'];
  103. if port == -1:
  104. port = max( [ rec['port'] for rec in Mumble.objects.values('port') ] ) + 1;
  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. def clean( self ):
  114. """ Try to bind to the addr and port to verify that they are available. """
  115. if self.instance.id is not None or 'addr' not in self.cleaned_data or 'port' not in self.cleaned_data:
  116. # Editing old instance or previous validation failed already, don't try to bind
  117. return self.cleaned_data;
  118. addr = socket.gethostbyname( self.cleaned_data['addr'] );
  119. port = self.cleaned_data['port'];
  120. try:
  121. socktcp = socket.socket( socket.AF_INET, socket.SOCK_STREAM );
  122. socktcp.bind( ( addr, port ) );
  123. except socket.error, err:
  124. raise forms.ValidationError( err.args[1] );
  125. finally:
  126. socktcp.close();
  127. try:
  128. sockudp = socket.socket( socket.AF_INET, socket.SOCK_DGRAM );
  129. sockudp.bind( ( addr, port ) );
  130. except socket.error, err:
  131. raise forms.ValidationError( err.args[1] );
  132. finally:
  133. sockudp.close();
  134. return self.cleaned_data;
  135. class MumbleUserForm( ModelForm ):
  136. """ The user registration form used to register an account. """
  137. def __init__( self, *args, **kwargs ):
  138. ModelForm.__init__( self, *args, **kwargs );
  139. self.server = None;
  140. def clean_name( self ):
  141. """ Check if the desired name is forbidden or taken. """
  142. name = self.cleaned_data['name'];
  143. if self.server is None:
  144. raise AttributeError( "You need to set the form's server attribute to the server instance "
  145. "for validation to work." );
  146. if self.server.player and re.compile( self.server.player ).match( name ) is None:
  147. raise forms.ValidationError( _( "That name is forbidden by the server." ) );
  148. if not self.instance.id and len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) > 0:
  149. raise forms.ValidationError( _( "Another player already registered that name." ) );
  150. return name;
  151. def clean_password( self ):
  152. """ Verify a password has been given. """
  153. passwd = self.cleaned_data['password'];
  154. if not passwd:
  155. raise forms.ValidationError( _( "Cannot register player without a password!" ) );
  156. return passwd;
  157. class Meta:
  158. model = MumbleUser;
  159. fields = ( 'name', 'password' );
  160. class MumbleUserPasswordForm( MumbleUserForm ):
  161. """ The user registration form used to register an account on a private server in protected mode. """
  162. serverpw = forms.CharField(
  163. label=_('Server Password'),
  164. help_text=_('This server is private and protected mode is active. Please enter the server password.'),
  165. widget=forms.PasswordInput(render_value=False)
  166. );
  167. def clean_serverpw( self ):
  168. """ Validate the password """
  169. serverpw = self.cleaned_data['serverpw'];
  170. if self.server.passwd != serverpw:
  171. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  172. return serverpw;
  173. def clean( self ):
  174. """ prevent save() from trying to store the password in the Model instance. """
  175. # clean() will be called after clean_serverpw(), so it has already been validated here.
  176. if 'serverpw' in self.cleaned_data:
  177. del( self.cleaned_data['serverpw'] );
  178. return self.cleaned_data;
  179. class MumbleUserLinkForm( MumbleUserForm ):
  180. """ Special registration form to either register or link an account. """
  181. linkacc = forms.BooleanField(
  182. label=_('Link account'),
  183. help_text=_('The account already exists and belongs to me, just link it instead of creating.'),
  184. required=False,
  185. );
  186. def __init__( self, *args, **kwargs ):
  187. MumbleUserForm.__init__( self, *args, **kwargs );
  188. self.mumbleid = None;
  189. def clean_name( self ):
  190. """ Check if the target account exists in Murmur. """
  191. if 'linkacc' not in self.data:
  192. return MumbleUserForm.clean_name( self );
  193. # Check if user exists
  194. name = self.cleaned_data['name'];
  195. if len( self.server.ctl.getRegisteredPlayers( self.server.srvid, name ) ) != 1:
  196. raise forms.ValidationError( _( "No such user found." ) );
  197. return name;
  198. def clean_password( self ):
  199. """ Verify that the password is correct. """
  200. if 'linkacc' not in self.data:
  201. return MumbleUserForm.clean_password( self );
  202. if 'name' not in self.cleaned_data:
  203. # keep clean() from trying to find a user that CAN'T exist
  204. self.mumbleid = -10;
  205. return '';
  206. # Validate password with Murmur
  207. passwd = self.cleaned_data['password'];
  208. self.mumbleid = self.server.ctl.verifyPassword( self.server.srvid, self.cleaned_data['name'], passwd )
  209. if self.mumbleid <= 0:
  210. raise forms.ValidationError( _( "The password you entered is incorrect." ) );
  211. return passwd;
  212. def clean( self ):
  213. """ Create the MumbleUser instance to save in. """
  214. if 'linkacc' not in self.data or self.mumbleid <= 0:
  215. return self.cleaned_data;
  216. try:
  217. m_user = MumbleUser.objects.get( server=self.server, mumbleid=self.mumbleid );
  218. except MumbleUser.DoesNotExist:
  219. m_user = MumbleUser( server=self.server, name=self.cleaned_data['name'], mumbleid=self.mumbleid );
  220. m_user.isAdmin = m_user.getAdmin();
  221. m_user.save( dontConfigureMurmur=True );
  222. else:
  223. if m_user.owner is not None:
  224. raise forms.ValidationError( _( "That account belongs to someone else." ) );
  225. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  226. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) );
  227. self.instance = m_user;
  228. return self.cleaned_data;
  229. class MumbleUserAdminForm( PropertyModelForm ):
  230. aclAdmin = forms.BooleanField( required=False );
  231. class Meta:
  232. model = Mumble;
  233. class MumbleTextureForm( Form ):
  234. """ The form used to upload a new image to be set as texture. """
  235. texturefile = forms.ImageField();