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.

292 lines
8.6 KiB

10 years ago
10 years ago
10 years ago
  1. from datetime import timedelta as td
  2. import json
  3. import re
  4. from urllib.parse import quote, urlencode
  5. from django import forms
  6. from django.forms import URLField
  7. from django.conf import settings
  8. from django.core.exceptions import ValidationError
  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. filter_by_subject = forms.ChoiceField(choices=(("no", "no"), ("yes", "yes")))
  50. subject = forms.CharField(required=False, max_length=100)
  51. subject_fail = forms.CharField(required=False, max_length=100)
  52. methods = forms.ChoiceField(required=False, choices=(("", "Any"), ("POST", "POST")))
  53. manual_resume = forms.BooleanField(required=False)
  54. def clean_subject(self):
  55. if self.cleaned_data["filter_by_subject"] == "yes":
  56. return self.cleaned_data["subject"]
  57. return ""
  58. def clean_subject_fail(self):
  59. if self.cleaned_data["filter_by_subject"] == "yes":
  60. return self.cleaned_data["subject_fail"]
  61. return ""
  62. class TimeoutForm(forms.Form):
  63. timeout = forms.IntegerField(min_value=60, max_value=2592000)
  64. grace = forms.IntegerField(min_value=60, max_value=2592000)
  65. def clean_timeout(self):
  66. return td(seconds=self.cleaned_data["timeout"])
  67. def clean_grace(self):
  68. return td(seconds=self.cleaned_data["grace"])
  69. class CronForm(forms.Form):
  70. schedule = forms.CharField(max_length=100, validators=[CronExpressionValidator()])
  71. tz = forms.CharField(max_length=36, validators=[TimezoneValidator()])
  72. grace = forms.IntegerField(min_value=1, max_value=43200)
  73. class AddOpsgenieForm(forms.Form):
  74. error_css_class = "has-error"
  75. region = forms.ChoiceField(initial="us", choices=(("us", "US"), ("eu", "EU")))
  76. key = forms.CharField(max_length=40)
  77. PRIO_CHOICES = [
  78. ("-2", "Lowest Priority"),
  79. ("-1", "Low Priority"),
  80. ("0", "Normal Priority"),
  81. ("1", "High Priority"),
  82. ("2", "Emergency Priority"),
  83. ]
  84. class AddPushoverForm(forms.Form):
  85. error_css_class = "has-error"
  86. pushover_user_key = forms.CharField()
  87. prio = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  88. prio_up = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  89. def get_value(self):
  90. key = self.cleaned_data["pushover_user_key"]
  91. prio = self.cleaned_data["prio"]
  92. prio_up = self.cleaned_data["prio_up"]
  93. return "%s|%s|%s" % (key, prio, prio_up)
  94. class AddEmailForm(forms.Form):
  95. error_css_class = "has-error"
  96. value = forms.EmailField(max_length=100)
  97. down = forms.BooleanField(required=False, initial=True)
  98. up = forms.BooleanField(required=False, initial=True)
  99. def clean(self):
  100. super().clean()
  101. down = self.cleaned_data.get("down")
  102. up = self.cleaned_data.get("up")
  103. if not down and not up:
  104. self.add_error("down", "Please select at least one.")
  105. class AddUrlForm(forms.Form):
  106. error_css_class = "has-error"
  107. value = forms.URLField(max_length=1000, validators=[WebhookValidator()])
  108. METHODS = ("GET", "POST", "PUT")
  109. class WebhookForm(forms.Form):
  110. error_css_class = "has-error"
  111. name = forms.CharField(max_length=100, required=False)
  112. method_down = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  113. body_down = forms.CharField(max_length=1000, required=False)
  114. headers_down = HeadersField(required=False)
  115. url_down = URLField(
  116. max_length=1000, required=False, validators=[WebhookValidator()]
  117. )
  118. method_up = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  119. body_up = forms.CharField(max_length=1000, required=False)
  120. headers_up = HeadersField(required=False)
  121. url_up = forms.URLField(
  122. max_length=1000, required=False, validators=[WebhookValidator()]
  123. )
  124. def clean(self):
  125. super().clean()
  126. url_down = self.cleaned_data.get("url_down")
  127. url_up = self.cleaned_data.get("url_up")
  128. if not url_down and not url_up:
  129. if not self.has_error("url_down"):
  130. self.add_error("url_down", "Enter a valid URL.")
  131. def get_value(self):
  132. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  133. class AddShellForm(forms.Form):
  134. error_css_class = "has-error"
  135. cmd_down = forms.CharField(max_length=1000, required=False)
  136. cmd_up = forms.CharField(max_length=1000, required=False)
  137. def get_value(self):
  138. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  139. class PhoneNumberForm(forms.Form):
  140. error_css_class = "has-error"
  141. label = forms.CharField(max_length=100, required=False)
  142. phone = forms.CharField()
  143. def clean_phone(self):
  144. v = self.cleaned_data["phone"]
  145. stripped = v.encode("ascii", "ignore").decode("ascii")
  146. stripped = stripped.replace(" ", "").replace("-", "")
  147. if not re.match(r"^\+\d{5,15}$", stripped):
  148. raise forms.ValidationError("Invalid phone number format.")
  149. return stripped
  150. def get_json(self):
  151. return json.dumps({"value": self.cleaned_data["phone"]})
  152. class PhoneUpDownForm(PhoneNumberForm):
  153. up = forms.BooleanField(required=False, initial=True)
  154. down = forms.BooleanField(required=False, initial=True)
  155. def get_json(self):
  156. return json.dumps(
  157. {
  158. "value": self.cleaned_data["phone"],
  159. "up": self.cleaned_data["up"],
  160. "down": self.cleaned_data["down"],
  161. }
  162. )
  163. class ChannelNameForm(forms.Form):
  164. name = forms.CharField(max_length=100, required=False)
  165. class AddMatrixForm(forms.Form):
  166. error_css_class = "has-error"
  167. alias = forms.CharField(max_length=100)
  168. def clean_alias(self):
  169. v = self.cleaned_data["alias"]
  170. # validate it by trying to join
  171. url = settings.MATRIX_HOMESERVER
  172. url += "/_matrix/client/r0/join/%s?" % quote(v)
  173. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  174. r = requests.post(url, {})
  175. if r.status_code == 429:
  176. raise forms.ValidationError(
  177. "Matrix server returned status code 429 (Too Many Requests), "
  178. "please try again later."
  179. )
  180. doc = r.json()
  181. if "error" in doc:
  182. raise forms.ValidationError("Response from Matrix: %s" % doc["error"])
  183. self.cleaned_data["room_id"] = doc["room_id"]
  184. return v
  185. class AddAppriseForm(forms.Form):
  186. error_css_class = "has-error"
  187. url = forms.CharField(max_length=512)
  188. class AddPdForm(forms.Form):
  189. error_css_class = "has-error"
  190. value = forms.CharField(max_length=32)
  191. ZULIP_TARGETS = (("stream", "Stream"), ("private", "Private"))
  192. class AddZulipForm(forms.Form):
  193. error_css_class = "has-error"
  194. bot_email = forms.EmailField(max_length=100)
  195. api_key = forms.CharField(max_length=50)
  196. site = forms.URLField(max_length=100, validators=[WebhookValidator()])
  197. mtype = forms.ChoiceField(choices=ZULIP_TARGETS)
  198. to = forms.CharField(max_length=100)
  199. def get_value(self):
  200. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  201. class AddTrelloForm(forms.Form):
  202. token = forms.RegexField(regex=r"^[0-9a-fA-F]{64}$")
  203. board_name = forms.CharField(max_length=100)
  204. list_name = forms.CharField(max_length=100)
  205. list_id = forms.RegexField(regex=r"^[0-9a-fA-F]{16,32}$")
  206. def get_value(self):
  207. return json.dumps(dict(self.cleaned_data), sort_keys=True)