validators.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. import functools
  9. from typing import Any, Optional, Union as TypeUnion
  10. from . import utils
  11. import grapheme
  12. import re
  13. class ValidationError(Exception):
  14. """
  15. Is being raised when config value passed can't be converted properly
  16. Must be raised with string, describing why value is incorrect
  17. It will be shown in .config, if user tries to set incorrect value
  18. """
  19. class Validator:
  20. """
  21. Class used as validator of config value
  22. :param validator: Sync function, which raises `ValidationError` if passed
  23. value is incorrect (with explanation) and returns converted
  24. value if it is semantically correct.
  25. ⚠️ If validator returns `None`, value will always be set to `None`
  26. :param doc: Docstrings for this validator as string, or dict in format:
  27. {
  28. "en": "docstring",
  29. "ru": "докстрингом",
  30. "ua": "докстрiнгом",
  31. "jp": "ヒント",
  32. }
  33. Use instrumental case with lowercase
  34. :param _internal_id: Do not pass anything here, or things will break
  35. """
  36. def __init__(
  37. self,
  38. validator: callable,
  39. doc: TypeUnion[str, dict] = None,
  40. _internal_id: int = None,
  41. ):
  42. self.validate = validator
  43. if isinstance(doc, str):
  44. doc = {"en": doc, "ru": doc}
  45. self.doc = doc
  46. self.internal_id = _internal_id
  47. def _Boolean(value: Any, /) -> bool:
  48. true_cases = ["True", "true", "1", 1, True]
  49. false_cases = ["False", "false", "0", 0, False]
  50. if value not in true_cases + false_cases:
  51. raise ValidationError("Passed value must be a boolean")
  52. return value in true_cases
  53. def Boolean() -> Validator:
  54. """
  55. Any logical value to be passed
  56. `1`, `"1"` etc. will be automatically converted to bool
  57. """
  58. return Validator(
  59. _Boolean,
  60. {"en": "boolean", "ru": "логическим значением"},
  61. _internal_id="Boolean",
  62. )
  63. def _Integer(
  64. value: Any,
  65. /,
  66. *,
  67. digits: int,
  68. minimum: int,
  69. maximum: int,
  70. ) -> TypeUnion[int, None]:
  71. try:
  72. value = int(str(value).strip())
  73. except ValueError:
  74. raise ValidationError(f"Passed value ({value}) must be a number")
  75. if minimum is not None and value < minimum:
  76. raise ValidationError(f"Passed value ({value}) is lower than minimum one")
  77. if maximum is not None and value > maximum:
  78. raise ValidationError(f"Passed value ({value}) is greater than maximum one")
  79. if digits is not None and len(str(value)) != digits:
  80. raise ValidationError(
  81. f"The length of passed value ({value}) is incorrect "
  82. f"(Must be exactly {digits} digits)"
  83. )
  84. return value
  85. def Integer(
  86. *,
  87. digits: Optional[int] = None,
  88. minimum: Optional[int] = None,
  89. maximum: Optional[int] = None,
  90. ) -> Validator:
  91. """
  92. Checks whether passed argument is an integer value
  93. :param digits: Digits quantity, which must be passed
  94. :param minimum: Minimal number to be passed
  95. :param maximum: Maximum number to be passed
  96. """
  97. _sign_en = "positive " if minimum is not None and minimum == 0 else ""
  98. _sign_ru = "положительным " if minimum is not None and minimum == 0 else ""
  99. _sign_en = "negative " if maximum is not None and maximum == 0 else _sign_en
  100. _sign_ru = "отрицательным " if maximum is not None and maximum == 0 else _sign_ru
  101. _digits_en = f" with exactly {digits} digits" if digits is not None else ""
  102. _digits_ru = f", в котором ровно {digits} цифр " if digits is not None else ""
  103. if minimum is not None and minimum != 0:
  104. if maximum is None and maximum != 0:
  105. doc = {
  106. "en": f"{_sign_en}integer greater than {minimum}{_digits_en}",
  107. "ru": f"{_sign_ru}целым числом больше {minimum}{_digits_ru}",
  108. }
  109. else:
  110. doc = {
  111. "en": f"{_sign_en}integer from {minimum} to {maximum}{_digits_en}",
  112. "ru": f"{_sign_ru}целым числом в промежутке от {minimum} до {maximum}{_digits_ru}",
  113. }
  114. else:
  115. if maximum is None and maximum != 0:
  116. doc = {
  117. "en": f"{_sign_en}integer{_digits_en}",
  118. "ru": f"{_sign_ru}целым числом{_digits_ru}",
  119. }
  120. else:
  121. doc = {
  122. "en": f"{_sign_en}integer less than {maximum}{_digits_en}",
  123. "ru": f"{_sign_ru}целым числом меньше {maximum}{_digits_ru}",
  124. }
  125. return Validator(
  126. functools.partial(
  127. _Integer,
  128. digits=digits,
  129. minimum=minimum,
  130. maximum=maximum,
  131. ),
  132. doc,
  133. _internal_id="Integer",
  134. )
  135. def _Choice(value: Any, /, *, possible_values: list) -> Any:
  136. if value not in possible_values:
  137. raise ValidationError(
  138. f"Passed value ({value}) is not one of the following: {'/'.join(list(map(str, possible_values)))}"
  139. )
  140. return value
  141. def Choice(possible_values: list, /) -> Validator:
  142. """
  143. Check whether entered value is in the allowed list
  144. :param possible_values: Allowed values to be passed to config param
  145. """
  146. return Validator(
  147. functools.partial(_Choice, possible_values=possible_values),
  148. {
  149. "en": f"one of the following: {'/'.join(list(map(str, possible_values)))}",
  150. "ru": f"одним из: {'/'.join(list(map(str, possible_values)))}",
  151. },
  152. _internal_id="Choice",
  153. )
  154. def _Series(
  155. value: Any,
  156. /,
  157. *,
  158. validator: Optional[Validator],
  159. min_len: Optional[int],
  160. max_len: Optional[int],
  161. fixed_len: Optional[int],
  162. ):
  163. if not isinstance(value, (list, tuple, set)):
  164. value = str(value).split(",")
  165. if isinstance(value, (tuple, set)):
  166. value = list(value)
  167. if min_len is not None and len(value) < min_len:
  168. raise ValidationError(
  169. f"Passed value ({value}) contains less than {min_len} items"
  170. )
  171. if max_len is not None and len(value) > max_len:
  172. raise ValidationError(
  173. f"Passed value ({value}) contains more than {max_len} items"
  174. )
  175. if fixed_len is not None and len(value) != fixed_len:
  176. raise ValidationError(
  177. f"Passed value ({value}) must contain exactly {fixed_len} items"
  178. )
  179. value = [item.strip() if isinstance(item, str) else item for item in value]
  180. if isinstance(validator, Validator):
  181. for i, item in enumerate(value):
  182. try:
  183. value[i] = validator.validate(item)
  184. except ValidationError:
  185. raise ValidationError(
  186. f"Passed value ({value}) contains invalid item ({str(item).strip()}), which must be {validator.doc['en']}"
  187. )
  188. value = list(filter(lambda x: x, value))
  189. return value
  190. def Series(
  191. validator: Optional[Validator] = None,
  192. min_len: Optional[int] = None,
  193. max_len: Optional[int] = None,
  194. fixed_len: Optional[int] = None,
  195. ) -> Validator:
  196. """
  197. Represents the series of value (simply `list`)
  198. :param separator: With which separator values must be separated
  199. :param validator: Internal validator for each sequence value
  200. :param min_len: Minimal number of series items to be passed
  201. :param max_len: Maximum number of series items to be passed
  202. :param fixed_len: Fixed number of series items to be passed
  203. """
  204. _each_en = f" (each must be {validator.doc['en']})" if validator is not None else ""
  205. _each_ru = (
  206. f" (каждое должно быть {validator.doc['ru']})" if validator is not None else ""
  207. )
  208. if fixed_len is not None:
  209. _len_en = f" (exactly {fixed_len} pcs.)"
  210. _len_ru = f" (ровно {fixed_len} шт.)"
  211. else:
  212. if min_len is not None:
  213. if max_len is not None:
  214. _len_en = f" (from {min_len} to {max_len} pcs.)"
  215. _len_ru = f" (от {min_len} до {max_len} шт.)"
  216. else:
  217. _len_en = f" (at least {min_len} pcs.)"
  218. _len_ru = f" (как минимум {min_len} шт.)"
  219. else:
  220. if max_len is not None:
  221. _len_en = f" (up to {max_len} pcs.)"
  222. _len_ru = f" (до {max_len} шт.)"
  223. else:
  224. _len_en = ""
  225. _len_ru = ""
  226. doc = {
  227. "en": f"series of values{_len_en}{_each_en}, separated with «,»",
  228. "ru": f"списком значений{_len_ru}{_each_ru}, разделенных «,»",
  229. }
  230. return Validator(
  231. functools.partial(
  232. _Series,
  233. validator=validator,
  234. min_len=min_len,
  235. max_len=max_len,
  236. fixed_len=fixed_len,
  237. ),
  238. doc,
  239. _internal_id="Series",
  240. )
  241. def _Link(value: Any, /) -> str:
  242. try:
  243. if not utils.check_url(value):
  244. raise Exception("Invalid URL")
  245. except Exception:
  246. raise ValidationError(f"Passed value ({value}) is not a valid URL")
  247. return value
  248. def Link() -> Validator:
  249. """Valid url must be specified"""
  250. return Validator(
  251. lambda value: _Link(value),
  252. {
  253. "en": "link",
  254. "ru": "ссылкой",
  255. },
  256. _internal_id="Link",
  257. )
  258. def _String(value: Any, /, *, length: int) -> str:
  259. if isinstance(length, int) and len(list(grapheme.graphemes(str(value)))) != length:
  260. raise ValidationError(f"Passed value ({value}) must be a length of {length}")
  261. return str(value)
  262. def String(length: Optional[int] = None) -> Validator:
  263. """
  264. Checks for length of passed value and automatically converts it to string
  265. :param length: Exact length of string
  266. """
  267. if length is not None:
  268. doc = {
  269. "en": f"string of length {length}",
  270. "ru": f"строкой из {length} символа(-ов)",
  271. }
  272. else:
  273. doc = {
  274. "en": "string",
  275. "ru": "строкой",
  276. }
  277. return Validator(
  278. functools.partial(_String, length=length),
  279. doc,
  280. _internal_id="String",
  281. )
  282. def _RegExp(value: Any, /, *, regex: str) -> str:
  283. if not re.match(regex, value):
  284. raise ValidationError(f"Passed value ({value}) must follow pattern {regex}")
  285. return value
  286. def RegExp(regex: str) -> Validator:
  287. """
  288. Checks if value matches the regex
  289. :param regex: Regex to match
  290. """
  291. try:
  292. re.compile(regex)
  293. except re.error as e:
  294. raise Exception(f"{regex} is not a valid regex") from e
  295. doc = {
  296. "en": f"string matching pattern «{regex}»",
  297. "ru": f"строкой, соответствующей шаблону «{regex}»",
  298. }
  299. return Validator(
  300. functools.partial(_RegExp, regex=regex),
  301. doc,
  302. _internal_id="RegExp",
  303. )
  304. def _Float(
  305. value: Any,
  306. /,
  307. *,
  308. minimum: Optional[float] = None,
  309. maximum: Optional[float] = None,
  310. ) -> TypeUnion[int, None]:
  311. try:
  312. value = float(str(value).strip().replace(",", "."))
  313. except ValueError:
  314. raise ValidationError(f"Passed value ({value}) must be a float")
  315. if minimum is not None and value < minimum:
  316. raise ValidationError(f"Passed value ({value}) is lower than minimum one")
  317. if maximum is not None and value > maximum:
  318. raise ValidationError(f"Passed value ({value}) is greater than maximum one")
  319. return value
  320. def Float(
  321. minimum: Optional[float] = None,
  322. maximum: Optional[float] = None,
  323. ) -> Validator:
  324. """
  325. Checks whether passed argument is a float value
  326. :param minimum: Minimal number to be passed
  327. :param maximum: Maximum number to be passed
  328. """
  329. _sign_en = "positive " if minimum is not None and minimum == 0 else ""
  330. _sign_ru = "положительным " if minimum is not None and minimum == 0 else ""
  331. _sign_en = "negative " if maximum is not None and maximum == 0 else _sign_en
  332. _sign_ru = "отрицательным " if maximum is not None and maximum == 0 else _sign_ru
  333. if minimum is not None and minimum != 0:
  334. if maximum is None and maximum != 0:
  335. doc = {
  336. "en": f"{_sign_en}float greater than {minimum}",
  337. "ru": f"{_sign_ru}дробным числом больше {minimum}",
  338. }
  339. else:
  340. doc = {
  341. "en": f"{_sign_en}float from {minimum} to {maximum}",
  342. "ru": f"{_sign_ru}дробным числом в промежутке от {minimum} до {maximum}",
  343. }
  344. else:
  345. if maximum is None and maximum != 0:
  346. doc = {
  347. "en": f"{_sign_en}float",
  348. "ru": f"{_sign_ru}дробным числом",
  349. }
  350. else:
  351. doc = {
  352. "en": f"{_sign_en}float less than {maximum}",
  353. "ru": f"{_sign_ru}дробным числом меньше {maximum}",
  354. }
  355. return Validator(
  356. functools.partial(
  357. _Float,
  358. minimum=minimum,
  359. maximum=maximum,
  360. ),
  361. doc,
  362. _internal_id="Float",
  363. )
  364. def _TelegramID(value: Any, /):
  365. e = ValidationError(f"Passed value ({value}) is not a valid telegram id")
  366. try:
  367. value = int(str(value).strip())
  368. except Exception:
  369. raise e
  370. if str(value).startswith("-100"):
  371. value = int(str(value)[4:])
  372. if value > 2**32 - 1 or value < 0:
  373. raise e
  374. return value
  375. def TelegramID() -> Validator:
  376. return Validator(
  377. _TelegramID,
  378. "Telegram ID",
  379. _internal_id="TelegramID",
  380. )
  381. def _Union(value: Any, /, *, validators: list):
  382. for validator in validators:
  383. try:
  384. return validator.validate(value)
  385. except ValidationError:
  386. pass
  387. raise ValidationError(f"Passed value ({value}) is not valid")
  388. def Union(*validators) -> Validator:
  389. doc = {
  390. "en": "one of the following:\n",
  391. "ru": "одним из следующего:\n",
  392. }
  393. def case(x: str) -> str:
  394. return x[0].upper() + x[1:]
  395. for validator in validators:
  396. doc["en"] += f"- {case(validator.doc['en'])}\n"
  397. doc["ru"] += f"- {case(validator.doc['ru'])}\n"
  398. doc["en"] = doc["en"].strip()
  399. doc["ru"] = doc["ru"].strip()
  400. return Validator(
  401. functools.partial(_Union, validators=validators),
  402. doc,
  403. _internal_id="Union",
  404. )
  405. def _NoneType(value: Any, /) -> None:
  406. if value not in {None, False, ""}:
  407. raise ValidationError(f"Passed value ({value}) is not None")
  408. return None
  409. def NoneType() -> Validator:
  410. return Validator(
  411. _NoneType,
  412. "`None`",
  413. _internal_id="NoneType",
  414. )
  415. def _Hidden(value: Any, /, *, validator: Validator) -> Any:
  416. return validator.validate(value)
  417. def Hidden(validator: Optional[Validator] = None) -> Validator:
  418. if not validator:
  419. validator = String()
  420. return Validator(
  421. functools.partial(_Hidden, validator=validator),
  422. validator.doc,
  423. _internal_id="Hidden",
  424. )