2016-01-24 16:47:27 -07:00
|
|
|
# Copyright 2016 OpenMarket Ltd
|
2021-01-15 08:57:37 -07:00
|
|
|
# Copyright 2020-2021 The Matrix.org Foundation C.I.C.
|
2016-01-24 16:47:27 -07:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2018-02-01 17:35:18 -07:00
|
|
|
import datetime
|
|
|
|
import errno
|
|
|
|
import fnmatch
|
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import shutil
|
|
|
|
import sys
|
|
|
|
import traceback
|
2022-01-24 06:58:18 -07:00
|
|
|
from typing import TYPE_CHECKING, BinaryIO, Iterable, Optional, Tuple
|
2022-03-16 05:21:36 -06:00
|
|
|
from urllib.parse import urljoin, urlparse, urlsplit
|
2022-01-24 06:58:18 -07:00
|
|
|
from urllib.request import urlopen
|
2018-07-09 00:09:20 -06:00
|
|
|
|
2021-09-07 07:10:34 -06:00
|
|
|
import attr
|
|
|
|
|
2021-09-15 06:45:32 -06:00
|
|
|
from twisted.internet.defer import Deferred
|
2019-05-10 11:32:44 -06:00
|
|
|
from twisted.internet.error import DNSLookupError
|
2016-04-03 05:56:29 -06:00
|
|
|
|
2018-07-09 00:09:20 -06:00
|
|
|
from synapse.api.errors import Codes, SynapseError
|
2018-12-21 07:56:13 -07:00
|
|
|
from synapse.http.client import SimpleHttpClient
|
2016-04-03 05:56:29 -06:00
|
|
|
from synapse.http.server import (
|
2020-07-03 12:02:19 -06:00
|
|
|
DirectServeJsonResource,
|
2017-11-23 10:52:31 -07:00
|
|
|
respond_with_json,
|
2018-07-09 00:09:20 -06:00
|
|
|
respond_with_json_bytes,
|
2016-04-03 05:56:29 -06:00
|
|
|
)
|
2018-07-13 13:40:14 -06:00
|
|
|
from synapse.http.servlet import parse_integer, parse_string
|
2021-03-12 09:37:57 -07:00
|
|
|
from synapse.http.site import SynapseRequest
|
2019-07-03 08:07:04 -06:00
|
|
|
from synapse.logging.context import make_deferred_yieldable, run_in_background
|
2018-07-25 02:41:12 -06:00
|
|
|
from synapse.metrics.background_process_metrics import run_as_background_process
|
2018-11-15 14:55:58 -07:00
|
|
|
from synapse.rest.media.v1._base import get_filename_from_headers
|
2021-01-15 08:57:37 -07:00
|
|
|
from synapse.rest.media.v1.media_storage import MediaStorage
|
2021-09-21 10:09:57 -06:00
|
|
|
from synapse.rest.media.v1.oembed import OEmbedProvider
|
2022-03-16 05:21:36 -06:00
|
|
|
from synapse.rest.media.v1.preview_html import decode_body, parse_html_to_open_graph
|
2021-11-12 09:05:26 -07:00
|
|
|
from synapse.types import JsonDict, UserID
|
2020-08-07 06:02:55 -06:00
|
|
|
from synapse.util import json_encoder
|
2018-08-10 07:50:21 -06:00
|
|
|
from synapse.util.async_helpers import ObservableDeferred
|
2018-07-09 00:09:20 -06:00
|
|
|
from synapse.util.caches.expiringcache import ExpiringCache
|
2018-11-15 14:55:58 -07:00
|
|
|
from synapse.util.stringutils import random_string
|
2018-07-09 00:09:20 -06:00
|
|
|
|
|
|
|
from ._base import FileInfo
|
2016-03-28 20:13:25 -06:00
|
|
|
|
2021-01-15 08:57:37 -07:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.rest.media.v1.media_repository import MediaRepository
|
2021-03-23 05:12:48 -06:00
|
|
|
from synapse.server import HomeServer
|
2021-01-15 08:57:37 -07:00
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2019-11-05 08:45:17 -07:00
|
|
|
OG_TAG_NAME_MAXLEN = 50
|
|
|
|
OG_TAG_VALUE_MAXLEN = 1000
|
|
|
|
|
2020-07-27 05:50:44 -06:00
|
|
|
ONE_HOUR = 60 * 60 * 1000
|
2021-09-21 10:09:57 -06:00
|
|
|
ONE_DAY = 24 * ONE_HOUR
|
2021-09-29 03:24:37 -06:00
|
|
|
IMAGE_CACHE_EXPIRY_MS = 2 * ONE_DAY
|
2020-07-27 05:50:44 -06:00
|
|
|
|
2016-04-03 05:56:29 -06:00
|
|
|
|
2022-01-24 06:58:18 -07:00
|
|
|
@attr.s(slots=True, frozen=True, auto_attribs=True)
|
|
|
|
class DownloadResult:
|
|
|
|
length: int
|
|
|
|
uri: str
|
|
|
|
response_code: int
|
|
|
|
media_type: str
|
|
|
|
download_name: Optional[str]
|
|
|
|
expires: int
|
|
|
|
etag: Optional[str]
|
|
|
|
|
|
|
|
|
2021-09-07 07:10:34 -06:00
|
|
|
@attr.s(slots=True, frozen=True, auto_attribs=True)
|
|
|
|
class MediaInfo:
|
|
|
|
"""
|
|
|
|
Information parsed from downloading media being previewed.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# The Content-Type header of the response.
|
|
|
|
media_type: str
|
|
|
|
# The length (in bytes) of the downloaded media.
|
|
|
|
media_length: int
|
|
|
|
# The media filename, according to the server. This is parsed from the
|
|
|
|
# returned headers, if possible.
|
|
|
|
download_name: Optional[str]
|
|
|
|
# The time of the preview.
|
|
|
|
created_ts_ms: int
|
|
|
|
# Information from the media storage provider about where the file is stored
|
|
|
|
# on disk.
|
|
|
|
filesystem_id: str
|
|
|
|
filename: str
|
|
|
|
# The URI being previewed.
|
|
|
|
uri: str
|
|
|
|
# The HTTP response code.
|
|
|
|
response_code: int
|
|
|
|
# The timestamp (in milliseconds) of when this preview expires.
|
|
|
|
expires: int
|
|
|
|
# The ETag header of the response.
|
|
|
|
etag: Optional[str]
|
|
|
|
|
|
|
|
|
2020-07-03 12:02:19 -06:00
|
|
|
class PreviewUrlResource(DirectServeJsonResource):
|
2021-09-07 07:10:34 -06:00
|
|
|
"""
|
2022-07-12 13:01:58 -06:00
|
|
|
The `GET /_matrix/media/r0/preview_url` endpoint provides a generic preview API
|
|
|
|
for URLs which outputs Open Graph (https://ogp.me/) responses (with some Matrix
|
|
|
|
specific additions).
|
|
|
|
|
|
|
|
This does have trade-offs compared to other designs:
|
|
|
|
|
|
|
|
* Pros:
|
|
|
|
* Simple and flexible; can be used by any clients at any point
|
|
|
|
* Cons:
|
|
|
|
* If each homeserver provides one of these independently, all the homeservers in a
|
|
|
|
room may needlessly DoS the target URI
|
|
|
|
* The URL metadata must be stored somewhere, rather than just using Matrix
|
|
|
|
itself to store the media.
|
|
|
|
* Matrix cannot be used to distribute the metadata between homeservers.
|
|
|
|
|
|
|
|
When Synapse is asked to preview a URL it does the following:
|
|
|
|
|
|
|
|
1. Checks against a URL blacklist (defined as `url_preview_url_blacklist` in the
|
|
|
|
config).
|
|
|
|
2. Checks the URL against an in-memory cache and returns the result if it exists. (This
|
|
|
|
is also used to de-duplicate processing of multiple in-flight requests at once.)
|
|
|
|
3. Kicks off a background process to generate a preview:
|
|
|
|
1. Checks URL and timestamp against the database cache and returns the result if it
|
|
|
|
has not expired and was successful (a 2xx return code).
|
|
|
|
2. Checks if the URL matches an oEmbed (https://oembed.com/) pattern. If it
|
|
|
|
does, update the URL to download.
|
|
|
|
3. Downloads the URL and stores it into a file via the media storage provider
|
|
|
|
and saves the local media metadata.
|
|
|
|
4. If the media is an image:
|
|
|
|
1. Generates thumbnails.
|
|
|
|
2. Generates an Open Graph response based on image properties.
|
|
|
|
5. If the media is HTML:
|
|
|
|
1. Decodes the HTML via the stored file.
|
|
|
|
2. Generates an Open Graph response from the HTML.
|
|
|
|
3. If a JSON oEmbed URL was found in the HTML via autodiscovery:
|
|
|
|
1. Downloads the URL and stores it into a file via the media storage provider
|
|
|
|
and saves the local media metadata.
|
|
|
|
2. Convert the oEmbed response to an Open Graph response.
|
|
|
|
3. Override any Open Graph data from the HTML with data from oEmbed.
|
|
|
|
4. If an image exists in the Open Graph response:
|
|
|
|
1. Downloads the URL and stores it into a file via the media storage
|
|
|
|
provider and saves the local media metadata.
|
|
|
|
2. Generates thumbnails.
|
|
|
|
3. Updates the Open Graph response based on image properties.
|
|
|
|
6. If the media is JSON and an oEmbed URL was found:
|
|
|
|
1. Convert the oEmbed response to an Open Graph response.
|
|
|
|
2. If a thumbnail or image is in the oEmbed response:
|
|
|
|
1. Downloads the URL and stores it into a file via the media storage
|
|
|
|
provider and saves the local media metadata.
|
|
|
|
2. Generates thumbnails.
|
|
|
|
3. Updates the Open Graph response based on image properties.
|
|
|
|
7. Stores the result in the database cache.
|
|
|
|
4. Returns the result.
|
|
|
|
|
|
|
|
The in-memory cache expires after 1 hour.
|
|
|
|
|
|
|
|
Expired entries in the database cache (and their associated media files) are
|
|
|
|
deleted every 10 seconds. The default expiration time is 1 hour from download.
|
2021-09-07 07:10:34 -06:00
|
|
|
"""
|
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
isLeaf = True
|
|
|
|
|
2021-01-15 08:57:37 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
hs: "HomeServer",
|
|
|
|
media_repo: "MediaRepository",
|
|
|
|
media_storage: MediaStorage,
|
|
|
|
):
|
2019-06-29 01:06:55 -06:00
|
|
|
super().__init__()
|
2016-04-19 07:45:05 -06:00
|
|
|
|
|
|
|
self.auth = hs.get_auth()
|
|
|
|
self.clock = hs.get_clock()
|
|
|
|
self.filepaths = media_repo.filepaths
|
2021-09-24 05:25:21 -06:00
|
|
|
self.max_spider_size = hs.config.media.max_spider_size
|
2016-04-19 07:45:05 -06:00
|
|
|
self.server_name = hs.hostname
|
2022-02-23 04:04:02 -07:00
|
|
|
self.store = hs.get_datastores().main
|
2018-12-21 07:56:13 -07:00
|
|
|
self.client = SimpleHttpClient(
|
|
|
|
hs,
|
|
|
|
treq_args={"browser_like_redirects": True},
|
2021-09-24 05:25:21 -06:00
|
|
|
ip_whitelist=hs.config.media.url_preview_ip_range_whitelist,
|
|
|
|
ip_blacklist=hs.config.media.url_preview_ip_range_blacklist,
|
2021-02-26 10:37:57 -07:00
|
|
|
use_proxy=True,
|
2018-12-21 07:56:13 -07:00
|
|
|
)
|
2016-04-19 07:51:34 -06:00
|
|
|
self.media_repo = media_repo
|
2017-10-12 10:31:24 -06:00
|
|
|
self.primary_base_path = media_repo.primary_base_path
|
2018-01-09 07:36:07 -07:00
|
|
|
self.media_storage = media_storage
|
2016-04-19 07:45:05 -06:00
|
|
|
|
2021-10-13 05:00:07 -06:00
|
|
|
self._oembed = OEmbedProvider(hs)
|
2021-08-31 16:37:07 -06:00
|
|
|
|
2020-06-17 07:13:30 -06:00
|
|
|
# We run the background jobs if we're the instance specified (or no
|
|
|
|
# instance is specified, where we assume there is only one instance
|
|
|
|
# serving media).
|
|
|
|
instance_running_jobs = hs.config.media.media_instance_running_background_jobs
|
|
|
|
self._worker_run_media_background_jobs = (
|
|
|
|
instance_running_jobs is None
|
|
|
|
or instance_running_jobs == hs.get_instance_name()
|
|
|
|
)
|
|
|
|
|
2021-09-24 05:25:21 -06:00
|
|
|
self.url_preview_url_blacklist = hs.config.media.url_preview_url_blacklist
|
|
|
|
self.url_preview_accept_language = hs.config.media.url_preview_accept_language
|
2016-04-02 17:31:57 -06:00
|
|
|
|
2017-11-10 09:34:33 -07:00
|
|
|
# memory cache mapping urls to an ObservableDeferred returning
|
|
|
|
# JSON-encoded OG metadata
|
2021-07-16 11:22:36 -06:00
|
|
|
self._cache: ExpiringCache[str, ObservableDeferred] = ExpiringCache(
|
2016-04-03 05:56:29 -06:00
|
|
|
cache_name="url_previews",
|
|
|
|
clock=self.clock,
|
|
|
|
# don't spider URLs more often than once an hour
|
2020-07-27 05:50:44 -06:00
|
|
|
expiry_ms=ONE_HOUR,
|
2021-07-16 11:22:36 -06:00
|
|
|
)
|
2016-04-02 17:47:40 -06:00
|
|
|
|
2020-06-17 07:13:30 -06:00
|
|
|
if self._worker_run_media_background_jobs:
|
|
|
|
self._cleaner_loop = self.clock.looping_call(
|
|
|
|
self._start_expire_url_cache_data, 10 * 1000
|
|
|
|
)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2021-09-24 04:01:25 -06:00
|
|
|
async def _async_render_OPTIONS(self, request: SynapseRequest) -> None:
|
2019-07-02 12:01:28 -06:00
|
|
|
request.setHeader(b"Allow", b"OPTIONS, GET")
|
2020-07-03 12:02:19 -06:00
|
|
|
respond_with_json(request, 200, {}, send_cors=True)
|
2017-11-23 10:52:31 -07:00
|
|
|
|
2021-03-12 09:37:57 -07:00
|
|
|
async def _async_render_GET(self, request: SynapseRequest) -> None:
|
2016-04-11 03:39:16 -06:00
|
|
|
# XXX: if get_user_by_req fails, what should we do in an async render?
|
2019-06-29 01:06:55 -06:00
|
|
|
requester = await self.auth.get_user_by_req(request)
|
2021-07-21 07:47:56 -06:00
|
|
|
url = parse_string(request, "url", required=True)
|
|
|
|
ts = parse_integer(request, "ts")
|
|
|
|
if ts is None:
|
2016-04-11 03:39:16 -06:00
|
|
|
ts = self.clock.time_msec()
|
|
|
|
|
2017-11-10 09:34:33 -07:00
|
|
|
# XXX: we could move this into _do_preview if we wanted.
|
2022-03-16 05:21:36 -06:00
|
|
|
url_tuple = urlsplit(url)
|
2016-05-16 06:03:59 -06:00
|
|
|
for entry in self.url_preview_url_blacklist:
|
|
|
|
match = True
|
|
|
|
for attrib in entry:
|
|
|
|
pattern = entry[attrib]
|
|
|
|
value = getattr(url_tuple, attrib)
|
|
|
|
logger.debug(
|
2019-11-21 05:00:14 -07:00
|
|
|
"Matching attrib '%s' with value '%s' against pattern '%s'",
|
2019-10-24 11:43:13 -06:00
|
|
|
attrib,
|
|
|
|
value,
|
|
|
|
pattern,
|
2016-05-16 06:03:59 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
if value is None:
|
|
|
|
match = False
|
|
|
|
continue
|
|
|
|
|
2022-03-31 03:49:49 -06:00
|
|
|
# Some attributes might not be parsed as strings by urlsplit (such as the
|
|
|
|
# port, which is parsed as an int). Because we use match functions that
|
|
|
|
# expect strings, we want to make sure that's what we give them.
|
|
|
|
value_str = str(value)
|
|
|
|
|
2016-05-16 06:03:59 -06:00
|
|
|
if pattern.startswith("^"):
|
2022-03-31 03:49:49 -06:00
|
|
|
if not re.match(pattern, value_str):
|
2016-04-11 03:39:16 -06:00
|
|
|
match = False
|
|
|
|
continue
|
2016-05-16 06:03:59 -06:00
|
|
|
else:
|
2022-03-31 03:49:49 -06:00
|
|
|
if not fnmatch.fnmatch(value_str, pattern):
|
2016-05-16 06:03:59 -06:00
|
|
|
match = False
|
|
|
|
continue
|
|
|
|
if match:
|
2019-10-31 04:23:24 -06:00
|
|
|
logger.warning("URL %s blocked by url_blacklist entry %s", url, entry)
|
2016-05-16 06:03:59 -06:00
|
|
|
raise SynapseError(
|
|
|
|
403, "URL blocked by url pattern blacklist entry", Codes.UNKNOWN
|
|
|
|
)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2017-11-10 09:34:33 -07:00
|
|
|
# the in-memory cache:
|
|
|
|
# * ensures that only one request is active at a time
|
|
|
|
# * takes load off the DB for the thundering herds
|
|
|
|
# * also caches any failures (unlike the DB) so we don't keep
|
|
|
|
# requesting the same endpoint
|
|
|
|
|
|
|
|
observable = self._cache.get(url)
|
|
|
|
|
|
|
|
if not observable:
|
2018-04-27 04:29:27 -06:00
|
|
|
download = run_in_background(self._do_preview, url, requester.user, ts)
|
2017-11-10 09:34:33 -07:00
|
|
|
observable = ObservableDeferred(download, consumeErrors=True)
|
|
|
|
self._cache[url] = observable
|
2017-11-10 09:58:04 -07:00
|
|
|
else:
|
|
|
|
logger.info("Returning cached response")
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2020-08-07 07:44:48 -06:00
|
|
|
og = await make_deferred_yieldable(observable.observe())
|
2017-11-10 09:34:33 -07:00
|
|
|
respond_with_json_bytes(request, 200, og, send_cors=True)
|
|
|
|
|
2021-11-12 09:05:26 -07:00
|
|
|
async def _do_preview(self, url: str, user: UserID, ts: int) -> bytes:
|
2017-11-10 09:34:33 -07:00
|
|
|
"""Check the db, and download the URL and build a preview
|
|
|
|
|
|
|
|
Args:
|
2020-07-27 12:40:11 -06:00
|
|
|
url: The URL to preview.
|
|
|
|
user: The user requesting the preview.
|
|
|
|
ts: The timestamp requested for the preview.
|
2017-11-10 09:34:33 -07:00
|
|
|
|
|
|
|
Returns:
|
2020-07-27 12:40:11 -06:00
|
|
|
json-encoded og data
|
2017-11-10 09:34:33 -07:00
|
|
|
"""
|
|
|
|
# check the URL cache in the DB (which will also provide us with
|
2016-04-11 03:39:16 -06:00
|
|
|
# historical previews, if we have any)
|
2020-03-20 05:20:02 -06:00
|
|
|
cache_result = await self.store.get_url_cache(url, ts)
|
2016-04-11 03:39:16 -06:00
|
|
|
if (
|
|
|
|
cache_result
|
2017-09-28 05:37:53 -06:00
|
|
|
and cache_result["expires_ts"] > ts
|
2016-04-11 03:39:16 -06:00
|
|
|
and cache_result["response_code"] / 100 == 2
|
|
|
|
):
|
2018-11-07 07:37:43 -07:00
|
|
|
# It may be stored as text in the database, not as bytes (such as
|
|
|
|
# PostgreSQL). If so, encode it back before handing it on.
|
|
|
|
og = cache_result["og"]
|
2020-06-16 06:51:47 -06:00
|
|
|
if isinstance(og, str):
|
2018-11-07 07:37:43 -07:00
|
|
|
og = og.encode("utf8")
|
2019-07-23 07:00:55 -06:00
|
|
|
return og
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
# If this URL can be accessed via oEmbed, use that instead.
|
|
|
|
url_to_download = url
|
|
|
|
oembed_url = self._oembed.get_oembed_url(url)
|
|
|
|
if oembed_url:
|
|
|
|
url_to_download = oembed_url
|
|
|
|
|
2022-01-24 06:58:18 -07:00
|
|
|
media_info = await self._handle_url(url_to_download, user)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2019-10-24 11:31:53 -06:00
|
|
|
logger.debug("got media_info of '%s'", media_info)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
# The number of milliseconds that the response should be considered valid.
|
|
|
|
expiration_ms = media_info.expires
|
2022-01-18 11:20:24 -07:00
|
|
|
author_name: Optional[str] = None
|
2021-09-21 10:09:57 -06:00
|
|
|
|
2021-09-07 07:10:34 -06:00
|
|
|
if _is_media(media_info.media_type):
|
|
|
|
file_id = media_info.filesystem_id
|
2020-03-20 05:20:02 -06:00
|
|
|
dims = await self.media_repo._generate_thumbnails(
|
2021-09-07 07:10:34 -06:00
|
|
|
None, file_id, file_id, media_info.media_type, url_cache=True
|
2016-04-02 17:31:57 -06:00
|
|
|
)
|
2016-03-31 07:15:09 -06:00
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
og = {
|
2021-09-07 07:10:34 -06:00
|
|
|
"og:description": media_info.download_name,
|
|
|
|
"og:image": f"mxc://{self.server_name}/{media_info.filesystem_id}",
|
|
|
|
"og:image:type": media_info.media_type,
|
|
|
|
"matrix:image:size": media_info.media_length,
|
2016-04-11 03:39:16 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if dims:
|
|
|
|
og["og:image:width"] = dims["width"]
|
|
|
|
og["og:image:height"] = dims["height"]
|
|
|
|
else:
|
2019-10-31 04:23:24 -06:00
|
|
|
logger.warning("Couldn't get dims for %s" % url)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
|
|
|
# define our OG response for this media
|
2021-09-07 07:10:34 -06:00
|
|
|
elif _is_html(media_info.media_type):
|
2016-04-11 03:39:16 -06:00
|
|
|
# TODO: somehow stop a big HTML tree from exploding synapse's RAM
|
|
|
|
|
2021-09-07 07:10:34 -06:00
|
|
|
with open(media_info.filename, "rb") as file:
|
2018-11-07 07:37:43 -07:00
|
|
|
body = file.read()
|
2016-04-15 07:32:25 -06:00
|
|
|
|
2021-10-14 08:17:20 -06:00
|
|
|
tree = decode_body(body, media_info.uri, media_info.media_type)
|
2021-10-08 12:14:42 -06:00
|
|
|
if tree is not None:
|
|
|
|
# Check if this HTML document points to oEmbed information and
|
|
|
|
# defer to that.
|
|
|
|
oembed_url = self._oembed.autodiscover_from_html(tree)
|
2022-01-18 11:20:24 -07:00
|
|
|
og_from_oembed: JsonDict = {}
|
2021-10-08 12:14:42 -06:00
|
|
|
if oembed_url:
|
2022-01-24 06:58:18 -07:00
|
|
|
oembed_info = await self._handle_url(
|
|
|
|
oembed_url, user, allow_data_urls=True
|
|
|
|
)
|
2022-01-18 11:20:24 -07:00
|
|
|
(
|
|
|
|
og_from_oembed,
|
|
|
|
author_name,
|
|
|
|
expiration_ms,
|
|
|
|
) = await self._handle_oembed_response(
|
2021-10-08 12:14:42 -06:00
|
|
|
url, oembed_info, expiration_ms
|
|
|
|
)
|
|
|
|
|
2022-01-18 11:20:24 -07:00
|
|
|
# Parse Open Graph information from the HTML in case the oEmbed
|
|
|
|
# response failed or is incomplete.
|
2022-03-16 05:21:36 -06:00
|
|
|
og_from_html = parse_html_to_open_graph(tree)
|
2022-01-18 11:20:24 -07:00
|
|
|
|
|
|
|
# Compile the Open Graph response by using the scraped
|
|
|
|
# information from the HTML and overlaying any information
|
|
|
|
# from the oEmbed response.
|
|
|
|
og = {**og_from_html, **og_from_oembed}
|
2021-10-08 12:14:42 -06:00
|
|
|
|
|
|
|
await self._precache_image_url(user, media_info, og)
|
|
|
|
else:
|
|
|
|
og = {}
|
2021-09-21 10:09:57 -06:00
|
|
|
|
2021-10-08 12:14:42 -06:00
|
|
|
elif oembed_url:
|
|
|
|
# Handle the oEmbed information.
|
2022-01-18 11:20:24 -07:00
|
|
|
og, author_name, expiration_ms = await self._handle_oembed_response(
|
2021-10-08 12:14:42 -06:00
|
|
|
url, media_info, expiration_ms
|
|
|
|
)
|
2021-09-21 10:09:57 -06:00
|
|
|
await self._precache_image_url(user, media_info, og)
|
2016-08-16 07:53:18 -06:00
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
else:
|
2019-10-31 04:23:24 -06:00
|
|
|
logger.warning("Failed to find any OG data in %s", url)
|
2016-04-11 03:39:16 -06:00
|
|
|
og = {}
|
|
|
|
|
2022-01-18 11:20:24 -07:00
|
|
|
# If we don't have a title but we have author_name, copy it as
|
|
|
|
# title
|
|
|
|
if not og.get("og:title") and author_name:
|
|
|
|
og["og:title"] = author_name
|
|
|
|
|
2019-11-05 08:45:17 -07:00
|
|
|
# filter out any stupidly long values
|
|
|
|
keys_to_remove = []
|
|
|
|
for k, v in og.items():
|
2019-11-05 10:22:58 -07:00
|
|
|
# values can be numeric as well as strings, hence the cast to str
|
|
|
|
if len(k) > OG_TAG_NAME_MAXLEN or len(str(v)) > OG_TAG_VALUE_MAXLEN:
|
2019-11-05 08:45:17 -07:00
|
|
|
logger.warning(
|
|
|
|
"Pruning overlong tag %s from OG data", k[:OG_TAG_NAME_MAXLEN]
|
|
|
|
)
|
|
|
|
keys_to_remove.append(k)
|
|
|
|
for k in keys_to_remove:
|
|
|
|
del og[k]
|
|
|
|
|
2019-10-24 11:31:53 -06:00
|
|
|
logger.debug("Calculated OG for %s as %s", url, og)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2020-08-07 06:02:55 -06:00
|
|
|
jsonog = json_encoder.encode(og)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
# Cap the amount of time to consider a response valid.
|
|
|
|
expiration_ms = min(expiration_ms, ONE_DAY)
|
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
# store OG in history-aware DB cache
|
2020-03-20 05:20:02 -06:00
|
|
|
await self.store.store_url_cache(
|
2016-04-11 03:39:16 -06:00
|
|
|
url,
|
2021-09-07 07:10:34 -06:00
|
|
|
media_info.response_code,
|
|
|
|
media_info.etag,
|
2021-09-21 10:09:57 -06:00
|
|
|
media_info.created_ts_ms + expiration_ms,
|
2017-11-10 09:34:33 -07:00
|
|
|
jsonog,
|
2021-09-07 07:10:34 -06:00
|
|
|
media_info.filesystem_id,
|
|
|
|
media_info.created_ts_ms,
|
2016-04-11 03:39:16 -06:00
|
|
|
)
|
|
|
|
|
2019-10-10 07:52:29 -06:00
|
|
|
return jsonog.encode("utf8")
|
2016-04-08 14:36:48 -06:00
|
|
|
|
2022-01-24 06:58:18 -07:00
|
|
|
async def _download_url(self, url: str, output_stream: BinaryIO) -> DownloadResult:
|
|
|
|
"""
|
|
|
|
Fetches a remote URL and parses the headers.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
url: The URL to fetch.
|
|
|
|
output_stream: The stream to write the content to.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple of:
|
|
|
|
Media length, URL downloaded, the HTTP response code,
|
|
|
|
the media type, the downloaded file name, the number of
|
|
|
|
milliseconds the result is valid for, the etag header.
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
logger.debug("Trying to get preview for url '%s'", url)
|
|
|
|
length, headers, uri, code = await self.client.get_file(
|
|
|
|
url,
|
|
|
|
output_stream=output_stream,
|
|
|
|
max_size=self.max_spider_size,
|
2022-02-22 05:11:39 -07:00
|
|
|
headers={
|
|
|
|
b"Accept-Language": self.url_preview_accept_language,
|
|
|
|
# Use a custom user agent for the preview because some sites will only return
|
|
|
|
# Open Graph metadata to crawler user agents. Omit the Synapse version
|
|
|
|
# string to avoid leaking information.
|
|
|
|
b"User-Agent": [
|
|
|
|
"Synapse (bot; +https://github.com/matrix-org/synapse)"
|
|
|
|
],
|
|
|
|
},
|
2022-02-10 08:43:01 -07:00
|
|
|
is_allowed_content_type=_is_previewable,
|
2022-01-24 06:58:18 -07:00
|
|
|
)
|
|
|
|
except SynapseError:
|
|
|
|
# Pass SynapseErrors through directly, so that the servlet
|
|
|
|
# handler will return a SynapseError to the client instead of
|
|
|
|
# blank data or a 500.
|
|
|
|
raise
|
|
|
|
except DNSLookupError:
|
|
|
|
# DNS lookup returned no results
|
|
|
|
# Note: This will also be the case if one of the resolved IP
|
|
|
|
# addresses is blacklisted
|
|
|
|
raise SynapseError(
|
|
|
|
502,
|
|
|
|
"DNS resolution failure during URL preview generation",
|
|
|
|
Codes.UNKNOWN,
|
|
|
|
)
|
|
|
|
except Exception as e:
|
|
|
|
# FIXME: pass through 404s and other error messages nicely
|
|
|
|
logger.warning("Error downloading %s: %r", url, e)
|
|
|
|
|
|
|
|
raise SynapseError(
|
|
|
|
500,
|
|
|
|
"Failed to download content: %s"
|
|
|
|
% (traceback.format_exception_only(sys.exc_info()[0], e),),
|
|
|
|
Codes.UNKNOWN,
|
|
|
|
)
|
|
|
|
|
|
|
|
if b"Content-Type" in headers:
|
|
|
|
media_type = headers[b"Content-Type"][0].decode("ascii")
|
|
|
|
else:
|
|
|
|
media_type = "application/octet-stream"
|
|
|
|
|
|
|
|
download_name = get_filename_from_headers(headers)
|
|
|
|
|
|
|
|
# FIXME: we should calculate a proper expiration based on the
|
|
|
|
# Cache-Control and Expire headers. But for now, assume 1 hour.
|
|
|
|
expires = ONE_HOUR
|
|
|
|
etag = headers[b"ETag"][0].decode("ascii") if b"ETag" in headers else None
|
|
|
|
|
|
|
|
return DownloadResult(
|
|
|
|
length, uri, code, media_type, download_name, expires, etag
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _parse_data_url(
|
|
|
|
self, url: str, output_stream: BinaryIO
|
|
|
|
) -> DownloadResult:
|
|
|
|
"""
|
|
|
|
Parses a data: URL.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
url: The URL to parse.
|
|
|
|
output_stream: The stream to write the content to.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple of:
|
|
|
|
Media length, URL downloaded, the HTTP response code,
|
|
|
|
the media type, the downloaded file name, the number of
|
|
|
|
milliseconds the result is valid for, the etag header.
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
logger.debug("Trying to parse data url '%s'", url)
|
|
|
|
with urlopen(url) as url_info:
|
|
|
|
# TODO Can this be more efficient.
|
|
|
|
output_stream.write(url_info.read())
|
|
|
|
except Exception as e:
|
|
|
|
logger.warning("Error parsing data: URL %s: %r", url, e)
|
|
|
|
|
|
|
|
raise SynapseError(
|
|
|
|
500,
|
|
|
|
"Failed to parse data URL: %s"
|
|
|
|
% (traceback.format_exception_only(sys.exc_info()[0], e),),
|
|
|
|
Codes.UNKNOWN,
|
|
|
|
)
|
|
|
|
|
|
|
|
return DownloadResult(
|
|
|
|
# Read back the length that has been written.
|
|
|
|
length=output_stream.tell(),
|
|
|
|
uri=url,
|
|
|
|
# If it was parsed, consider this a 200 OK.
|
|
|
|
response_code=200,
|
|
|
|
# urlopen shoves the media-type from the data URL into the content type
|
|
|
|
# header object.
|
|
|
|
media_type=url_info.headers.get_content_type(),
|
|
|
|
# Some features are not supported by data: URLs.
|
|
|
|
download_name=None,
|
|
|
|
expires=ONE_HOUR,
|
|
|
|
etag=None,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _handle_url(
|
|
|
|
self, url: str, user: UserID, allow_data_urls: bool = False
|
|
|
|
) -> MediaInfo:
|
|
|
|
"""
|
|
|
|
Fetches content from a URL and parses the result to generate a MediaInfo.
|
|
|
|
|
|
|
|
It uses the media storage provider to persist the fetched content and
|
|
|
|
stores the mapping into the database.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
url: The URL to fetch.
|
|
|
|
user: The user who ahs requested this URL.
|
|
|
|
allow_data_urls: True if data URLs should be allowed.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A MediaInfo object describing the fetched content.
|
|
|
|
"""
|
|
|
|
|
2016-03-31 07:15:09 -06:00
|
|
|
# TODO: we should probably honour robots.txt... except in practice
|
|
|
|
# we're most likely being explicitly triggered by a human rather than a
|
|
|
|
# bot, so are we really a robot?
|
|
|
|
|
2017-09-28 05:18:06 -06:00
|
|
|
file_id = datetime.date.today().isoformat() + "_" + random_string(16)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2018-01-09 07:36:07 -07:00
|
|
|
file_info = FileInfo(server_name=None, file_id=file_id, url_cache=True)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
with self.media_storage.store_into_file(file_info) as (f, fname, finish):
|
2022-01-24 06:58:18 -07:00
|
|
|
if url.startswith("data:"):
|
|
|
|
if not allow_data_urls:
|
|
|
|
raise SynapseError(
|
|
|
|
500, "Previewing of data: URLs is forbidden", Codes.UNKNOWN
|
|
|
|
)
|
2020-07-27 05:50:44 -06:00
|
|
|
|
2022-01-24 06:58:18 -07:00
|
|
|
download_result = await self._parse_data_url(url, f)
|
2021-09-21 10:09:57 -06:00
|
|
|
else:
|
2022-01-24 06:58:18 -07:00
|
|
|
download_result = await self._download_url(url, f)
|
2021-09-21 10:09:57 -06:00
|
|
|
|
2022-01-24 06:58:18 -07:00
|
|
|
await finish()
|
2016-04-01 20:06:39 -06:00
|
|
|
|
2018-02-01 17:35:18 -07:00
|
|
|
try:
|
2016-01-24 16:47:27 -07:00
|
|
|
time_now_ms = self.clock.time_msec()
|
|
|
|
|
2020-03-20 05:20:02 -06:00
|
|
|
await self.store.store_local_media(
|
2016-03-31 19:17:48 -06:00
|
|
|
media_id=file_id,
|
2022-01-24 06:58:18 -07:00
|
|
|
media_type=download_result.media_type,
|
2020-07-27 05:50:44 -06:00
|
|
|
time_now_ms=time_now_ms,
|
2022-01-24 06:58:18 -07:00
|
|
|
upload_name=download_result.download_name,
|
|
|
|
media_length=download_result.length,
|
2016-03-28 20:13:25 -06:00
|
|
|
user_id=user,
|
2017-06-23 04:14:11 -06:00
|
|
|
url_cache=url,
|
2016-01-24 16:47:27 -07:00
|
|
|
)
|
|
|
|
|
2016-04-08 14:36:48 -06:00
|
|
|
except Exception as e:
|
2018-02-01 17:35:18 -07:00
|
|
|
logger.error("Error handling downloaded %s: %r", url, e)
|
|
|
|
# TODO: we really ought to delete the downloaded file in this
|
|
|
|
# case, since we won't have recorded it in the db, and will
|
|
|
|
# therefore not expire it.
|
|
|
|
raise
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2021-09-07 07:10:34 -06:00
|
|
|
return MediaInfo(
|
2022-01-24 06:58:18 -07:00
|
|
|
media_type=download_result.media_type,
|
|
|
|
media_length=download_result.length,
|
|
|
|
download_name=download_result.download_name,
|
2021-09-07 07:10:34 -06:00
|
|
|
created_ts_ms=time_now_ms,
|
|
|
|
filesystem_id=file_id,
|
|
|
|
filename=fname,
|
2022-01-24 06:58:18 -07:00
|
|
|
uri=download_result.uri,
|
|
|
|
response_code=download_result.response_code,
|
|
|
|
expires=download_result.expires,
|
|
|
|
etag=download_result.etag,
|
2021-09-07 07:10:34 -06:00
|
|
|
)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
async def _precache_image_url(
|
2021-11-12 09:05:26 -07:00
|
|
|
self, user: UserID, media_info: MediaInfo, og: JsonDict
|
2021-09-21 10:09:57 -06:00
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Pre-cache the image (if one exists) for posterity
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user: The user requesting the preview.
|
|
|
|
media_info: The media being previewed.
|
|
|
|
og: The Open Graph dictionary. This is modified with image information.
|
|
|
|
"""
|
|
|
|
# If there's no image or it is blank, there's nothing to do.
|
2022-06-06 05:46:04 -06:00
|
|
|
if "og:image" not in og:
|
|
|
|
return
|
|
|
|
|
|
|
|
# Remove the raw image URL, this will be replaced with an MXC URL, if successful.
|
|
|
|
image_url = og.pop("og:image")
|
|
|
|
if not image_url:
|
2021-09-21 10:09:57 -06:00
|
|
|
return
|
|
|
|
|
2022-03-16 05:21:36 -06:00
|
|
|
# The image URL from the HTML might be relative to the previewed page,
|
|
|
|
# convert it to an URL which can be requested directly.
|
|
|
|
url_parts = urlparse(image_url)
|
|
|
|
if url_parts.scheme != "data":
|
|
|
|
image_url = urljoin(media_info.uri, image_url)
|
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
# FIXME: it might be cleaner to use the same flow as the main /preview_url
|
|
|
|
# request itself and benefit from the same caching etc. But for now we
|
|
|
|
# just rely on the caching on the master request to speed things up.
|
2022-06-06 05:46:04 -06:00
|
|
|
try:
|
|
|
|
image_info = await self._handle_url(image_url, user, allow_data_urls=True)
|
|
|
|
except Exception as e:
|
|
|
|
# Pre-caching the image failed, don't block the entire URL preview.
|
|
|
|
logger.warning(
|
|
|
|
"Pre-caching image failed during URL preview: %s errored with %s",
|
|
|
|
image_url,
|
|
|
|
e,
|
|
|
|
)
|
|
|
|
return
|
2021-09-21 10:09:57 -06:00
|
|
|
|
|
|
|
if _is_media(image_info.media_type):
|
|
|
|
# TODO: make sure we don't choke on white-on-transparent images
|
|
|
|
file_id = image_info.filesystem_id
|
|
|
|
dims = await self.media_repo._generate_thumbnails(
|
|
|
|
None, file_id, file_id, image_info.media_type, url_cache=True
|
|
|
|
)
|
|
|
|
if dims:
|
|
|
|
og["og:image:width"] = dims["width"]
|
|
|
|
og["og:image:height"] = dims["height"]
|
|
|
|
else:
|
2022-06-06 05:46:04 -06:00
|
|
|
logger.warning("Couldn't get dims for %s", image_url)
|
2021-09-21 10:09:57 -06:00
|
|
|
|
|
|
|
og["og:image"] = f"mxc://{self.server_name}/{image_info.filesystem_id}"
|
|
|
|
og["og:image:type"] = image_info.media_type
|
|
|
|
og["matrix:image:size"] = image_info.media_length
|
|
|
|
|
2021-10-08 12:14:42 -06:00
|
|
|
async def _handle_oembed_response(
|
|
|
|
self, url: str, media_info: MediaInfo, expiration_ms: int
|
2022-01-18 11:20:24 -07:00
|
|
|
) -> Tuple[JsonDict, Optional[str], int]:
|
2021-10-08 12:14:42 -06:00
|
|
|
"""
|
|
|
|
Parse the downloaded oEmbed info.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
url: The URL which is being previewed (not the one which was
|
|
|
|
requested).
|
|
|
|
media_info: The media being previewed.
|
|
|
|
expiration_ms: The length of time, in milliseconds, the media is valid for.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple of:
|
|
|
|
The Open Graph dictionary, if the oEmbed info can be parsed.
|
2022-01-18 11:20:24 -07:00
|
|
|
The author name if it could be retrieved from oEmbed.
|
2021-10-08 12:14:42 -06:00
|
|
|
The (possibly updated) length of time, in milliseconds, the media is valid for.
|
|
|
|
"""
|
|
|
|
# If JSON was not returned, there's nothing to do.
|
|
|
|
if not _is_json(media_info.media_type):
|
2022-01-18 11:20:24 -07:00
|
|
|
return {}, None, expiration_ms
|
2021-10-08 12:14:42 -06:00
|
|
|
|
|
|
|
with open(media_info.filename, "rb") as file:
|
|
|
|
body = file.read()
|
|
|
|
|
|
|
|
oembed_response = self._oembed.parse_oembed_response(url, body)
|
|
|
|
open_graph_result = oembed_response.open_graph_result
|
|
|
|
|
|
|
|
# Use the cache age from the oEmbed result, if one was given.
|
|
|
|
if open_graph_result and oembed_response.cache_age is not None:
|
|
|
|
expiration_ms = oembed_response.cache_age
|
|
|
|
|
2022-01-18 11:20:24 -07:00
|
|
|
return open_graph_result, oembed_response.author_name, expiration_ms
|
2021-10-08 12:14:42 -06:00
|
|
|
|
2021-09-15 06:45:32 -06:00
|
|
|
def _start_expire_url_cache_data(self) -> Deferred:
|
2018-07-26 04:44:26 -06:00
|
|
|
return run_as_background_process(
|
2018-07-25 02:41:12 -06:00
|
|
|
"expire_url_cache_data", self._expire_url_cache_data
|
|
|
|
)
|
|
|
|
|
2021-01-15 08:57:37 -07:00
|
|
|
async def _expire_url_cache_data(self) -> None:
|
2017-09-28 05:18:06 -06:00
|
|
|
"""Clean up expired url cache content, media and thumbnails."""
|
2017-10-12 11:16:25 -06:00
|
|
|
|
2020-06-17 07:13:30 -06:00
|
|
|
assert self._worker_run_media_background_jobs
|
|
|
|
|
2017-09-28 05:18:06 -06:00
|
|
|
now = self.clock.time_msec()
|
|
|
|
|
2020-04-22 05:45:16 -06:00
|
|
|
logger.debug("Running url preview cache expiry")
|
2017-11-21 04:03:21 -07:00
|
|
|
|
2021-09-29 03:24:37 -06:00
|
|
|
def try_remove_parent_dirs(dirs: Iterable[str]) -> None:
|
|
|
|
"""Attempt to remove the given chain of parent directories
|
|
|
|
|
|
|
|
Args:
|
|
|
|
dirs: The list of directory paths to delete, with children appearing
|
|
|
|
before their parents.
|
|
|
|
"""
|
|
|
|
for dir in dirs:
|
|
|
|
try:
|
|
|
|
os.rmdir(dir)
|
|
|
|
except FileNotFoundError:
|
|
|
|
# Already deleted, continue with deleting the rest
|
|
|
|
pass
|
|
|
|
except OSError as e:
|
|
|
|
# Failed, skip deleting the rest of the parent dirs
|
|
|
|
if e.errno != errno.ENOTEMPTY:
|
|
|
|
logger.warning(
|
2022-05-12 11:16:32 -06:00
|
|
|
"Failed to remove media directory while clearing url preview cache: %r: %s",
|
|
|
|
dir,
|
|
|
|
e,
|
2021-09-29 03:24:37 -06:00
|
|
|
)
|
|
|
|
break
|
|
|
|
|
2017-09-28 05:18:06 -06:00
|
|
|
# First we delete expired url cache entries
|
2020-03-20 05:20:02 -06:00
|
|
|
media_ids = await self.store.get_expired_url_cache(now)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
removed_media = []
|
|
|
|
for media_id in media_ids:
|
|
|
|
fname = self.filepaths.url_cache_filepath(media_id)
|
|
|
|
try:
|
|
|
|
os.remove(fname)
|
2021-09-29 03:24:37 -06:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass # If the path doesn't exist, meh
|
2017-09-28 05:18:06 -06:00
|
|
|
except OSError as e:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.warning(
|
|
|
|
"Failed to remove media while clearing url preview cache: %r: %s",
|
|
|
|
media_id,
|
|
|
|
e,
|
|
|
|
)
|
2021-09-29 03:24:37 -06:00
|
|
|
continue
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
removed_media.append(media_id)
|
|
|
|
|
2021-09-29 03:24:37 -06:00
|
|
|
dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
|
|
|
|
try_remove_parent_dirs(dirs)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2020-03-20 05:20:02 -06:00
|
|
|
await self.store.delete_url_cache(removed_media)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2017-09-28 09:08:08 -06:00
|
|
|
if removed_media:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.debug(
|
|
|
|
"Deleted %d entries from url preview cache", len(removed_media)
|
|
|
|
)
|
2020-04-22 05:45:16 -06:00
|
|
|
else:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.debug("No entries removed from url preview cache")
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
# Now we delete old images associated with the url cache.
|
|
|
|
# These may be cached for a bit on the client (i.e., they
|
|
|
|
# may have a room open with a preview url thing open).
|
|
|
|
# So we wait a couple of days before deleting, just in case.
|
2021-09-29 03:24:37 -06:00
|
|
|
expire_before = now - IMAGE_CACHE_EXPIRY_MS
|
2020-03-20 05:20:02 -06:00
|
|
|
media_ids = await self.store.get_url_cache_media_before(expire_before)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
removed_media = []
|
|
|
|
for media_id in media_ids:
|
|
|
|
fname = self.filepaths.url_cache_filepath(media_id)
|
|
|
|
try:
|
|
|
|
os.remove(fname)
|
2021-09-29 03:24:37 -06:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass # If the path doesn't exist, meh
|
2017-09-28 05:18:06 -06:00
|
|
|
except OSError as e:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.warning(
|
|
|
|
"Failed to remove media from url preview cache: %r: %s", media_id, e
|
|
|
|
)
|
2021-09-29 03:24:37 -06:00
|
|
|
continue
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2021-09-29 03:24:37 -06:00
|
|
|
dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
|
|
|
|
try_remove_parent_dirs(dirs)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
thumbnail_dir = self.filepaths.url_cache_thumbnail_directory(media_id)
|
|
|
|
try:
|
|
|
|
shutil.rmtree(thumbnail_dir)
|
2021-09-29 03:24:37 -06:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass # If the path doesn't exist, meh
|
2017-09-28 05:18:06 -06:00
|
|
|
except OSError as e:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.warning(
|
|
|
|
"Failed to remove media from url preview cache: %r: %s", media_id, e
|
|
|
|
)
|
2021-09-29 03:24:37 -06:00
|
|
|
continue
|
2017-09-28 05:18:06 -06:00
|
|
|
|
|
|
|
removed_media.append(media_id)
|
|
|
|
|
2021-09-29 03:24:37 -06:00
|
|
|
dirs = self.filepaths.url_cache_thumbnail_dirs_to_delete(media_id)
|
|
|
|
# Note that one of the directories to be deleted has already been
|
|
|
|
# removed by the `rmtree` above.
|
|
|
|
try_remove_parent_dirs(dirs)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2020-03-20 05:20:02 -06:00
|
|
|
await self.store.delete_url_cache_media(removed_media)
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2020-04-22 05:45:16 -06:00
|
|
|
if removed_media:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.debug("Deleted %d media from url preview cache", len(removed_media))
|
2020-04-22 05:45:16 -06:00
|
|
|
else:
|
2022-05-12 11:16:32 -06:00
|
|
|
logger.debug("No media removed from url preview cache")
|
2017-09-28 05:18:06 -06:00
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2021-01-15 08:57:37 -07:00
|
|
|
def _is_media(content_type: str) -> bool:
|
|
|
|
return content_type.lower().startswith("image/")
|
2016-08-16 07:53:18 -06:00
|
|
|
|
|
|
|
|
2021-01-15 08:57:37 -07:00
|
|
|
def _is_html(content_type: str) -> bool:
|
2016-08-16 07:53:18 -06:00
|
|
|
content_type = content_type.lower()
|
2021-01-15 08:57:37 -07:00
|
|
|
return content_type.startswith("text/html") or content_type.startswith(
|
2016-08-16 07:53:18 -06:00
|
|
|
"application/xhtml"
|
2021-01-15 08:57:37 -07:00
|
|
|
)
|
2016-08-04 09:08:32 -06:00
|
|
|
|
|
|
|
|
2021-09-21 10:09:57 -06:00
|
|
|
def _is_json(content_type: str) -> bool:
|
|
|
|
return content_type.lower().startswith("application/json")
|
2022-02-10 08:43:01 -07:00
|
|
|
|
|
|
|
|
|
|
|
def _is_previewable(content_type: str) -> bool:
|
|
|
|
"""Returns True for content types for which we will perform URL preview and False
|
|
|
|
otherwise."""
|
|
|
|
|
|
|
|
return _is_html(content_type) or _is_media(content_type) or _is_json(content_type)
|