Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

914 рядки
26 KiB

  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 enum
  16. import logging
  17. from http import HTTPStatus
  18. from typing import (
  19. TYPE_CHECKING,
  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, StrCollection
  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[StrCollection] = 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[StrCollection] = None,
  287. encoding: str = "ascii",
  288. ) -> str:
  289. ...
  290. @overload
  291. def parse_string(
  292. request: Request,
  293. name: str,
  294. *,
  295. default: Optional[str] = None,
  296. required: bool = False,
  297. allowed_values: Optional[StrCollection] = None,
  298. encoding: str = "ascii",
  299. ) -> Optional[str]:
  300. ...
  301. def parse_string(
  302. request: Request,
  303. name: str,
  304. default: Optional[str] = None,
  305. required: bool = False,
  306. allowed_values: Optional[StrCollection] = None,
  307. encoding: str = "ascii",
  308. ) -> Optional[str]:
  309. """
  310. Parse a string parameter from the request query string.
  311. If encoding is not None, the content of the query param will be
  312. decoded to Unicode using the encoding, otherwise it will be encoded
  313. Args:
  314. request: the twisted HTTP request.
  315. name: the name of the query parameter.
  316. default: value to use if the parameter is absent, defaults to None.
  317. required: whether to raise a 400 SynapseError if the
  318. parameter is absent, defaults to False.
  319. allowed_values: List of allowed values for the
  320. string, or None if any value is allowed, defaults to None. Must be
  321. the same type as name, if given.
  322. encoding: The encoding to decode the string content with.
  323. Returns:
  324. A string value or the default.
  325. Raises:
  326. SynapseError if the parameter is absent and required, or if the
  327. parameter is present, must be one of a list of allowed values and
  328. is not one of those allowed values.
  329. """
  330. args: Mapping[bytes, Sequence[bytes]] = request.args # type: ignore
  331. return parse_string_from_args(
  332. args,
  333. name,
  334. default,
  335. required=required,
  336. allowed_values=allowed_values,
  337. encoding=encoding,
  338. )
  339. EnumT = TypeVar("EnumT", bound=enum.Enum)
  340. @overload
  341. def parse_enum(
  342. request: Request,
  343. name: str,
  344. E: Type[EnumT],
  345. default: EnumT,
  346. ) -> EnumT:
  347. ...
  348. @overload
  349. def parse_enum(
  350. request: Request,
  351. name: str,
  352. E: Type[EnumT],
  353. *,
  354. required: Literal[True],
  355. ) -> EnumT:
  356. ...
  357. def parse_enum(
  358. request: Request,
  359. name: str,
  360. E: Type[EnumT],
  361. default: Optional[EnumT] = None,
  362. required: bool = False,
  363. ) -> Optional[EnumT]:
  364. """
  365. Parse an enum parameter from the request query string.
  366. Note that the enum *must only have string values*.
  367. Args:
  368. request: the twisted HTTP request.
  369. name: the name of the query parameter.
  370. E: the enum which represents valid values
  371. default: enum value to use if the parameter is absent, defaults to None.
  372. required: whether to raise a 400 SynapseError if the
  373. parameter is absent, defaults to False.
  374. Returns:
  375. An enum value.
  376. Raises:
  377. SynapseError if the parameter is absent and required, or if the
  378. parameter is present, must be one of a list of allowed values and
  379. is not one of those allowed values.
  380. """
  381. # Assert the enum values are strings.
  382. assert all(
  383. isinstance(e.value, str) for e in E
  384. ), "parse_enum only works with string values"
  385. str_value = parse_string(
  386. request,
  387. name,
  388. default=default.value if default is not None else None,
  389. required=required,
  390. allowed_values=[e.value for e in E],
  391. )
  392. if str_value is None:
  393. return None
  394. return E(str_value)
  395. def _parse_string_value(
  396. value: bytes,
  397. allowed_values: Optional[StrCollection],
  398. name: str,
  399. encoding: str,
  400. ) -> str:
  401. try:
  402. value_str = value.decode(encoding)
  403. except ValueError:
  404. raise SynapseError(
  405. HTTPStatus.BAD_REQUEST, "Query parameter %r must be %s" % (name, encoding)
  406. )
  407. if allowed_values is not None and value_str not in allowed_values:
  408. message = "Query parameter %r must be one of [%s]" % (
  409. name,
  410. ", ".join(repr(v) for v in allowed_values),
  411. )
  412. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.INVALID_PARAM)
  413. else:
  414. return value_str
  415. @overload
  416. def parse_strings_from_args(
  417. args: Mapping[bytes, Sequence[bytes]],
  418. name: str,
  419. *,
  420. allowed_values: Optional[StrCollection] = None,
  421. encoding: str = "ascii",
  422. ) -> Optional[List[str]]:
  423. ...
  424. @overload
  425. def parse_strings_from_args(
  426. args: Mapping[bytes, Sequence[bytes]],
  427. name: str,
  428. default: List[str],
  429. *,
  430. allowed_values: Optional[StrCollection] = None,
  431. encoding: str = "ascii",
  432. ) -> List[str]:
  433. ...
  434. @overload
  435. def parse_strings_from_args(
  436. args: Mapping[bytes, Sequence[bytes]],
  437. name: str,
  438. *,
  439. required: Literal[True],
  440. allowed_values: Optional[StrCollection] = None,
  441. encoding: str = "ascii",
  442. ) -> List[str]:
  443. ...
  444. @overload
  445. def parse_strings_from_args(
  446. args: Mapping[bytes, Sequence[bytes]],
  447. name: str,
  448. default: Optional[List[str]] = None,
  449. *,
  450. required: bool = False,
  451. allowed_values: Optional[StrCollection] = None,
  452. encoding: str = "ascii",
  453. ) -> Optional[List[str]]:
  454. ...
  455. def parse_strings_from_args(
  456. args: Mapping[bytes, Sequence[bytes]],
  457. name: str,
  458. default: Optional[List[str]] = None,
  459. required: bool = False,
  460. allowed_values: Optional[StrCollection] = None,
  461. encoding: str = "ascii",
  462. ) -> Optional[List[str]]:
  463. """
  464. Parse a string parameter from the request query string list.
  465. The content of the query param will be decoded to Unicode using the encoding.
  466. Args:
  467. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  468. name: the name of the query parameter.
  469. default: value to use if the parameter is absent, defaults to None.
  470. required: whether to raise a 400 SynapseError if the
  471. parameter is absent, defaults to False.
  472. allowed_values: List of allowed values for the
  473. string, or None if any value is allowed, defaults to None.
  474. encoding: The encoding to decode the string content with.
  475. Returns:
  476. A string value or the default.
  477. Raises:
  478. SynapseError if the parameter is absent and required, or if the
  479. parameter is present, must be one of a list of allowed values and
  480. is not one of those allowed values.
  481. """
  482. name_bytes = name.encode("ascii")
  483. if name_bytes in args:
  484. values = args[name_bytes]
  485. return [
  486. _parse_string_value(value, allowed_values, name=name, encoding=encoding)
  487. for value in values
  488. ]
  489. else:
  490. if required:
  491. message = "Missing string query parameter %r" % (name,)
  492. raise SynapseError(
  493. HTTPStatus.BAD_REQUEST, message, errcode=Codes.MISSING_PARAM
  494. )
  495. return default
  496. @overload
  497. def parse_string_from_args(
  498. args: Mapping[bytes, Sequence[bytes]],
  499. name: str,
  500. default: Optional[str] = None,
  501. *,
  502. allowed_values: Optional[StrCollection] = None,
  503. encoding: str = "ascii",
  504. ) -> Optional[str]:
  505. ...
  506. @overload
  507. def parse_string_from_args(
  508. args: Mapping[bytes, Sequence[bytes]],
  509. name: str,
  510. default: Optional[str] = None,
  511. *,
  512. required: Literal[True],
  513. allowed_values: Optional[StrCollection] = None,
  514. encoding: str = "ascii",
  515. ) -> str:
  516. ...
  517. @overload
  518. def parse_string_from_args(
  519. args: Mapping[bytes, Sequence[bytes]],
  520. name: str,
  521. default: Optional[str] = None,
  522. required: bool = False,
  523. allowed_values: Optional[StrCollection] = None,
  524. encoding: str = "ascii",
  525. ) -> Optional[str]:
  526. ...
  527. def parse_string_from_args(
  528. args: Mapping[bytes, Sequence[bytes]],
  529. name: str,
  530. default: Optional[str] = None,
  531. required: bool = False,
  532. allowed_values: Optional[StrCollection] = None,
  533. encoding: str = "ascii",
  534. ) -> Optional[str]:
  535. """
  536. Parse the string parameter from the request query string list
  537. and return the first result.
  538. The content of the query param will be decoded to Unicode using the encoding.
  539. Args:
  540. args: A mapping of request args as bytes to a list of bytes (e.g. request.args).
  541. name: the name of the query parameter.
  542. default: value to use if the parameter is absent, defaults to None.
  543. required: whether to raise a 400 SynapseError if the
  544. parameter is absent, defaults to False.
  545. allowed_values: List of allowed values for the
  546. string, or None if any value is allowed, defaults to None. Must be
  547. the same type as name, if given.
  548. encoding: The encoding to decode the string content with.
  549. Returns:
  550. A string value or the default.
  551. Raises:
  552. SynapseError if the parameter is absent and required, or if the
  553. parameter is present, must be one of a list of allowed values and
  554. is not one of those allowed values.
  555. """
  556. strings = parse_strings_from_args(
  557. args,
  558. name,
  559. default=[default] if default is not None else None,
  560. required=required,
  561. allowed_values=allowed_values,
  562. encoding=encoding,
  563. )
  564. if strings is None:
  565. return None
  566. return strings[0]
  567. @overload
  568. def parse_json_value_from_request(request: Request) -> JsonDict:
  569. ...
  570. @overload
  571. def parse_json_value_from_request(
  572. request: Request, allow_empty_body: Literal[False]
  573. ) -> JsonDict:
  574. ...
  575. @overload
  576. def parse_json_value_from_request(
  577. request: Request, allow_empty_body: bool = False
  578. ) -> Optional[JsonDict]:
  579. ...
  580. def parse_json_value_from_request(
  581. request: Request, allow_empty_body: bool = False
  582. ) -> Optional[JsonDict]:
  583. """Parse a JSON value from the body of a twisted HTTP request.
  584. Args:
  585. request: the twisted HTTP request.
  586. allow_empty_body: if True, an empty body will be accepted and turned into None
  587. Returns:
  588. The JSON value.
  589. Raises:
  590. SynapseError if the request body couldn't be decoded as JSON.
  591. """
  592. try:
  593. content_bytes = request.content.read() # type: ignore
  594. except Exception:
  595. raise SynapseError(HTTPStatus.BAD_REQUEST, "Error reading JSON content.")
  596. if not content_bytes and allow_empty_body:
  597. return None
  598. try:
  599. content = json_decoder.decode(content_bytes.decode("utf-8"))
  600. except Exception as e:
  601. logger.warning(
  602. "Unable to parse JSON from %s %s response: %s (%s)",
  603. request.method.decode("ascii", errors="replace"),
  604. redact_uri(request.uri.decode("ascii", errors="replace")),
  605. e,
  606. content_bytes,
  607. )
  608. raise SynapseError(
  609. HTTPStatus.BAD_REQUEST, "Content not JSON.", errcode=Codes.NOT_JSON
  610. )
  611. return content
  612. def parse_json_object_from_request(
  613. request: Request, allow_empty_body: bool = False
  614. ) -> JsonDict:
  615. """Parse a JSON object from the body of a twisted HTTP request.
  616. Args:
  617. request: the twisted HTTP request.
  618. allow_empty_body: if True, an empty body will be accepted and turned into
  619. an empty dict.
  620. Raises:
  621. SynapseError if the request body couldn't be decoded as JSON or
  622. if it wasn't a JSON object.
  623. """
  624. content = parse_json_value_from_request(request, allow_empty_body=allow_empty_body)
  625. if allow_empty_body and content is None:
  626. return {}
  627. if not isinstance(content, dict):
  628. message = "Content must be a JSON object."
  629. raise SynapseError(HTTPStatus.BAD_REQUEST, message, errcode=Codes.BAD_JSON)
  630. return content
  631. Model = TypeVar("Model", bound=BaseModel)
  632. def validate_json_object(content: JsonDict, model_type: Type[Model]) -> Model:
  633. """Validate a deserialized JSON object using the given pydantic model.
  634. Raises:
  635. SynapseError if the request body couldn't be decoded as JSON or
  636. if it wasn't a JSON object.
  637. """
  638. try:
  639. instance = model_type.parse_obj(content)
  640. except ValidationError as e:
  641. # Choose a matrix error code. The catch-all is BAD_JSON, but we try to find a
  642. # more specific error if possible (which occasionally helps us to be spec-
  643. # compliant) This is a bit awkward because the spec's error codes aren't very
  644. # clear-cut: BAD_JSON arguably overlaps with MISSING_PARAM and INVALID_PARAM.
  645. errcode = Codes.BAD_JSON
  646. raw_errors = e.raw_errors
  647. if len(raw_errors) == 1 and isinstance(raw_errors[0], ErrorWrapper):
  648. raw_error = raw_errors[0].exc
  649. if isinstance(raw_error, MissingError):
  650. errcode = Codes.MISSING_PARAM
  651. elif isinstance(raw_error, PydanticValueError):
  652. errcode = Codes.INVALID_PARAM
  653. raise SynapseError(HTTPStatus.BAD_REQUEST, str(e), errcode=errcode)
  654. return instance
  655. def parse_and_validate_json_object_from_request(
  656. request: Request, model_type: Type[Model]
  657. ) -> Model:
  658. """Parse a JSON object from the body of a twisted HTTP request, then deserialise and
  659. validate using the given pydantic model.
  660. Raises:
  661. SynapseError if the request body couldn't be decoded as JSON or
  662. if it wasn't a JSON object.
  663. """
  664. content = parse_json_object_from_request(request, allow_empty_body=False)
  665. return validate_json_object(content, model_type)
  666. def assert_params_in_dict(body: JsonDict, required: StrCollection) -> None:
  667. absent = []
  668. for k in required:
  669. if k not in body:
  670. absent.append(k)
  671. if len(absent) > 0:
  672. raise SynapseError(
  673. HTTPStatus.BAD_REQUEST, "Missing params: %r" % absent, Codes.MISSING_PARAM
  674. )
  675. class RestServlet:
  676. """A Synapse REST Servlet.
  677. An implementing class can either provide its own custom 'register' method,
  678. or use the automatic pattern handling provided by the base class.
  679. To use this latter, the implementing class instead provides a `PATTERN`
  680. class attribute containing a pre-compiled regular expression. The automatic
  681. register method will then use this method to register any of the following
  682. instance methods associated with the corresponding HTTP method:
  683. on_GET
  684. on_PUT
  685. on_POST
  686. on_DELETE
  687. Automatically handles turning CodeMessageExceptions thrown by these methods
  688. into the appropriate HTTP response.
  689. """
  690. def register(self, http_server: HttpServer) -> None:
  691. """Register this servlet with the given HTTP server."""
  692. patterns = getattr(self, "PATTERNS", None)
  693. if patterns:
  694. for method in ("GET", "PUT", "POST", "DELETE"):
  695. if hasattr(self, "on_%s" % (method,)):
  696. servlet_classname = self.__class__.__name__
  697. method_handler = getattr(self, "on_%s" % (method,))
  698. http_server.register_paths(
  699. method, patterns, method_handler, servlet_classname
  700. )
  701. else:
  702. raise NotImplementedError("RestServlet must register something.")
  703. class ResolveRoomIdMixin:
  704. def __init__(self, hs: "HomeServer"):
  705. self.room_member_handler = hs.get_room_member_handler()
  706. async def resolve_room_id(
  707. self, room_identifier: str, remote_room_hosts: Optional[List[str]] = None
  708. ) -> Tuple[str, Optional[List[str]]]:
  709. """
  710. Resolve a room identifier to a room ID, if necessary.
  711. This also performanes checks to ensure the room ID is of the proper form.
  712. Args:
  713. room_identifier: The room ID or alias.
  714. remote_room_hosts: The potential remote room hosts to use.
  715. Returns:
  716. The resolved room ID.
  717. Raises:
  718. SynapseError if the room ID is of the wrong form.
  719. """
  720. if RoomID.is_valid(room_identifier):
  721. resolved_room_id = room_identifier
  722. elif RoomAlias.is_valid(room_identifier):
  723. room_alias = RoomAlias.from_string(room_identifier)
  724. (
  725. room_id,
  726. remote_room_hosts,
  727. ) = await self.room_member_handler.lookup_room_alias(room_alias)
  728. resolved_room_id = room_id.to_string()
  729. else:
  730. raise SynapseError(
  731. HTTPStatus.BAD_REQUEST,
  732. "%s was not legal room ID or room alias" % (room_identifier,),
  733. )
  734. if not resolved_room_id:
  735. raise SynapseError(
  736. HTTPStatus.BAD_REQUEST,
  737. "Unknown room ID or room alias %s" % room_identifier,
  738. )
  739. return resolved_room_id, remote_room_hosts