repository.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 OpenMarket 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 os
  16. from collections import namedtuple
  17. from typing import Dict, List
  18. from synapse.python_dependencies import DependencyException, check_requirements
  19. from synapse.util.module_loader import load_module
  20. from ._base import Config, ConfigError
  21. DEFAULT_THUMBNAIL_SIZES = [
  22. {"width": 32, "height": 32, "method": "crop"},
  23. {"width": 96, "height": 96, "method": "crop"},
  24. {"width": 320, "height": 240, "method": "scale"},
  25. {"width": 640, "height": 480, "method": "scale"},
  26. {"width": 800, "height": 600, "method": "scale"},
  27. ]
  28. THUMBNAIL_SIZE_YAML = """\
  29. # - width: %(width)i
  30. # height: %(height)i
  31. # method: %(method)s
  32. """
  33. ThumbnailRequirement = namedtuple(
  34. "ThumbnailRequirement", ["width", "height", "method", "media_type"]
  35. )
  36. MediaStorageProviderConfig = namedtuple(
  37. "MediaStorageProviderConfig",
  38. (
  39. "store_local", # Whether to store newly uploaded local files
  40. "store_remote", # Whether to store newly downloaded remote files
  41. "store_synchronous", # Whether to wait for successful storage for local uploads
  42. ),
  43. )
  44. def parse_thumbnail_requirements(thumbnail_sizes):
  45. """ Takes a list of dictionaries with "width", "height", and "method" keys
  46. and creates a map from image media types to the thumbnail size, thumbnailing
  47. method, and thumbnail media type to precalculate
  48. Args:
  49. thumbnail_sizes(list): List of dicts with "width", "height", and
  50. "method" keys
  51. Returns:
  52. Dictionary mapping from media type string to list of
  53. ThumbnailRequirement tuples.
  54. """
  55. requirements = {} # type: Dict[str, List]
  56. for size in thumbnail_sizes:
  57. width = size["width"]
  58. height = size["height"]
  59. method = size["method"]
  60. jpeg_thumbnail = ThumbnailRequirement(width, height, method, "image/jpeg")
  61. png_thumbnail = ThumbnailRequirement(width, height, method, "image/png")
  62. requirements.setdefault("image/jpeg", []).append(jpeg_thumbnail)
  63. requirements.setdefault("image/webp", []).append(jpeg_thumbnail)
  64. requirements.setdefault("image/gif", []).append(png_thumbnail)
  65. requirements.setdefault("image/png", []).append(png_thumbnail)
  66. return {
  67. media_type: tuple(thumbnails) for media_type, thumbnails in requirements.items()
  68. }
  69. class ContentRepositoryConfig(Config):
  70. section = "media"
  71. def read_config(self, config, **kwargs):
  72. # Only enable the media repo if either the media repo is enabled or the
  73. # current worker app is the media repo.
  74. if (
  75. self.enable_media_repo is False
  76. and config.get("worker_app") != "synapse.app.media_repository"
  77. ):
  78. self.can_load_media_repo = False
  79. return
  80. else:
  81. self.can_load_media_repo = True
  82. self.max_upload_size = self.parse_size(config.get("max_upload_size", "10M"))
  83. self.max_image_pixels = self.parse_size(config.get("max_image_pixels", "32M"))
  84. self.max_spider_size = self.parse_size(config.get("max_spider_size", "10M"))
  85. self.media_store_path = self.ensure_directory(
  86. config.get("media_store_path", "media_store")
  87. )
  88. backup_media_store_path = config.get("backup_media_store_path")
  89. synchronous_backup_media_store = config.get(
  90. "synchronous_backup_media_store", False
  91. )
  92. storage_providers = config.get("media_storage_providers", [])
  93. if backup_media_store_path:
  94. if storage_providers:
  95. raise ConfigError(
  96. "Cannot use both 'backup_media_store_path' and 'storage_providers'"
  97. )
  98. storage_providers = [
  99. {
  100. "module": "file_system",
  101. "store_local": True,
  102. "store_synchronous": synchronous_backup_media_store,
  103. "store_remote": True,
  104. "config": {"directory": backup_media_store_path},
  105. }
  106. ]
  107. # This is a list of config that can be used to create the storage
  108. # providers. The entries are tuples of (Class, class_config,
  109. # MediaStorageProviderConfig), where Class is the class of the provider,
  110. # the class_config the config to pass to it, and
  111. # MediaStorageProviderConfig are options for StorageProviderWrapper.
  112. #
  113. # We don't create the storage providers here as not all workers need
  114. # them to be started.
  115. self.media_storage_providers = [] # type: List[tuple]
  116. for provider_config in storage_providers:
  117. # We special case the module "file_system" so as not to need to
  118. # expose FileStorageProviderBackend
  119. if provider_config["module"] == "file_system":
  120. provider_config["module"] = (
  121. "synapse.rest.media.v1.storage_provider"
  122. ".FileStorageProviderBackend"
  123. )
  124. provider_class, parsed_config = load_module(provider_config)
  125. wrapper_config = MediaStorageProviderConfig(
  126. provider_config.get("store_local", False),
  127. provider_config.get("store_remote", False),
  128. provider_config.get("store_synchronous", False),
  129. )
  130. self.media_storage_providers.append(
  131. (provider_class, parsed_config, wrapper_config)
  132. )
  133. self.dynamic_thumbnails = config.get("dynamic_thumbnails", False)
  134. self.thumbnail_requirements = parse_thumbnail_requirements(
  135. config.get("thumbnail_sizes", DEFAULT_THUMBNAIL_SIZES)
  136. )
  137. self.url_preview_enabled = config.get("url_preview_enabled", False)
  138. if self.url_preview_enabled:
  139. try:
  140. check_requirements("url_preview")
  141. except DependencyException as e:
  142. raise ConfigError(e.message)
  143. if "url_preview_ip_range_blacklist" not in config:
  144. raise ConfigError(
  145. "For security, you must specify an explicit target IP address "
  146. "blacklist in url_preview_ip_range_blacklist for url previewing "
  147. "to work"
  148. )
  149. # netaddr is a dependency for url_preview
  150. from netaddr import IPSet
  151. self.url_preview_ip_range_blacklist = IPSet(
  152. config["url_preview_ip_range_blacklist"]
  153. )
  154. # we always blacklist '0.0.0.0' and '::', which are supposed to be
  155. # unroutable addresses.
  156. self.url_preview_ip_range_blacklist.update(["0.0.0.0", "::"])
  157. self.url_preview_ip_range_whitelist = IPSet(
  158. config.get("url_preview_ip_range_whitelist", ())
  159. )
  160. self.url_preview_url_blacklist = config.get("url_preview_url_blacklist", ())
  161. self.url_preview_accept_language = config.get(
  162. "url_preview_accept_language"
  163. ) or ["en"]
  164. def generate_config_section(self, data_dir_path, **kwargs):
  165. media_store = os.path.join(data_dir_path, "media_store")
  166. uploads_path = os.path.join(data_dir_path, "uploads")
  167. formatted_thumbnail_sizes = "".join(
  168. THUMBNAIL_SIZE_YAML % s for s in DEFAULT_THUMBNAIL_SIZES
  169. )
  170. # strip final NL
  171. formatted_thumbnail_sizes = formatted_thumbnail_sizes[:-1]
  172. return (
  173. r"""
  174. ## Media Store ##
  175. # Enable the media store service in the Synapse master. Uncomment the
  176. # following if you are using a separate media store worker.
  177. #
  178. #enable_media_repo: false
  179. # Directory where uploaded images and attachments are stored.
  180. #
  181. media_store_path: "%(media_store)s"
  182. # Media storage providers allow media to be stored in different
  183. # locations.
  184. #
  185. #media_storage_providers:
  186. # - module: file_system
  187. # # Whether to store newly uploaded local files
  188. # store_local: false
  189. # # Whether to store newly downloaded remote files
  190. # store_remote: false
  191. # # Whether to wait for successful storage for local uploads
  192. # store_synchronous: false
  193. # config:
  194. # directory: /mnt/some/other/directory
  195. # The largest allowed upload size in bytes
  196. #
  197. #max_upload_size: 10M
  198. # Maximum number of pixels that will be thumbnailed
  199. #
  200. #max_image_pixels: 32M
  201. # Whether to generate new thumbnails on the fly to precisely match
  202. # the resolution requested by the client. If true then whenever
  203. # a new resolution is requested by the client the server will
  204. # generate a new thumbnail. If false the server will pick a thumbnail
  205. # from a precalculated list.
  206. #
  207. #dynamic_thumbnails: false
  208. # List of thumbnails to precalculate when an image is uploaded.
  209. #
  210. #thumbnail_sizes:
  211. %(formatted_thumbnail_sizes)s
  212. # Is the preview URL API enabled?
  213. #
  214. # 'false' by default: uncomment the following to enable it (and specify a
  215. # url_preview_ip_range_blacklist blacklist).
  216. #
  217. #url_preview_enabled: true
  218. # List of IP address CIDR ranges that the URL preview spider is denied
  219. # from accessing. There are no defaults: you must explicitly
  220. # specify a list for URL previewing to work. You should specify any
  221. # internal services in your network that you do not want synapse to try
  222. # to connect to, otherwise anyone in any Matrix room could cause your
  223. # synapse to issue arbitrary GET requests to your internal services,
  224. # causing serious security issues.
  225. #
  226. # (0.0.0.0 and :: are always blacklisted, whether or not they are explicitly
  227. # listed here, since they correspond to unroutable addresses.)
  228. #
  229. # This must be specified if url_preview_enabled is set. It is recommended that
  230. # you uncomment the following list as a starting point.
  231. #
  232. #url_preview_ip_range_blacklist:
  233. # - '127.0.0.0/8'
  234. # - '10.0.0.0/8'
  235. # - '172.16.0.0/12'
  236. # - '192.168.0.0/16'
  237. # - '100.64.0.0/10'
  238. # - '169.254.0.0/16'
  239. # - '::1/128'
  240. # - 'fe80::/64'
  241. # - 'fc00::/7'
  242. # List of IP address CIDR ranges that the URL preview spider is allowed
  243. # to access even if they are specified in url_preview_ip_range_blacklist.
  244. # This is useful for specifying exceptions to wide-ranging blacklisted
  245. # target IP ranges - e.g. for enabling URL previews for a specific private
  246. # website only visible in your network.
  247. #
  248. #url_preview_ip_range_whitelist:
  249. # - '192.168.1.1'
  250. # Optional list of URL matches that the URL preview spider is
  251. # denied from accessing. You should use url_preview_ip_range_blacklist
  252. # in preference to this, otherwise someone could define a public DNS
  253. # entry that points to a private IP address and circumvent the blacklist.
  254. # This is more useful if you know there is an entire shape of URL that
  255. # you know that will never want synapse to try to spider.
  256. #
  257. # Each list entry is a dictionary of url component attributes as returned
  258. # by urlparse.urlsplit as applied to the absolute form of the URL. See
  259. # https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit
  260. # The values of the dictionary are treated as an filename match pattern
  261. # applied to that component of URLs, unless they start with a ^ in which
  262. # case they are treated as a regular expression match. If all the
  263. # specified component matches for a given list item succeed, the URL is
  264. # blacklisted.
  265. #
  266. #url_preview_url_blacklist:
  267. # # blacklist any URL with a username in its URI
  268. # - username: '*'
  269. #
  270. # # blacklist all *.google.com URLs
  271. # - netloc: 'google.com'
  272. # - netloc: '*.google.com'
  273. #
  274. # # blacklist all plain HTTP URLs
  275. # - scheme: 'http'
  276. #
  277. # # blacklist http(s)://www.acme.com/foo
  278. # - netloc: 'www.acme.com'
  279. # path: '/foo'
  280. #
  281. # # blacklist any URL with a literal IPv4 address
  282. # - netloc: '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$'
  283. # The largest allowed URL preview spidering size in bytes
  284. #
  285. #max_spider_size: 10M
  286. # A list of values for the Accept-Language HTTP header used when
  287. # downloading webpages during URL preview generation. This allows
  288. # Synapse to specify the preferred languages that URL previews should
  289. # be in when communicating with remote servers.
  290. #
  291. # Each value is a IETF language tag; a 2-3 letter identifier for a
  292. # language, optionally followed by subtags separated by '-', specifying
  293. # a country or region variant.
  294. #
  295. # Multiple values can be provided, and a weight can be added to each by
  296. # using quality value syntax (;q=). '*' translates to any language.
  297. #
  298. # Defaults to "en".
  299. #
  300. # Example:
  301. #
  302. # url_preview_accept_language:
  303. # - en-UK
  304. # - en-US;q=0.9
  305. # - fr;q=0.8
  306. # - *;q=0.7
  307. #
  308. url_preview_accept_language:
  309. # - en
  310. """
  311. % locals()
  312. )