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.

327 lines
12 KiB

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