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.

325 lines
11 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, widget=forms.PasswordInput )
  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:
  81. if self.instance.booted:
  82. def add_item( item, level ):
  83. if item.is_server or item.is_channel:
  84. choices.append( ( item.chanid, ( "-"*level + " " + item.name ) ) )
  85. self.instance.rootchan.visit(add_item)
  86. else:
  87. current = self.instance.defchan
  88. if current is not None:
  89. choices.append( ( current, "Current value: %d" % current ) )
  90. self.fields['defchan'].choices = choices
  91. class Meta:
  92. model = Mumble;
  93. fields = ['name'];
  94. class MumbleAdminForm( MumbleForm ):
  95. """ A Mumble Server admin form intended to be used by the server hoster. """
  96. users = forms.IntegerField( required=False )
  97. bwidth = forms.IntegerField( required=False )
  98. sslcrt = forms.CharField( required=False, widget=forms.Textarea )
  99. sslkey = forms.CharField( required=False, widget=forms.Textarea )
  100. booted = forms.BooleanField( required=False )
  101. autoboot = forms.BooleanField( required=False )
  102. bonjour = forms.BooleanField( required=False )
  103. class Meta:
  104. fields = None
  105. exclude = None
  106. def clean_port( self ):
  107. """ Check if the port number is valid. """
  108. port = self.cleaned_data['port'];
  109. if port is not None and port != '':
  110. if port < 1 or port >= 2**16:
  111. raise forms.ValidationError(
  112. _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  113. 'portno': port,
  114. 'minrange': 1,
  115. 'maxrange': 2**16,
  116. });
  117. return port;
  118. return None
  119. class MumbleServerForm( ModelForm ):
  120. defaultconf = forms.CharField( label=_("Default config"), required=False, widget=forms.Textarea )
  121. def __init__( self, *args, **kwargs ):
  122. ModelForm.__init__( self, *args, **kwargs )
  123. if self.instance and self.instance.id:
  124. if self.instance.online:
  125. confstr = ""
  126. conf = self.instance.defaultconf
  127. for field in conf:
  128. confstr += "%s: %s\n" % ( field, conf[field] )
  129. self.fields["defaultconf"].initial = confstr
  130. else:
  131. self.fields["defaultconf"].initial = _("This server is currently offline.")
  132. class Meta:
  133. model = MumbleServer
  134. class MumbleUserForm( ModelForm ):
  135. """ The user registration form used to register an account. """
  136. password = forms.CharField( widget=forms.PasswordInput, required=False )
  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 and ( not self.instance or self.instance.mumbleid == -1 ):
  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.save( dontConfigureMurmur=True );
  221. else:
  222. if m_user.owner is not None:
  223. raise forms.ValidationError( _( "That account belongs to someone else." ) );
  224. if m_user.getAdmin() and not settings.ALLOW_ACCOUNT_LINKING_ADMINS:
  225. raise forms.ValidationError( _( "Linking Admin accounts is not allowed." ) );
  226. self.instance = m_user;
  227. return self.cleaned_data;
  228. class MumbleUserAdminForm( PropertyModelForm ):
  229. aclAdmin = forms.BooleanField( required=False );
  230. password = forms.CharField( widget=forms.PasswordInput, required=False )
  231. def clean_password( self ):
  232. """ Verify a password has been given. """
  233. passwd = self.cleaned_data['password'];
  234. if not passwd and ( not self.instance or self.instance.mumbleid == -1 ):
  235. raise forms.ValidationError( _( "Cannot register player without a password!" ) );
  236. return passwd;
  237. class Meta:
  238. model = Mumble;
  239. class MumbleKickForm( Form ):
  240. session = forms.IntegerField();
  241. ban = forms.BooleanField( required=False );
  242. reason = forms.CharField( required=False );
  243. class MumbleTextureForm( Form ):
  244. """ The form used to upload a new image to be set as texture. """
  245. usegravatar = forms.BooleanField( required=False, label=_("Use my Gravatar as my Texture") );
  246. texturefile = forms.ImageField( required=False, label=_("User Texture") );