servlet.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ This module contains base REST classes for constructing REST servlets. """
  15. import logging
  16. from http import HTTPStatus
  17. from typing import (
  18. TYPE_CHECKING,
  19. Iterable,
  20. List,
  21. Mapping,
  22. Optional,
  23. Sequence,
  24. Tuple,
  25. Type,
  26. TypeVar,
  27. overload,
  28. )
  29. from pydantic import BaseModel, MissingError, PydanticValueError, ValidationError
  30. from pydantic.error_wrappers import ErrorWrapper
  31. from typing_extensions import Literal
  32. from twisted.web.server import Request
  33. from synapse.api.errors import Codes, SynapseError
  34. from synapse.http import redact_uri
  35. from synapse.http.server import HttpServer
  36. from synapse.types import JsonDict, RoomAlias, RoomID
  37. from synapse.util import json_decoder
  38. if TYPE_CHECKING:
  39. from synapse.server import HomeServer
  40. logger = logging.getLogger(__name__)
  41. @overload
  42. def parse_integer(request: Request, name: str, default: int) -> int:
  43. ...
  44. @overload
  45. def parse_integer(request: Request, name: str, *, required: Literal[True]) -> int:
  46. ...
  47. @overload
  48. def parse_integer(
  49. request: Request, name: str, default: Optional[int] = None, required: bool = False
  50. ) -> Optional[int]:
  51. ...
  52. def parse_integer(
  53. request: Request, name: str, default: Optional[int] = None, required: bool = False
  54. ) -> Optional[int]:
  55. """Parse an integer parameter from the request string
  56. Args:
  57. request: the twisted HTTP request.
  58. name: the name of the query parameter.
  59. default: value to use if the parameter is absent, defaults to None.
  60. required: whether to raise a 400 SynapseError if the parameter is absent,
  61. defaults to False.
  62. Returns:
  63. An int value or the default.
  64. Raises:
  65. SynapseError: if the parameter is absent and required, or if the
  66. parameter is present and not an integer.
  67. """
  68. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  69. return parse_integer_from_args(args, name, default, required)
  70. @overload
  71. def parse_integer_from_args(
  72. args: Mapping[bytes, Sequence[bytes]],
  73. name: str,
  74. default: Optional[int] = None,
  75. ) -> Optional[int]:
  76. ...
  77. @overload
  78. def parse_integer_from_args(
  79. args: Mapping[bytes, Sequence[bytes]],
  80. name: str,
  81. *,
  82. required: Literal[True],
  83. ) -> int:
  84. ...
  85. @overload
  86. def parse_integer_from_args(
  87. args: Mapping[bytes, Sequence[bytes]],
  88. name: str,
  89. default: Optional[int] = None,
  90. required: bool = False,
  91. ) -> Optional[int]:
  92. ...
  93. def parse_integer_from_args(
  94. args: Mapping[bytes, Sequence[bytes]],
  95. name: str,
  96. default: Optional[int] = None,
  97. required: bool = False,
  98. ) -> Optional[int]:
  99. """Parse an integer parameter from the request string
  100. Args:
  101. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  102. name: the name of the query parameter.
  103. default: value to use if the parameter is absent, defaults to None.
  104. required: whether to raise a 400 SynapseError if the parameter is absent,
  105. defaults to False.
  106. Returns:
  107. An int value or the default.
  108. Raises:
  109. SynapseError: if the parameter is absent and required, or if the
  110. parameter is present and not an integer.
  111. """
  112. name_bytes = name.encode("ascii")
  113. if name_bytes in args:
  114. try:
  115. return int(args[name_bytes][0])
  116. except Exception:
  117. message = "Query parameter %r must be an integer" % (name,)
  118. raise SynapseError(
  119. HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
  120. )
  121. else:
  122. if required:
  123. message = "Missing integer query parameter %r" % (name,)
  124. raise SynapseError(
  125. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  126. )
  127. else:
  128. return default
  129. @overload
  130. def parse_boolean(request: Request, name: str, default: bool) -> bool:
  131. ...
  132. @overload
  133. def parse_boolean(request: Request, name: str, *, required: Literal[True]) -> bool:
  134. ...
  135. @overload
  136. def parse_boolean(
  137. request: Request, name: str, default: Optional[bool] = None, required: bool = False
  138. ) -> Optional[bool]:
  139. ...
  140. def parse_boolean(
  141. request: Request, name: str, default: Optional[bool] = None, required: bool = False
  142. ) -> Optional[bool]:
  143. """Parse a boolean parameter from the request query string
  144. Args:
  145. request: the twisted HTTP request.
  146. name: the name of the query parameter.
  147. default: value to use if the parameter is absent, defaults to None.
  148. required: whether to raise a 400 SynapseError if the parameter is absent,
  149. defaults to False.
  150. Returns:
  151. A bool value or the default.
  152. Raises:
  153. SynapseError: if the parameter is absent and required, or if the
  154. parameter is present and not one of "true" or "false".
  155. """
  156. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  157. return parse_boolean_from_args(args, name, default, required)
  158. @overload
  159. def parse_boolean_from_args(
  160. args: Mapping[bytes, Sequence[bytes]],
  161. name: str,
  162. default: bool,
  163. ) -> bool:
  164. ...
  165. @overload
  166. def parse_boolean_from_args(
  167. args: Mapping[bytes, Sequence[bytes]],
  168. name: str,
  169. *,
  170. required: Literal[True],
  171. ) -> bool:
  172. ...
  173. @overload
  174. def parse_boolean_from_args(
  175. args: Mapping[bytes, Sequence[bytes]],
  176. name: str,
  177. default: Optional[bool] = None,
  178. required: bool = False,
  179. ) -> Optional[bool]:
  180. ...
  181. def parse_boolean_from_args(
  182. args: Mapping[bytes, Sequence[bytes]],
  183. name: str,
  184. default: Optional[bool] = None,
  185. required: bool = False,
  186. ) -> Optional[bool]:
  187. """Parse a boolean parameter from the request query string
  188. Args:
  189. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  190. name: the name of the query parameter.
  191. default: value to use if the parameter is absent, defaults to None.
  192. required: whether to raise a 400 SynapseError if the parameter is absent,
  193. defaults to False.
  194. Returns:
  195. A bool value or the default.
  196. Raises:
  197. SynapseError: if the parameter is absent and required, or if the
  198. parameter is present and not one of "true" or "false".
  199. """
  200. name_bytes = name.encode("ascii")
  201. if name_bytes in args:
  202. try:
  203. return {b"true": True, b"false": False}[args[name_bytes][0]]
  204. except Exception:
  205. message = (
  206. "Boolean query parameter %r must be one of ['true', 'false']"
  207. ) % (name,)
  208. raise SynapseError(
  209. HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM
  210. )
  211. else:
  212. if required:
  213. message = "Missing boolean query parameter %r" % (name,)
  214. raise SynapseError(
  215. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  216. )
  217. else:
  218. return default
  219. @overload
  220. def parse_bytes_from_args(
  221. args: Mapping[bytes, Sequence[bytes]],
  222. name: str,
  223. default: Optional[bytes] = None,
  224. ) -> Optional[bytes]:
  225. ...
  226. @overload
  227. def parse_bytes_from_args(
  228. args: Mapping[bytes, Sequence[bytes]],
  229. name: str,
  230. default: Literal[None] = None,
  231. *,
  232. required: Literal[True],
  233. ) -> bytes:
  234. ...
  235. @overload
  236. def parse_bytes_from_args(
  237. args: Mapping[bytes, Sequence[bytes]],
  238. name: str,
  239. default: Optional[bytes] = None,
  240. required: bool = False,
  241. ) -> Optional[bytes]:
  242. ...
  243. def parse_bytes_from_args(
  244. args: Mapping[bytes, Sequence[bytes]],
  245. name: str,
  246. default: Optional[bytes] = None,
  247. required: bool = False,
  248. ) -> Optional[bytes]:
  249. """
  250. Parse a string parameter as bytes from the request query string.
  251. Args:
  252. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  253. name: the name of the query parameter.
  254. default: value to use if the parameter is absent,
  255. defaults to None. Must be bytes if encoding is None.
  256. required: whether to raise a 400 SynapseError if the
  257. parameter is absent, defaults to False.
  258. Returns:
  259. Bytes or the default value.
  260. Raises:
  261. SynapseError if the parameter is absent and required.
  262. """
  263. name_bytes = name.encode("ascii")
  264. if name_bytes in args:
  265. return args[name_bytes][0]
  266. elif required:
  267. message = "Missing string query parameter %s" % (name,)
  268. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM)
  269. return default
  270. @overload
  271. def parse_string(
  272. request: Request,
  273. name: str,
  274. default: str,
  275. *,
  276. allowed_values: Optional[Iterable[str]] = None,
  277. encoding: str = "ascii",
  278. ) -> str:
  279. ...
  280. @overload
  281. def parse_string(
  282. request: Request,
  283. name: str,
  284. *,
  285. required: Literal[True],
  286. allowed_values: Optional[Iterable[str]] = None,
  287. encoding: str = "ascii",
  288. ) -> str:
  289. ...
  290. @overload
  291. def parse_string(
  292. request: Request,
  293. name: str,
  294. *,
  295. required: bool = False,
  296. allowed_values: Optional[Iterable[str]] = None,
  297. encoding: str = "ascii",
  298. ) -> Optional[str]:
  299. ...
  300. def parse_string(
  301. request: Request,
  302. name: str,
  303. default: Optional[str] = None,
  304. required: bool = False,
  305. allowed_values: Optional[Iterable[str]] = None,
  306. encoding: str = "ascii",
  307. ) -> Optional[str]:
  308. """
  309. Parse a string parameter from the request query string.
  310. If encoding is not None, the content of the query param will be
  311. decoded to Unicode using the encoding, otherwise it will be encoded
  312. Args:
  313. request: the twisted HTTP request.
  314. name: the name of the query parameter.
  315. default: value to use if the parameter is absent, defaults to None.
  316. required: whether to raise a 400 SynapseError if the
  317. parameter is absent, defaults to False.
  318. allowed_values: List of allowed values for the
  319. string, or None if any value is allowed, defaults to None. Must be
  320. the same type as name, if given.
  321. encoding: The encoding to decode the string content with.
  322. Returns:
  323. A string value or the default.
  324. Raises:
  325. SynapseError if the parameter is absent and required, or if the
  326. parameter is present, must be one of a list of allowed values and
  327. is not one of those allowed values.
  328. """
  329. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  330. return parse_string_from_args(
  331. args,
  332. name,
  333. default,
  334. required=required,
  335. allowed_values=allowed_values,
  336. encoding=encoding,
  337. )
  338. def _parse_string_value(
  339. value: bytes,
  340. allowed_values: Optional[Iterable[str]],
  341. name: str,
  342. encoding: str,
  343. ) -> str:
  344. try:
  345. value_str = value.decode(encoding)
  346. except ValueError:
  347. raise SynapseError(
  348. HTTPStatus.BAD_REQUEST, "Query parameter %r must be %s" % (name, encoding)
  349. )
  350. if allowed_values is not None and value_str not in allowed_values:
  351. message = "Query parameter %r must be one of [%s]" % (
  352. name,
  353. ", ".join(repr(v) for v in allowed_values),
  354. )
  355. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM)
  356. else:
  357. return value_str
  358. @overload
  359. def parse_strings_from_args(
  360. args: Mapping[bytes, Sequence[bytes]],
  361. name: str,
  362. *,
  363. allowed_values: Optional[Iterable[str]] = None,
  364. encoding: str = "ascii",
  365. ) -> Optional[List[str]]:
  366. ...
  367. @overload
  368. def parse_strings_from_args(
  369. args: Mapping[bytes, Sequence[bytes]],
  370. name: str,
  371. default: List[str],
  372. *,
  373. allowed_values: Optional[Iterable[str]] = None,
  374. encoding: str = "ascii",
  375. ) -> List[str]:
  376. ...
  377. @overload
  378. def parse_strings_from_args(
  379. args: Mapping[bytes, Sequence[bytes]],
  380. name: str,
  381. *,
  382. required: Literal[True],
  383. allowed_values: Optional[Iterable[str]] = None,
  384. encoding: str = "ascii",
  385. ) -> List[str]:
  386. ...
  387. @overload
  388. def parse_strings_from_args(
  389. args: Mapping[bytes, Sequence[bytes]],
  390. name: str,
  391. default: Optional[List[str]] = None,
  392. *,
  393. required: bool = False,
  394. allowed_values: Optional[Iterable[str]] = None,
  395. encoding: str = "ascii",
  396. ) -> Optional[List[str]]:
  397. ...
  398. def parse_strings_from_args(
  399. args: Mapping[bytes, Sequence[bytes]],
  400. name: str,
  401. default: Optional[List[str]] = None,
  402. required: bool = False,
  403. allowed_values: Optional[Iterable[str]] = None,
  404. encoding: str = "ascii",
  405. ) -> Optional[List[str]]:
  406. """
  407. Parse a string parameter from the request query string list.
  408. The content of the query param will be decoded to Unicode using the encoding.
  409. Args:
  410. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  411. name: the name of the query parameter.
  412. default: value to use if the parameter is absent, defaults to None.
  413. required: whether to raise a 400 SynapseError if the
  414. parameter is absent, defaults to False.
  415. allowed_values: List of allowed values for the
  416. string, or None if any value is allowed, defaults to None.
  417. encoding: The encoding to decode the string content with.
  418. Returns:
  419. A string value or the default.
  420. Raises:
  421. SynapseError if the parameter is absent and required, or if the
  422. parameter is present, must be one of a list of allowed values and
  423. is not one of those allowed values.
  424. """
  425. name_bytes = name.encode("ascii")
  426. if name_bytes in args:
  427. values = args[name_bytes]
  428. return [
  429. _parse_string_value(value, allowed_values, name=name, encoding=encoding)
  430. for value in values
  431. ]
  432. else:
  433. if required:
  434. message = "Missing string query parameter %r" % (name,)
  435. raise SynapseError(
  436. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  437. )
  438. return default
  439. @overload
  440. def parse_string_from_args(
  441. args: Mapping[bytes, Sequence[bytes]],
  442. name: str,
  443. default: Optional[str] = None,
  444. *,
  445. allowed_values: Optional[Iterable[str]] = None,
  446. encoding: str = "ascii",
  447. ) -> Optional[str]:
  448. ...
  449. @overload
  450. def parse_string_from_args(
  451. args: Mapping[bytes, Sequence[bytes]],
  452. name: str,
  453. default: Optional[str] = None,
  454. *,
  455. required: Literal[True],
  456. allowed_values: Optional[Iterable[str]] = None,
  457. encoding: str = "ascii",
  458. ) -> str:
  459. ...
  460. @overload
  461. def parse_string_from_args(
  462. args: Mapping[bytes, Sequence[bytes]],
  463. name: str,
  464. default: Optional[str] = None,
  465. required: bool = False,
  466. allowed_values: Optional[Iterable[str]] = None,
  467. encoding: str = "ascii",
  468. ) -> Optional[str]:
  469. ...
  470. def parse_string_from_args(
  471. args: Mapping[bytes, Sequence[bytes]],
  472. name: str,
  473. default: Optional[str] = None,
  474. required: bool = False,
  475. allowed_values: Optional[Iterable[str]] = None,
  476. encoding: str = "ascii",
  477. ) -> Optional[str]:
  478. """
  479. Parse the string parameter from the request query string list
  480. and return the first result.
  481. The content of the query param will be decoded to Unicode using the encoding.
  482. Args:
  483. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  484. name: the name of the query parameter.
  485. default: value to use if the parameter is absent, defaults to None.
  486. required: whether to raise a 400 SynapseError if the
  487. parameter is absent, defaults to False.
  488. allowed_values: List of allowed values for the
  489. string, or None if any value is allowed, defaults to None. Must be
  490. the same type as name, if given.
  491. encoding: The encoding to decode the string content with.
  492. Returns:
  493. A string value or the default.
  494. Raises:
  495. SynapseError if the parameter is absent and required, or if the
  496. parameter is present, must be one of a list of allowed values and
  497. is not one of those allowed values.
  498. """
  499. strings = parse_strings_from_args(
  500. args,
  501. name,
  502. default=[default] if default is not None else None,
  503. required=required,
  504. allowed_values=allowed_values,
  505. encoding=encoding,
  506. )
  507. if strings is None:
  508. return None
  509. return strings[0]
  510. @overload
  511. def parse_json_value_from_request(request: Request) -> JsonDict:
  512. ...
  513. @overload
  514. def parse_json_value_from_request(
  515. request: Request, allow_empty_body: Literal[False]
  516. ) -> JsonDict:
  517. ...
  518. @overload
  519. def parse_json_value_from_request(
  520. request: Request, allow_empty_body: bool = False
  521. ) -> Optional[JsonDict]:
  522. ...
  523. def parse_json_value_from_request(
  524. request: Request, allow_empty_body: bool = False
  525. ) -> Optional[JsonDict]:
  526. """Parse a JSON value from the body of a twisted HTTP request.
  527. Args:
  528. request: the twisted HTTP request.
  529. allow_empty_body: if True, an empty body will be accepted and turned into None
  530. Returns:
  531. The JSON value.
  532. Raises:
  533. SynapseError if the request body couldn't be decoded as JSON.
  534. """
  535. try:
  536. content_bytes = request.content.read() # type: ignore
  537. except Exception:
  538. raise SynapseError(HTTPStatus.BAD_REQUEST, "Error reading JSON content.")
  539. if not content_bytes and allow_empty_body:
  540. return None
  541. try:
  542. content = json_decoder.decode(content_bytes.decode("utf-8"))
  543. except Exception as e:
  544. logger.warning(
  545. "Unable to parse JSON from %s %s response: %s (%s)",
  546. request.method.decode("ascii", errors="replace"),
  547. redact_uri(request.uri.decode("ascii", errors="replace")),
  548. e,
  549. content_bytes,
  550. )
  551. raise SynapseError(
  552. HTTPStatus.BAD_REQUEST, "Content not JSON.", errcode=Codes.NOT_JSON
  553. )
  554. return content
  555. def parse_json_object_from_request(
  556. request: Request, allow_empty_body: bool = False
  557. ) -> JsonDict:
  558. """Parse a JSON object from the body of a twisted HTTP request.
  559. Args:
  560. request: the twisted HTTP request.
  561. allow_empty_body: if True, an empty body will be accepted and turned into
  562. an empty dict.
  563. Raises:
  564. SynapseError if the request body couldn't be decoded as JSON or
  565. if it wasn't a JSON object.
  566. """
  567. content = parse_json_value_from_request(request, allow_empty_body=allow_empty_body)
  568. if allow_empty_body and content is None:
  569. return {}
  570. if not isinstance(content, dict):
  571. message = "Content must be a JSON object."
  572. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.BAD_JSON)
  573. return content
  574. Model = TypeVar("Model", bound=BaseModel)
  575. def parse_and_validate_json_object_from_request(
  576. request: Request, model_type: Type[Model]
  577. ) -> Model:
  578. """Parse a JSON object from the body of a twisted HTTP request, then deserialise and
  579. validate using the given pydantic model.
  580. Raises:
  581. SynapseError if the request body couldn't be decoded as JSON or
  582. if it wasn't a JSON object.
  583. """
  584. content = parse_json_object_from_request(request, allow_empty_body=False)
  585. try:
  586. instance = model_type.parse_obj(content)
  587. except ValidationError as e:
  588. # Choose a matrix error code. The catch-all is BAD_JSON, but we try to find a
  589. # more specific error if possible (which occasionally helps us to be spec-
  590. # compliant) This is a bit awkward because the spec's error codes aren't very
  591. # clear-cut: BAD_JSON arguably overlaps with MISSING_PARAM and INVALID_PARAM.
  592. errcode = Codes.BAD_JSON
  593. raw_errors = e.raw_errors
  594. if len(raw_errors) == 1 and isinstance(raw_errors[0], ErrorWrapper):
  595. raw_error = raw_errors[0].exc
  596. if isinstance(raw_error, MissingError):
  597. errcode = Codes.MISSING_PARAM
  598. elif isinstance(raw_error, PydanticValueError):
  599. errcode = Codes.INVALID_PARAM
  600. raise SynapseError(HTTPStatus.BAD_REQUEST, str(e), errcode=errcode)
  601. return instance
  602. def assert_params_in_dict(body: JsonDict, required: Iterable[str]) -> None:
  603. absent = []
  604. for k in required:
  605. if k not in body:
  606. absent.append(k)
  607. if len(absent) > 0:
  608. raise SynapseError(
  609. HTTPStatus.BAD_REQUEST, "Missing params: %r" % absent, Codes.MISSING_PARAM
  610. )
  611. class RestServlet:
  612. """A Synapse REST Servlet.
  613. An implementing class can either provide its own custom 'register' method,
  614. or use the automatic pattern handling provided by the base class.
  615. To use this latter, the implementing class instead provides a `PATTERN`
  616. class attribute containing a pre-compiled regular expression. The automatic
  617. register method will then use this method to register any of the following
  618. instance methods associated with the corresponding HTTP method:
  619. on_GET
  620. on_PUT
  621. on_POST
  622. on_DELETE
  623. Automatically handles turning CodeMessageExceptions thrown by these methods
  624. into the appropriate HTTP response.
  625. """
  626. def register(self, http_server: HttpServer) -> None:
  627. """Register this servlet with the given HTTP server."""
  628. patterns = getattr(self, "PATTERNS", None)
  629. if patterns:
  630. for method in ("GET", "PUT", "POST", "DELETE"):
  631. if hasattr(self, "on_%s" % (method,)):
  632. servlet_classname = self.__class__.__name__
  633. method_handler = getattr(self, "on_%s" % (method,))
  634. http_server.register_paths(
  635. method, patterns, method_handler, servlet_classname
  636. )
  637. else:
  638. raise NotImplementedError("RestServlet must register something.")
  639. class ResolveRoomIdMixin:
  640. def __init__(self, hs: "HomeServer"):
  641. self.room_member_handler = hs.get_room_member_handler()
  642. async def resolve_room_id(
  643. self, room_identifier: str, remote_room_hosts: Optional[List[str]] = None
  644. ) -> Tuple[str, Optional[List[str]]]:
  645. """
  646. Resolve a room identifier to a room ID, if necessary.
  647. This also performanes checks to ensure the room ID is of the proper form.
  648. Args:
  649. room_identifier: The room ID or alias.
  650. remote_room_hosts: The potential remote room hosts to use.
  651. Returns:
  652. The resolved room ID.
  653. Raises:
  654. SynapseError if the room ID is of the wrong form.
  655. """
  656. if RoomID.is_valid(room_identifier):
  657. resolved_room_id = room_identifier
  658. elif RoomAlias.is_valid(room_identifier):
  659. room_alias = RoomAlias.from_string(room_identifier)
  660. (
  661. room_id,
  662. remote_room_hosts,
  663. ) = await self.room_member_handler.lookup_room_alias(room_alias)
  664. resolved_room_id = room_id.to_string()
  665. else:
  666. raise SynapseError(
  667. HTTPStatus.BAD_REQUEST,
  668. "%s was not legal room ID or room alias" % (room_identifier,),
  669. )
  670. if not resolved_room_id:
  671. raise SynapseError(
  672. HTTPStatus.BAD_REQUEST,
  673. "Unknown room ID or room alias %s" % room_identifier,
  674. )
  675. return resolved_room_id, remote_room_hosts