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.

266 lines
7.8 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 AddSmsForm(forms.Form):
  140. error_css_class = "has-error"
  141. label = forms.CharField(max_length=100, required=False)
  142. value = forms.CharField()
  143. down = forms.BooleanField(required=False, initial=True)
  144. up = forms.BooleanField(required=False, initial=True)
  145. def clean_value(self):
  146. v = self.cleaned_data["value"]
  147. stripped = v.encode("ascii", "ignore").decode("ascii")
  148. stripped = stripped.replace(" ", "").replace("-", "")
  149. if not re.match(r"^\+\d{5,15}$", stripped):
  150. raise forms.ValidationError("Invalid phone number format.")
  151. return stripped
  152. class ChannelNameForm(forms.Form):
  153. name = forms.CharField(max_length=100, required=False)
  154. class AddMatrixForm(forms.Form):
  155. error_css_class = "has-error"
  156. alias = forms.CharField(max_length=100)
  157. def clean_alias(self):
  158. v = self.cleaned_data["alias"]
  159. # validate it by trying to join
  160. url = settings.MATRIX_HOMESERVER
  161. url += "/_matrix/client/r0/join/%s?" % quote(v)
  162. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  163. r = requests.post(url, {})
  164. if r.status_code == 429:
  165. raise forms.ValidationError(
  166. "Matrix server returned status code 429 (Too Many Requests), "
  167. "please try again later."
  168. )
  169. doc = r.json()
  170. if "error" in doc:
  171. raise forms.ValidationError("Response from Matrix: %s" % doc["error"])
  172. self.cleaned_data["room_id"] = doc["room_id"]
  173. return v
  174. class AddAppriseForm(forms.Form):
  175. error_css_class = "has-error"
  176. url = forms.CharField(max_length=512)
  177. class AddPdForm(forms.Form):
  178. error_css_class = "has-error"
  179. value = forms.CharField(max_length=32)
  180. ZULIP_TARGETS = (("stream", "Stream"), ("private", "Private"))
  181. class AddZulipForm(forms.Form):
  182. error_css_class = "has-error"
  183. bot_email = forms.EmailField(max_length=100)
  184. api_key = forms.CharField(max_length=50)
  185. mtype = forms.ChoiceField(choices=ZULIP_TARGETS)
  186. to = forms.CharField(max_length=100)
  187. def get_value(self):
  188. return json.dumps(dict(self.cleaned_data), sort_keys=True)