forms.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. from future import standard_library
  18. standard_library.install_aliases()
  19. from builtins import zip
  20. from builtins import range
  21. import logging
  22. import sys
  23. import urllib.request, urllib.error
  24. from django import forms
  25. from django.forms import FileField, CharField, BooleanField, Textarea
  26. from django.forms.formsets import formset_factory, BaseFormSet
  27. from aws.s3 import S3A_ROOT, normpath as s3_normpath
  28. from azure.abfs.__init__ import ABFS_ROOT, normpath as abfs_normpath
  29. from desktop.lib import i18n
  30. from hadoop.fs import normpath
  31. from useradmin.models import User, Group
  32. from filebrowser.lib import rwx
  33. if sys.version_info[0] > 2:
  34. from urllib.parse import unquote as urllib_unquote
  35. from django.utils.translation import gettext_lazy as _
  36. else:
  37. from urllib import unquote as urllib_unquote
  38. from django.utils.translation import ugettext_lazy as _
  39. logger = logging.getLogger(__name__)
  40. class FormSet(BaseFormSet):
  41. def __init__(self, data=None, prefix=None, *args, **kwargs):
  42. self.prefix = prefix or self.get_default_prefix()
  43. if data:
  44. self.data = {}
  45. # Add management field info
  46. # This is hard coded given that none of these keys or info is exportable
  47. # This could be a problem point if the management form changes in later releases
  48. self.data['%s-TOTAL_FORMS' % self.prefix] = len(data)
  49. self.data['%s-INITIAL_FORMS' % self.prefix] = len(data)
  50. self.data['%s-MAX_NUM_FORMS' % self.prefix] = 0
  51. # Add correct data
  52. for i in range(0, len(data)):
  53. prefix = self.add_prefix(i)
  54. for field in data[i]:
  55. self.data['%s-%s' % (prefix, field)] = data[i][field]
  56. BaseFormSet.__init__(self, self.data, self.prefix, *args, **kwargs)
  57. class PathField(CharField):
  58. def __init__(self, label, help_text=None, **kwargs):
  59. kwargs.setdefault('required', True)
  60. kwargs.setdefault('min_length', 1)
  61. forms.CharField.__init__(self, label=label, help_text=help_text, **kwargs)
  62. def clean(self, value):
  63. cleaned_path = CharField.clean(self, value)
  64. if not value:
  65. value = ''
  66. elif value.lower().startswith(S3A_ROOT):
  67. cleaned_path = s3_normpath(cleaned_path)
  68. elif value.lower().startswith(ABFS_ROOT):
  69. cleaned_path = abfs_normpath(cleaned_path)
  70. else:
  71. cleaned_path = normpath(cleaned_path)
  72. return cleaned_path
  73. class EditorForm(forms.Form):
  74. path = PathField(label=_("File to edit"))
  75. contents = CharField(widget=Textarea, label=_("Contents"), required=False)
  76. encoding = CharField(label=_('Encoding'), required=False)
  77. def clean_path(self):
  78. return urllib_unquote(self.cleaned_data.get('path', ''))
  79. def clean_contents(self):
  80. return self.cleaned_data.get('contents', '').replace('\r\n', '\n')
  81. def clean_encoding(self):
  82. encoding = self.cleaned_data.get('encoding', '').strip()
  83. if not encoding:
  84. return i18n.get_site_encoding()
  85. return encoding
  86. class RenameForm(forms.Form):
  87. op = "rename"
  88. src_path = CharField(label=_("File to rename"), help_text=_("The file to rename."))
  89. dest_path = CharField(label=_("New name"), help_text=_("Rename the file to:"))
  90. class BaseRenameFormSet(FormSet):
  91. op = "rename"
  92. RenameFormSet = formset_factory(RenameForm, formset=BaseRenameFormSet, extra=0)
  93. class CopyForm(forms.Form):
  94. op = "copy"
  95. src_path = CharField(label=_("File to copy"), help_text=_("The file to copy."))
  96. dest_path = CharField(label=_("Destination location"), help_text=_("Copy the file to:"))
  97. class BaseCopyFormSet(FormSet):
  98. op = "copy"
  99. CopyFormSet = formset_factory(CopyForm, formset=BaseCopyFormSet, extra=0)
  100. class SetReplicationFactorForm(forms.Form):
  101. op = "setreplication"
  102. src_path = CharField(label=_("File to set replication factor"), help_text=_("The file to set replication factor."))
  103. replication_factor = CharField(label=_("Value of replication factor"), help_text=_("The value of replication factor."))
  104. class UploadFileForm(forms.Form):
  105. op = "upload"
  106. # The "hdfs" prefix in "hdfs_file" triggers the HDFSfileUploadHandler
  107. hdfs_file = FileField(label=_("File to Upload"))
  108. dest = PathField(label=_("Destination Path"), help_text=_("Filename or directory to upload to."), required=False) # Used actually?
  109. extract_archive = BooleanField(required=False)
  110. class UploadLocalFileForm(forms.Form):
  111. op = "upload"
  112. file = FileField(label=_("File to Upload"))
  113. class UploadArchiveForm(forms.Form):
  114. op = "upload"
  115. archive = FileField(label=_("Archive to Upload"))
  116. dest = PathField(label=_("Destination Path"), help_text=_("Archive to upload to."))
  117. class RemoveForm(forms.Form):
  118. op = "remove"
  119. path = PathField(label=_("File to remove"))
  120. class RmDirForm(forms.Form):
  121. op = "rmdir"
  122. path = PathField(label=_("Directory to remove"))
  123. class RmTreeForm(forms.Form):
  124. op = "rmtree"
  125. path = PathField(label=_("Directory to remove (recursively)"))
  126. class BaseRmTreeFormset(FormSet):
  127. op = "rmtree"
  128. RmTreeFormSet = formset_factory(RmTreeForm, formset=BaseRmTreeFormset, extra=0)
  129. class RestoreForm(forms.Form):
  130. op = "rmtree"
  131. path = PathField(label=_("Path to restore"))
  132. class BaseRestoreFormset(FormSet):
  133. op = "restore"
  134. RestoreFormSet = formset_factory(RestoreForm, formset=BaseRestoreFormset, extra=0)
  135. class TrashPurgeForm(forms.Form):
  136. op = "purge_trash"
  137. class MkDirForm(forms.Form):
  138. op = "mkdir"
  139. path = PathField(label=_("Path in which to create the directory"))
  140. name = PathField(label=_("Directory Name"))
  141. class TouchForm(forms.Form):
  142. op = "touch"
  143. path = PathField(label=_("Path in which to create the file"))
  144. name = PathField(label=_("File Name"))
  145. class ChownForm(forms.Form):
  146. op = "chown"
  147. path = PathField(label=_("Path to change user/group ownership"))
  148. # These could be "ChoiceFields", listing only users and groups
  149. # that the current user has permissions for.
  150. user = CharField(label=_("User"), min_length=1)
  151. user_other = CharField(label=_("OtherUser"), min_length=1, required=False)
  152. group = CharField(label=_("Group"), min_length=1)
  153. group_other = CharField(label=_("OtherGroup"), min_length=1, required=False)
  154. recursive = BooleanField(label=_("Recursive"), required=False)
  155. def __init__(self, *args, **kwargs):
  156. super(ChownForm, self).__init__(*args, **kwargs)
  157. self.all_groups = [group.name for group in Group.objects.all()]
  158. self.all_users = [user.username for user in User.objects.all()]
  159. class BaseChownFormSet(FormSet):
  160. op = "chown"
  161. ChownFormSet = formset_factory(ChownForm, formset=BaseChownFormSet, extra=0)
  162. class ChmodForm(forms.Form):
  163. op = "chmod"
  164. path = PathField(label=_("Path to change permissions"))
  165. # By default, BooleanField only validates when
  166. # it's checked.
  167. user_read = BooleanField(required=False)
  168. user_write = BooleanField(required=False)
  169. user_execute = BooleanField(required=False)
  170. group_read = BooleanField(required=False)
  171. group_write = BooleanField(required=False)
  172. group_execute = BooleanField(required=False)
  173. other_read = BooleanField(required=False)
  174. other_write = BooleanField(required=False)
  175. other_execute = BooleanField(required=False)
  176. sticky = BooleanField(required=False)
  177. recursive = BooleanField(required=False)
  178. names = ("user_read", "user_write", "user_execute",
  179. "group_read", "group_write", "group_execute",
  180. "other_read", "other_write", "other_execute",
  181. "sticky")
  182. def __init__(self, initial, *args, **kwargs):
  183. logging.info(dir(self))
  184. logging.info(dir(type(self)))
  185. # Convert from string representation.
  186. mode = initial.get("mode")
  187. if mode is not None:
  188. mode = int(mode, 8)
  189. bools = rwx.expand_mode(mode)
  190. for name, b in zip(self.names, bools):
  191. initial[name] = b
  192. logging.debug(initial)
  193. kwargs['initial'] = initial
  194. forms.Form.__init__(self, *args, **kwargs)
  195. def full_clean(self):
  196. forms.Form.full_clean(self)
  197. if hasattr(self, "cleaned_data"):
  198. self.cleaned_data["mode"] = rwx.compress_mode([self.cleaned_data[name] for name in self.names])
  199. class BaseChmodFormSet(FormSet):
  200. op = "chmod"
  201. ChmodFormSet = formset_factory(ChmodForm, formset=BaseChmodFormSet, extra=0)