consent_server_notices.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import Any
  17. from synapse.api.errors import SynapseError
  18. from synapse.api.urls import ConsentURIBuilder
  19. from synapse.config import ConfigError
  20. from synapse.types import get_localpart_from_id
  21. logger = logging.getLogger(__name__)
  22. class ConsentServerNotices:
  23. """Keeps track of whether we need to send users server_notices about
  24. privacy policy consent, and sends one if we do.
  25. """
  26. def __init__(self, hs):
  27. """
  28. Args:
  29. hs (synapse.server.HomeServer):
  30. """
  31. self._server_notices_manager = hs.get_server_notices_manager()
  32. self._store = hs.get_datastore()
  33. self._users_in_progress = set()
  34. self._current_consent_version = hs.config.user_consent_version
  35. self._server_notice_content = hs.config.user_consent_server_notice_content
  36. self._send_to_guests = hs.config.user_consent_server_notice_to_guests
  37. if self._server_notice_content is not None:
  38. if not self._server_notices_manager.is_enabled():
  39. raise ConfigError(
  40. "user_consent configuration requires server notices, but "
  41. "server notices are not enabled."
  42. )
  43. if "body" not in self._server_notice_content:
  44. raise ConfigError(
  45. "user_consent server_notice_consent must contain a 'body' key."
  46. )
  47. self._consent_uri_builder = ConsentURIBuilder(hs.config)
  48. async def maybe_send_server_notice_to_user(self, user_id: str) -> None:
  49. """Check if we need to send a notice to this user, and does so if so
  50. Args:
  51. user_id: user to check
  52. """
  53. if self._server_notice_content is None:
  54. # not enabled
  55. return
  56. # make sure we don't send two messages to the same user at once
  57. if user_id in self._users_in_progress:
  58. return
  59. self._users_in_progress.add(user_id)
  60. try:
  61. u = await self._store.get_user_by_id(user_id)
  62. if u["is_guest"] and not self._send_to_guests:
  63. # don't send to guests
  64. return
  65. if u["consent_version"] == self._current_consent_version:
  66. # user has already consented
  67. return
  68. if u["consent_server_notice_sent"] == self._current_consent_version:
  69. # we've already sent a notice to the user
  70. return
  71. # need to send a message.
  72. try:
  73. consent_uri = self._consent_uri_builder.build_user_consent_uri(
  74. get_localpart_from_id(user_id)
  75. )
  76. content = copy_with_str_subst(
  77. self._server_notice_content, {"consent_uri": consent_uri}
  78. )
  79. await self._server_notices_manager.send_notice(user_id, content)
  80. await self._store.user_set_consent_server_notice_sent(
  81. user_id, self._current_consent_version
  82. )
  83. except SynapseError as e:
  84. logger.error("Error sending server notice about user consent: %s", e)
  85. finally:
  86. self._users_in_progress.remove(user_id)
  87. def copy_with_str_subst(x: Any, substitutions: Any) -> Any:
  88. """Deep-copy a structure, carrying out string substitutions on any strings
  89. Args:
  90. x (object): structure to be copied
  91. substitutions (object): substitutions to be made - passed into the
  92. string '%' operator
  93. Returns:
  94. copy of x
  95. """
  96. if isinstance(x, str):
  97. return x % substitutions
  98. if isinstance(x, dict):
  99. return {k: copy_with_str_subst(v, substitutions) for (k, v) in x.items()}
  100. if isinstance(x, (list, tuple)):
  101. return [copy_with_str_subst(y, substitutions) for y in x]
  102. # assume it's uninterested and can be shallow-copied.
  103. return x