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.

201 lines
5.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. class AddEmailForm(forms.Form):
  67. error_css_class = "has-error"
  68. value = forms.EmailField(max_length=100)
  69. down = forms.BooleanField(required=False, initial=True)
  70. up = forms.BooleanField(required=False, initial=True)
  71. def clean(self):
  72. super().clean()
  73. down = self.cleaned_data.get("down")
  74. up = self.cleaned_data.get("up")
  75. if not down and not up:
  76. self.add_error("down", "Please select at least one.")
  77. class AddUrlForm(forms.Form):
  78. error_css_class = "has-error"
  79. value = forms.URLField(max_length=1000, validators=[WebhookValidator()])
  80. METHODS = ("GET", "POST", "PUT")
  81. class AddWebhookForm(forms.Form):
  82. error_css_class = "has-error"
  83. method_down = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  84. body_down = forms.CharField(max_length=1000, required=False)
  85. headers_down = HeadersField(required=False)
  86. url_down = URLField(
  87. max_length=1000, required=False, validators=[WebhookValidator()]
  88. )
  89. method_up = forms.ChoiceField(initial="GET", choices=zip(METHODS, METHODS))
  90. body_up = forms.CharField(max_length=1000, required=False)
  91. headers_up = HeadersField(required=False)
  92. url_up = forms.URLField(
  93. max_length=1000, required=False, validators=[WebhookValidator()]
  94. )
  95. def clean(self):
  96. super().clean()
  97. url_down = self.cleaned_data.get("url_down")
  98. url_up = self.cleaned_data.get("url_up")
  99. if not url_down and not url_up:
  100. self.add_error("url_down", "Enter a valid URL.")
  101. def get_value(self):
  102. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  103. class AddShellForm(forms.Form):
  104. error_css_class = "has-error"
  105. cmd_down = forms.CharField(max_length=1000, required=False)
  106. cmd_up = forms.CharField(max_length=1000, required=False)
  107. def get_value(self):
  108. return json.dumps(dict(self.cleaned_data), sort_keys=True)
  109. phone_validator = RegexValidator(
  110. regex="^\+\d{5,15}$", message="Invalid phone number format."
  111. )
  112. class AddSmsForm(forms.Form):
  113. error_css_class = "has-error"
  114. label = forms.CharField(max_length=100, required=False)
  115. value = forms.CharField(max_length=16, validators=[phone_validator])
  116. down = forms.BooleanField(required=False, initial=True)
  117. up = forms.BooleanField(required=False, initial=True)
  118. class ChannelNameForm(forms.Form):
  119. name = forms.CharField(max_length=100, required=False)
  120. class AddMatrixForm(forms.Form):
  121. error_css_class = "has-error"
  122. alias = forms.CharField(max_length=100)
  123. def clean_alias(self):
  124. v = self.cleaned_data["alias"]
  125. # validate it by trying to join
  126. url = settings.MATRIX_HOMESERVER
  127. url += "/_matrix/client/r0/join/%s?" % quote(v)
  128. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  129. doc = requests.post(url, {}).json()
  130. if "error" in doc:
  131. raise forms.ValidationError("Response from Matrix: %s" % doc["error"])
  132. self.cleaned_data["room_id"] = doc["room_id"]
  133. return v
  134. class AddAppriseForm(forms.Form):
  135. error_css_class = "has-error"
  136. url = forms.CharField(max_length=512)
  137. class AddPdForm(forms.Form):
  138. error_css_class = "has-error"
  139. value = forms.CharField(max_length=32)