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.

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