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.

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