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.
 
 
 
 
 
 

246 lines
9.6 KiB

  1. # Copyright 2014, 2015 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. import logging
  15. import os
  16. from typing import Any, Dict, List, Tuple
  17. from urllib.request import getproxies_environment # type: ignore
  18. import attr
  19. from synapse.config.server import generate_ip_set
  20. from synapse.types import JsonDict
  21. from synapse.util.check_dependencies import DependencyException, check_requirements
  22. from synapse.util.module_loader import load_module
  23. from ._base import Config, ConfigError
  24. logger = logging.getLogger(__name__)
  25. DEFAULT_THUMBNAIL_SIZES = [
  26. {"width": 32, "height": 32, "method": "crop"},
  27. {"width": 96, "height": 96, "method": "crop"},
  28. {"width": 320, "height": 240, "method": "scale"},
  29. {"width": 640, "height": 480, "method": "scale"},
  30. {"width": 800, "height": 600, "method": "scale"},
  31. ]
  32. THUMBNAIL_SIZE_YAML = """\
  33. # - width: %(width)i
  34. # height: %(height)i
  35. # method: %(method)s
  36. """
  37. HTTP_PROXY_SET_WARNING = """\
  38. The Synapse config url_preview_ip_range_blacklist will be ignored as an HTTP(s) proxy is configured."""
  39. @attr.s(frozen=True, slots=True, auto_attribs=True)
  40. class ThumbnailRequirement:
  41. width: int
  42. height: int
  43. method: str
  44. media_type: str
  45. @attr.s(frozen=True, slots=True, auto_attribs=True)
  46. class MediaStorageProviderConfig:
  47. store_local: bool # Whether to store newly uploaded local files
  48. store_remote: bool # Whether to store newly downloaded remote files
  49. store_synchronous: bool # Whether to wait for successful storage for local uploads
  50. def parse_thumbnail_requirements(
  51. thumbnail_sizes: List[JsonDict],
  52. ) -> Dict[str, Tuple[ThumbnailRequirement, ...]]:
  53. """Takes a list of dictionaries with "width", "height", and "method" keys
  54. and creates a map from image media types to the thumbnail size, thumbnailing
  55. method, and thumbnail media type to precalculate
  56. Args:
  57. thumbnail_sizes: List of dicts with "width", "height", and "method" keys
  58. Returns:
  59. Dictionary mapping from media type string to list of ThumbnailRequirement.
  60. """
  61. requirements: Dict[str, List[ThumbnailRequirement]] = {}
  62. for size in thumbnail_sizes:
  63. width = size["width"]
  64. height = size["height"]
  65. method = size["method"]
  66. jpeg_thumbnail = ThumbnailRequirement(width, height, method, "image/jpeg")
  67. png_thumbnail = ThumbnailRequirement(width, height, method, "image/png")
  68. requirements.setdefault("image/jpeg", []).append(jpeg_thumbnail)
  69. requirements.setdefault("image/jpg", []).append(jpeg_thumbnail)
  70. requirements.setdefault("image/webp", []).append(jpeg_thumbnail)
  71. requirements.setdefault("image/gif", []).append(png_thumbnail)
  72. requirements.setdefault("image/png", []).append(png_thumbnail)
  73. return {
  74. media_type: tuple(thumbnails) for media_type, thumbnails in requirements.items()
  75. }
  76. class ContentRepositoryConfig(Config):
  77. section = "media"
  78. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  79. # Only enable the media repo if either the media repo is enabled or the
  80. # current worker app is the media repo.
  81. if (
  82. self.root.server.enable_media_repo is False
  83. and config.get("worker_app") != "synapse.app.media_repository"
  84. ):
  85. self.can_load_media_repo = False
  86. return
  87. else:
  88. self.can_load_media_repo = True
  89. # Whether this instance should be the one to run the background jobs to
  90. # e.g clean up old URL previews.
  91. self.media_instance_running_background_jobs = config.get(
  92. "media_instance_running_background_jobs",
  93. )
  94. self.max_upload_size = self.parse_size(config.get("max_upload_size", "50M"))
  95. self.max_image_pixels = self.parse_size(config.get("max_image_pixels", "32M"))
  96. self.max_spider_size = self.parse_size(config.get("max_spider_size", "10M"))
  97. self.media_store_path = self.ensure_directory(
  98. config.get("media_store_path", "media_store")
  99. )
  100. backup_media_store_path = config.get("backup_media_store_path")
  101. synchronous_backup_media_store = config.get(
  102. "synchronous_backup_media_store", False
  103. )
  104. storage_providers = config.get("media_storage_providers", [])
  105. if backup_media_store_path:
  106. if storage_providers:
  107. raise ConfigError(
  108. "Cannot use both 'backup_media_store_path' and 'storage_providers'"
  109. )
  110. storage_providers = [
  111. {
  112. "module": "file_system",
  113. "store_local": True,
  114. "store_synchronous": synchronous_backup_media_store,
  115. "store_remote": True,
  116. "config": {"directory": backup_media_store_path},
  117. }
  118. ]
  119. # This is a list of config that can be used to create the storage
  120. # providers. The entries are tuples of (Class, class_config,
  121. # MediaStorageProviderConfig), where Class is the class of the provider,
  122. # the class_config the config to pass to it, and
  123. # MediaStorageProviderConfig are options for StorageProviderWrapper.
  124. #
  125. # We don't create the storage providers here as not all workers need
  126. # them to be started.
  127. self.media_storage_providers: List[tuple] = []
  128. for i, provider_config in enumerate(storage_providers):
  129. # We special case the module "file_system" so as not to need to
  130. # expose FileStorageProviderBackend
  131. if provider_config["module"] == "file_system":
  132. provider_config["module"] = (
  133. "synapse.rest.media.v1.storage_provider"
  134. ".FileStorageProviderBackend"
  135. )
  136. provider_class, parsed_config = load_module(
  137. provider_config, ("media_storage_providers", "<item %i>" % i)
  138. )
  139. wrapper_config = MediaStorageProviderConfig(
  140. provider_config.get("store_local", False),
  141. provider_config.get("store_remote", False),
  142. provider_config.get("store_synchronous", False),
  143. )
  144. self.media_storage_providers.append(
  145. (provider_class, parsed_config, wrapper_config)
  146. )
  147. self.dynamic_thumbnails = config.get("dynamic_thumbnails", False)
  148. self.thumbnail_requirements = parse_thumbnail_requirements(
  149. config.get("thumbnail_sizes", DEFAULT_THUMBNAIL_SIZES)
  150. )
  151. self.url_preview_enabled = config.get("url_preview_enabled", False)
  152. if self.url_preview_enabled:
  153. try:
  154. check_requirements("url_preview")
  155. except DependencyException as e:
  156. raise ConfigError(
  157. e.message # noqa: B306, DependencyException.message is a property
  158. )
  159. proxy_env = getproxies_environment()
  160. if "url_preview_ip_range_blacklist" not in config:
  161. if "http" not in proxy_env or "https" not in proxy_env:
  162. raise ConfigError(
  163. "For security, you must specify an explicit target IP address "
  164. "blacklist in url_preview_ip_range_blacklist for url previewing "
  165. "to work"
  166. )
  167. else:
  168. if "http" in proxy_env or "https" in proxy_env:
  169. logger.warning("".join(HTTP_PROXY_SET_WARNING))
  170. # we always blacklist '0.0.0.0' and '::', which are supposed to be
  171. # unroutable addresses.
  172. self.url_preview_ip_range_blacklist = generate_ip_set(
  173. config["url_preview_ip_range_blacklist"],
  174. ["0.0.0.0", "::"],
  175. config_path=("url_preview_ip_range_blacklist",),
  176. )
  177. self.url_preview_ip_range_whitelist = generate_ip_set(
  178. config.get("url_preview_ip_range_whitelist", ()),
  179. config_path=("url_preview_ip_range_whitelist",),
  180. )
  181. self.url_preview_url_blacklist = config.get("url_preview_url_blacklist", ())
  182. self.url_preview_accept_language = config.get(
  183. "url_preview_accept_language"
  184. ) or ["en"]
  185. media_retention = config.get("media_retention") or {}
  186. self.media_retention_local_media_lifetime_ms = None
  187. local_media_lifetime = media_retention.get("local_media_lifetime")
  188. if local_media_lifetime is not None:
  189. self.media_retention_local_media_lifetime_ms = self.parse_duration(
  190. local_media_lifetime
  191. )
  192. self.media_retention_remote_media_lifetime_ms = None
  193. remote_media_lifetime = media_retention.get("remote_media_lifetime")
  194. if remote_media_lifetime is not None:
  195. self.media_retention_remote_media_lifetime_ms = self.parse_duration(
  196. remote_media_lifetime
  197. )
  198. def generate_config_section(self, data_dir_path: str, **kwargs: Any) -> str:
  199. assert data_dir_path is not None
  200. media_store = os.path.join(data_dir_path, "media_store")
  201. return f"media_store_path: {media_store}"