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.

240 lines
7.0 KiB

10 years ago
10 years ago
10 years ago
  1. from datetime import timedelta as td
  2. import json
  3. from urllib.parse import quote, urlencode
  4. from django import forms
  5. from django.forms import URLField
  6. from django.conf import settings
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import RegexValidator
  9. from hc.front.validators import (
  10. CronExpressionValidator,
  11. TimezoneValidator,
  12. WebhookValidator,
  13. )
  14. import requests
  15. class HeadersField(forms.Field):
  16. message = """Use "Header-Name: value" pairs, one per line."""
  17. def to_python(self, value):
  18. if not value:
  19. return {}
  20. headers = {}
  21. for line in value.split("\n"):
  22. if not line.strip():
  23. continue
  24. if ":" not in line:
  25. raise ValidationError(self.message)
  26. n, v = line.split(":", maxsplit=1)
  27. n, v = n.strip(), v.strip()
  28. if not n or not v:
  29. raise ValidationError(message=self.message)
  30. headers[n] = v
  31. return headers
  32. def validate(self, value):
  33. super().validate(value)
  34. for k, v in value.items():
  35. if len(k) > 1000 or len(v) > 1000:
  36. raise ValidationError("Value too long")
  37. class NameTagsForm(forms.Form):
  38. name = forms.CharField(max_length=100, required=False)
  39. tags = forms.CharField(max_length=500, required=False)
  40. desc = forms.CharField(required=False)
  41. def clean_tags(self):
  42. result = []
  43. for part in self.cleaned_data["tags"].split(" "):
  44. part = part.strip()
  45. if part != "":
  46. result.append(part)
  47. return " ".join(result)
  48. class FilteringRulesForm(forms.Form):
  49. subject = forms.CharField(required=False, max_length=100)
  50. methods = forms.ChoiceField(required=False, choices=(("", "Any"), ("POST", "POST")))
  51. manual_resume = forms.BooleanField(required=False)
  52. class TimeoutForm(forms.Form):
  53. timeout = forms.IntegerField(min_value=60, max_value=2592000)
  54. grace = forms.IntegerField(min_value=60, max_value=2592000)
  55. def clean_timeout(self):
  56. return td(seconds=self.cleaned_data["timeout"])
  57. def clean_grace(self):
  58. return td(seconds=self.cleaned_data["grace"])
  59. class CronForm(forms.Form):
  60. schedule = forms.CharField(max_length=100, validators=[CronExpressionValidator()])
  61. tz = forms.CharField(max_length=36, validators=[TimezoneValidator()])
  62. grace = forms.IntegerField(min_value=1, max_value=43200)
  63. class AddOpsGenieForm(forms.Form):
  64. error_css_class = "has-error"
  65. region = forms.ChoiceField(initial="us", choices=(("us", "US"), ("eu", "EU")))
  66. key = forms.CharField(max_length=40)
  67. PRIO_CHOICES = [
  68. ("-2", "Lowest Priority"),
  69. ("-1", "Low Priority"),
  70. ("0", "Normal Priority"),
  71. ("1", "High Priority"),
  72. ("2", "Emergency Priority"),
  73. ]
  74. class AddPushoverForm(forms.Form):
  75. error_css_class = "has-error"
  76. pushover_user_key = forms.CharField()
  77. prio = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  78. prio_up = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  79. def get_value(self):
  80. key = self.cleaned_data["pushover_user_key"]
  81. prio = self.cleaned_data["prio"]
  82. prio_up = self.cleaned_data["prio_up"]
  83. return "%s|%s|%s" % (key, prio, prio_up)
  84. class AddEmailForm(forms.Form):
  85. error_css_class = "has-error"
  86. value = forms.EmailField(max_length=100)
  87. down = forms.BooleanField(required=False, initial=True)
  88. up = forms.BooleanField(required=False, initial=True)
  89. def clean(self):
  90. super().clean()
  91. down = self.cleaned_data.get("down")
  92. up = self.cleaned_data.get("up")
  93. if not down and not up:
  94. self.add_error("down", "Please select at least one.")
  95. class AddUrlForm(forms.Form):
  96. error_css_class = "has-error"
  97. value = forms.URLField(max_length=1000, validators=[WebhookValidator()])
  98. METHODS = ("GET", "POST", "PUT")
  99. class WebhookForm(forms.Form):
  100. error_css_class = "has-error"
  101. name = forms.CharField(max_length=100, required=False)
  102. method_down = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  103. body_down = forms.CharField(max_length=1000, required=False)
  104. headers_down = HeadersField(required=False)
  105. url_down = URLField(
  106. max_length=1000, required=False, validators=[WebhookValidator()]
  107. )
  108. method_up = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  109. body_up = forms.CharField(max_length=1000, required=False)
  110. headers_up = HeadersField(required=False)
  111. url_up = forms.URLField(
  112. max_length=1000, required=False, validators=[WebhookValidator()]
  113. )
  114. def clean(self):
  115. super().clean()
  116. url_down = self.cleaned_data.get("url_down")
  117. url_up = self.cleaned_data.get("url_up")
  118. if not url_down and not url_up:
  119. if not self.has_error("url_down"):
  120. self.add_error("url_down", "Enter a valid URL.")
  121. def get_value(self):
  122. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  123. class AddShellForm(forms.Form):
  124. error_css_class = "has-error"
  125. cmd_down = forms.CharField(max_length=1000, required=False)
  126. cmd_up = forms.CharField(max_length=1000, required=False)
  127. def get_value(self):
  128. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  129. phone_validator = RegexValidator(
  130. regex="^\+\d{5,15}$", message="Invalid phone number format."
  131. )
  132. class AddSmsForm(forms.Form):
  133. error_css_class = "has-error"
  134. label = forms.CharField(max_length=100, required=False)
  135. value = forms.CharField(max_length=16, validators=[phone_validator])
  136. down = forms.BooleanField(required=False, initial=True)
  137. up = forms.BooleanField(required=False, initial=True)
  138. class ChannelNameForm(forms.Form):
  139. name = forms.CharField(max_length=100, required=False)
  140. class AddMatrixForm(forms.Form):
  141. error_css_class = "has-error"
  142. alias = forms.CharField(max_length=100)
  143. def clean_alias(self):
  144. v = self.cleaned_data["alias"]
  145. # validate it by trying to join
  146. url = settings.MATRIX_HOMESERVER
  147. url += "/_matrix/client/r0/join/%s?" % quote(v)
  148. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  149. doc = requests.post(url, {}).json()
  150. if "error" in doc:
  151. raise forms.ValidationError("Response from Matrix: %s" % doc["error"])
  152. self.cleaned_data["room_id"] = doc["room_id"]
  153. return v
  154. class AddAppriseForm(forms.Form):
  155. error_css_class = "has-error"
  156. url = forms.CharField(max_length=512)
  157. class AddPdForm(forms.Form):
  158. error_css_class = "has-error"
  159. value = forms.CharField(max_length=32)
  160. ZULIP_TARGETS = (("stream", "Stream"), ("private", "Private"))
  161. class AddZulipForm(forms.Form):
  162. error_css_class = "has-error"
  163. bot_email = forms.EmailField(max_length=100)
  164. api_key = forms.CharField(max_length=50)
  165. mtype = forms.ChoiceField(choices=ZULIP_TARGETS)
  166. to = forms.CharField(max_length=100)
  167. def get_value(self):
  168. return json.dumps(dict(self.cleaned_data), sort_keys=True)