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.

237 lines
6.8 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(max_length=100)
  50. methods = forms.ChoiceField(required=False, choices=(("", "Any"), ("POST", "POST")))
  51. class TimeoutForm(forms.Form):
  52. timeout = forms.IntegerField(min_value=60, max_value=2592000)
  53. grace = forms.IntegerField(min_value=60, max_value=2592000)
  54. def clean_timeout(self):
  55. return td(seconds=self.cleaned_data["timeout"])
  56. def clean_grace(self):
  57. return td(seconds=self.cleaned_data["grace"])
  58. class CronForm(forms.Form):
  59. schedule = forms.CharField(max_length=100, validators=[CronExpressionValidator()])
  60. tz = forms.CharField(max_length=36, validators=[TimezoneValidator()])
  61. grace = forms.IntegerField(min_value=1, max_value=43200)
  62. class AddOpsGenieForm(forms.Form):
  63. error_css_class = "has-error"
  64. region = forms.ChoiceField(initial="us", choices=(("us", "US"), ("eu", "EU")))
  65. key = forms.CharField(max_length=40)
  66. PRIO_CHOICES = [
  67. ("-2", "Lowest Priority"),
  68. ("-1", "Low Priority"),
  69. ("0", "Normal Priority"),
  70. ("1", "High Priority"),
  71. ("2", "Emergency Priority"),
  72. ]
  73. class AddPushoverForm(forms.Form):
  74. error_css_class = "has-error"
  75. pushover_user_key = forms.CharField()
  76. prio = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  77. prio_up = forms.ChoiceField(initial="0", choices=PRIO_CHOICES)
  78. def get_value(self):
  79. key = self.cleaned_data["pushover_user_key"]
  80. prio = self.cleaned_data["prio"]
  81. prio_up = self.cleaned_data["prio_up"]
  82. return "%s|%s|%s" % (key, prio, prio_up)
  83. class AddEmailForm(forms.Form):
  84. error_css_class = "has-error"
  85. value = forms.EmailField(max_length=100)
  86. down = forms.BooleanField(required=False, initial=True)
  87. up = forms.BooleanField(required=False, initial=True)
  88. def clean(self):
  89. super().clean()
  90. down = self.cleaned_data.get("down")
  91. up = self.cleaned_data.get("up")
  92. if not down and not up:
  93. self.add_error("down", "Please select at least one.")
  94. class AddUrlForm(forms.Form):
  95. error_css_class = "has-error"
  96. value = forms.URLField(max_length=1000, validators=[WebhookValidator()])
  97. METHODS = ("GET", "POST", "PUT")
  98. class AddWebhookForm(forms.Form):
  99. error_css_class = "has-error"
  100. method_down = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  101. body_down = forms.CharField(max_length=1000, required=False)
  102. headers_down = HeadersField(required=False)
  103. url_down = URLField(
  104. max_length=1000, required=False, validators=[WebhookValidator()]
  105. )
  106. method_up = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  107. body_up = forms.CharField(max_length=1000, required=False)
  108. headers_up = HeadersField(required=False)
  109. url_up = forms.URLField(
  110. max_length=1000, required=False, validators=[WebhookValidator()]
  111. )
  112. def clean(self):
  113. super().clean()
  114. url_down = self.cleaned_data.get("url_down")
  115. url_up = self.cleaned_data.get("url_up")
  116. if not url_down and not url_up:
  117. self.add_error("url_down", "Enter a valid URL.")
  118. def get_value(self):
  119. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  120. class AddShellForm(forms.Form):
  121. error_css_class = "has-error"
  122. cmd_down = forms.CharField(max_length=1000, required=False)
  123. cmd_up = forms.CharField(max_length=1000, required=False)
  124. def get_value(self):
  125. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  126. phone_validator = RegexValidator(
  127. regex="^\+\d{5,15}$", message="Invalid phone number format."
  128. )
  129. class AddSmsForm(forms.Form):
  130. error_css_class = "has-error"
  131. label = forms.CharField(max_length=100, required=False)
  132. value = forms.CharField(max_length=16, validators=[phone_validator])
  133. down = forms.BooleanField(required=False, initial=True)
  134. up = forms.BooleanField(required=False, initial=True)
  135. class ChannelNameForm(forms.Form):
  136. name = forms.CharField(max_length=100, required=False)
  137. class AddMatrixForm(forms.Form):
  138. error_css_class = "has-error"
  139. alias = forms.CharField(max_length=100)
  140. def clean_alias(self):
  141. v = self.cleaned_data["alias"]
  142. # validate it by trying to join
  143. url = settings.MATRIX_HOMESERVER
  144. url += "/_matrix/client/r0/join/%s?" % quote(v)
  145. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  146. doc = requests.post(url, {}).json()
  147. if "error" in doc:
  148. raise forms.ValidationError("Response from Matrix: %s" % doc["error"])
  149. self.cleaned_data["room_id"] = doc["room_id"]
  150. return v
  151. class AddAppriseForm(forms.Form):
  152. error_css_class = "has-error"
  153. url = forms.CharField(max_length=512)
  154. class AddPdForm(forms.Form):
  155. error_css_class = "has-error"
  156. value = forms.CharField(max_length=32)
  157. ZULIP_TARGETS = (("stream", "Stream"), ("private", "Private"))
  158. class AddZulipForm(forms.Form):
  159. error_css_class = "has-error"
  160. bot_email = forms.EmailField(max_length=100)
  161. api_key = forms.CharField(max_length=50)
  162. mtype = forms.ChoiceField(choices=ZULIP_TARGETS)
  163. to = forms.CharField(max_length=100)
  164. def get_value(self):
  165. return json.dumps(dict(self.cleaned_data), sort_keys=True)