2016-04-03 05:59:27 -06:00
|
|
|
# -*- coding: utf-8 -*-
|
2016-01-24 16:47:27 -07:00
|
|
|
# Copyright 2016 OpenMarket Ltd
|
|
|
|
#
|
|
|
|
# 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.
|
|
|
|
|
2016-03-28 20:13:25 -06:00
|
|
|
from twisted.web.server import NOT_DONE_YET
|
2016-03-28 19:07:57 -06:00
|
|
|
from twisted.internet import defer
|
2016-04-19 04:24:59 -06:00
|
|
|
from twisted.web.resource import Resource
|
2016-04-03 05:56:29 -06:00
|
|
|
|
2016-04-08 14:36:48 -06:00
|
|
|
from synapse.api.errors import (
|
|
|
|
SynapseError, Codes,
|
|
|
|
)
|
2016-03-28 20:13:25 -06:00
|
|
|
from synapse.util.stringutils import random_string
|
2016-04-01 17:35:49 -06:00
|
|
|
from synapse.util.caches.expiringcache import ExpiringCache
|
2016-03-30 18:55:21 -06:00
|
|
|
from synapse.http.client import SpiderHttpClient
|
2016-04-03 05:56:29 -06:00
|
|
|
from synapse.http.server import (
|
2016-04-08 11:37:15 -06:00
|
|
|
request_handler, respond_with_json_bytes
|
2016-04-03 05:56:29 -06:00
|
|
|
)
|
2016-04-02 17:47:40 -06:00
|
|
|
from synapse.util.async import ObservableDeferred
|
2016-04-03 05:56:29 -06:00
|
|
|
from synapse.util.stringutils import is_ascii
|
2016-03-28 20:13:25 -06:00
|
|
|
|
|
|
|
import os
|
2016-03-31 07:15:09 -06:00
|
|
|
import re
|
2016-04-08 11:37:15 -06:00
|
|
|
import fnmatch
|
2016-04-03 05:56:29 -06:00
|
|
|
import cgi
|
2016-03-28 19:07:57 -06:00
|
|
|
import ujson as json
|
2016-04-14 08:23:48 -06:00
|
|
|
import urlparse
|
2016-01-24 16:47:27 -07:00
|
|
|
|
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2016-04-03 05:56:29 -06:00
|
|
|
|
2016-04-19 04:24:59 -06:00
|
|
|
class PreviewUrlResource(Resource):
|
2016-01-24 16:47:27 -07:00
|
|
|
isLeaf = True
|
|
|
|
|
2016-04-19 04:24:59 -06:00
|
|
|
def __init__(self, hs, media_repo):
|
|
|
|
Resource.__init__(self)
|
2016-04-19 07:45:05 -06:00
|
|
|
|
|
|
|
self.auth = hs.get_auth()
|
|
|
|
self.clock = hs.get_clock()
|
|
|
|
self.version_string = hs.version_string
|
|
|
|
self.filepaths = media_repo.filepaths
|
|
|
|
self.max_spider_size = hs.config.max_spider_size
|
|
|
|
self.server_name = hs.hostname
|
2016-04-19 07:48:24 -06:00
|
|
|
self.store = hs.get_datastore()
|
2016-03-30 18:55:21 -06:00
|
|
|
self.client = SpiderHttpClient(hs)
|
2016-04-19 07:51:34 -06:00
|
|
|
self.media_repo = media_repo
|
2016-04-19 07:45:05 -06:00
|
|
|
|
2016-05-16 06:03:59 -06:00
|
|
|
self.url_preview_url_blacklist = hs.config.url_preview_url_blacklist
|
2016-04-02 17:31:57 -06:00
|
|
|
|
|
|
|
# simple memory cache mapping urls to OG metadata
|
2016-04-01 17:35:49 -06:00
|
|
|
self.cache = 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
|
|
|
|
expiry_ms=60 * 60 * 1000,
|
2016-04-01 17:35:49 -06:00
|
|
|
)
|
|
|
|
self.cache.start()
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2016-04-02 17:47:40 -06:00
|
|
|
self.downloads = {}
|
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
def render_GET(self, request):
|
|
|
|
self._async_render_GET(request)
|
|
|
|
return NOT_DONE_YET
|
|
|
|
|
2016-04-28 03:57:49 -06:00
|
|
|
@request_handler()
|
2016-01-24 16:47:27 -07:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _async_render_GET(self, request):
|
2016-04-03 05:56:29 -06:00
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
# XXX: if get_user_by_req fails, what should we do in an async render?
|
|
|
|
requester = yield self.auth.get_user_by_req(request)
|
|
|
|
url = request.args.get("url")[0]
|
|
|
|
if "ts" in request.args:
|
|
|
|
ts = int(request.args.get("ts")[0])
|
|
|
|
else:
|
|
|
|
ts = self.clock.time_msec()
|
|
|
|
|
2016-05-16 06:03:59 -06:00
|
|
|
url_tuple = urlparse.urlsplit(url)
|
|
|
|
for entry in self.url_preview_url_blacklist:
|
|
|
|
match = True
|
|
|
|
for attrib in entry:
|
|
|
|
pattern = entry[attrib]
|
|
|
|
value = getattr(url_tuple, attrib)
|
|
|
|
logger.debug((
|
|
|
|
"Matching attrib '%s' with value '%s' against"
|
|
|
|
" pattern '%s'"
|
|
|
|
) % (attrib, value, pattern))
|
|
|
|
|
|
|
|
if value is None:
|
|
|
|
match = False
|
|
|
|
continue
|
|
|
|
|
|
|
|
if pattern.startswith('^'):
|
|
|
|
if not re.match(pattern, getattr(url_tuple, attrib)):
|
2016-04-11 03:39:16 -06:00
|
|
|
match = False
|
|
|
|
continue
|
2016-05-16 06:03:59 -06:00
|
|
|
else:
|
|
|
|
if not fnmatch.fnmatch(getattr(url_tuple, attrib), pattern):
|
|
|
|
match = False
|
|
|
|
continue
|
|
|
|
if match:
|
|
|
|
logger.warn(
|
|
|
|
"URL %s blocked by url_blacklist entry %s", url, entry
|
|
|
|
)
|
|
|
|
raise SynapseError(
|
|
|
|
403, "URL blocked by url pattern blacklist entry",
|
|
|
|
Codes.UNKNOWN
|
|
|
|
)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
|
|
|
# first check the memory cache - good to handle all the clients on this
|
|
|
|
# HS thundering away to preview the same URL at the same time.
|
|
|
|
og = self.cache.get(url)
|
|
|
|
if og:
|
|
|
|
respond_with_json_bytes(request, 200, json.dumps(og), send_cors=True)
|
|
|
|
return
|
|
|
|
|
|
|
|
# then check the URL cache in the DB (which will also provide us with
|
|
|
|
# historical previews, if we have any)
|
|
|
|
cache_result = yield self.store.get_url_cache(url, ts)
|
|
|
|
if (
|
|
|
|
cache_result and
|
|
|
|
cache_result["download_ts"] + cache_result["expires"] > ts and
|
|
|
|
cache_result["response_code"] / 100 == 2
|
|
|
|
):
|
|
|
|
respond_with_json_bytes(
|
|
|
|
request, 200, cache_result["og"].encode('utf-8'),
|
|
|
|
send_cors=True
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
# Ensure only one download for a given URL is active at a time
|
|
|
|
download = self.downloads.get(url)
|
|
|
|
if download is None:
|
|
|
|
download = self._download_url(url, requester.user)
|
|
|
|
download = ObservableDeferred(
|
|
|
|
download,
|
|
|
|
consumeErrors=True
|
|
|
|
)
|
|
|
|
self.downloads[url] = download
|
2016-04-08 11:37:15 -06:00
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
@download.addBoth
|
|
|
|
def callback(media_info):
|
|
|
|
del self.downloads[url]
|
|
|
|
return media_info
|
|
|
|
media_info = yield download.observe()
|
2016-03-31 19:17:48 -06:00
|
|
|
|
2016-04-11 03:39:16 -06:00
|
|
|
# FIXME: we should probably update our cache now anyway, so that
|
|
|
|
# even if the OG calculation raises, we don't keep hammering on the
|
|
|
|
# remote server. For now, leave it uncached to aid debugging OG
|
|
|
|
# calculation problems
|
|
|
|
|
|
|
|
logger.debug("got media_info of '%s'" % media_info)
|
|
|
|
|
|
|
|
if self._is_media(media_info['media_type']):
|
2016-04-19 04:24:59 -06:00
|
|
|
dims = yield self.media_repo._generate_local_thumbnails(
|
2016-04-11 03:39:16 -06:00
|
|
|
media_info['filesystem_id'], media_info
|
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 = {
|
|
|
|
"og:description": media_info['download_name'],
|
|
|
|
"og:image": "mxc://%s/%s" % (
|
|
|
|
self.server_name, media_info['filesystem_id']
|
|
|
|
),
|
|
|
|
"og:image:type": media_info['media_type'],
|
|
|
|
"matrix:image:size": media_info['media_length'],
|
|
|
|
}
|
|
|
|
|
|
|
|
if dims:
|
|
|
|
og["og:image:width"] = dims['width']
|
|
|
|
og["og:image:height"] = dims['height']
|
|
|
|
else:
|
|
|
|
logger.warn("Couldn't get dims for %s" % url)
|
|
|
|
|
|
|
|
# define our OG response for this media
|
|
|
|
elif self._is_html(media_info['media_type']):
|
|
|
|
# TODO: somehow stop a big HTML tree from exploding synapse's RAM
|
|
|
|
|
2016-04-15 07:32:25 -06:00
|
|
|
from lxml import etree
|
2016-04-13 04:57:46 -06:00
|
|
|
|
2016-04-15 06:19:57 -06:00
|
|
|
file = open(media_info['filename'])
|
|
|
|
body = file.read()
|
|
|
|
file.close()
|
2016-04-15 07:32:25 -06:00
|
|
|
|
|
|
|
# clobber the encoding from the content-type, or default to utf-8
|
|
|
|
# XXX: this overrides any <meta/> or XML charset headers in the body
|
|
|
|
# which may pose problems, but so far seems to work okay.
|
|
|
|
match = re.match(r'.*; *charset=(.*?)(;|$)', media_info['media_type'], re.I)
|
|
|
|
encoding = match.group(1) if match else "utf-8"
|
|
|
|
|
|
|
|
try:
|
|
|
|
parser = etree.HTMLParser(recover=True, encoding=encoding)
|
|
|
|
tree = etree.fromstring(body, parser)
|
|
|
|
og = yield self._calc_og(tree, media_info, requester)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# blindly try decoding the body as utf-8, which seems to fix
|
|
|
|
# the charset mismatches on https://google.com
|
|
|
|
parser = etree.HTMLParser(recover=True, encoding=encoding)
|
|
|
|
tree = etree.fromstring(body.decode('utf-8', 'ignore'), parser)
|
|
|
|
og = yield self._calc_og(tree, media_info, requester)
|
2016-04-11 03:39:16 -06:00
|
|
|
|
|
|
|
else:
|
|
|
|
logger.warn("Failed to find any OG data in %s", url)
|
|
|
|
og = {}
|
|
|
|
|
|
|
|
logger.debug("Calculated OG for %s as %s" % (url, og))
|
|
|
|
|
|
|
|
# store OG in ephemeral in-memory cache
|
|
|
|
self.cache[url] = og
|
|
|
|
|
|
|
|
# store OG in history-aware DB cache
|
|
|
|
yield self.store.store_url_cache(
|
|
|
|
url,
|
|
|
|
media_info["response_code"],
|
|
|
|
media_info["etag"],
|
|
|
|
media_info["expires"],
|
|
|
|
json.dumps(og),
|
|
|
|
media_info["filesystem_id"],
|
|
|
|
media_info["created_ts"],
|
|
|
|
)
|
|
|
|
|
|
|
|
respond_with_json_bytes(request, 200, json.dumps(og), send_cors=True)
|
2016-04-08 14:36:48 -06:00
|
|
|
|
2016-04-01 17:35:49 -06:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _calc_og(self, tree, media_info, requester):
|
|
|
|
# suck our tree into lxml and define our OG response.
|
|
|
|
|
|
|
|
# if we see any image URLs in the OG response, then spider them
|
2016-04-03 05:56:29 -06:00
|
|
|
# (although the client could choose to do this by asking for previews of those
|
|
|
|
# URLs to avoid DoSing the server)
|
2016-04-01 17:35:49 -06:00
|
|
|
|
|
|
|
# "og:type" : "video",
|
|
|
|
# "og:url" : "https://www.youtube.com/watch?v=LXDBoHyjmtw",
|
|
|
|
# "og:site_name" : "YouTube",
|
|
|
|
# "og:video:type" : "application/x-shockwave-flash",
|
2016-04-03 05:56:29 -06:00
|
|
|
# "og:description" : "Fun stuff happening here",
|
2016-04-01 17:35:49 -06:00
|
|
|
# "og:title" : "RemoteJam - Matrix team hack for Disrupt Europe Hackathon",
|
|
|
|
# "og:image" : "https://i.ytimg.com/vi/LXDBoHyjmtw/maxresdefault.jpg",
|
|
|
|
# "og:video:url" : "http://www.youtube.com/v/LXDBoHyjmtw?version=3&autohide=1",
|
|
|
|
# "og:video:width" : "1280"
|
|
|
|
# "og:video:height" : "720",
|
2016-04-03 05:56:29 -06:00
|
|
|
# "og:video:secure_url": "https://www.youtube.com/v/LXDBoHyjmtw?version=3",
|
2016-04-01 17:35:49 -06:00
|
|
|
|
|
|
|
og = {}
|
|
|
|
for tag in tree.xpath("//*/meta[starts-with(@property, 'og:')]"):
|
|
|
|
og[tag.attrib['property']] = tag.attrib['content']
|
|
|
|
|
|
|
|
# TODO: grab article: meta tags too, e.g.:
|
|
|
|
|
2016-04-03 05:56:29 -06:00
|
|
|
# "article:publisher" : "https://www.facebook.com/thethudonline" />
|
|
|
|
# "article:author" content="https://www.facebook.com/thethudonline" />
|
|
|
|
# "article:tag" content="baby" />
|
|
|
|
# "article:section" content="Breaking News" />
|
|
|
|
# "article:published_time" content="2016-03-31T19:58:24+00:00" />
|
|
|
|
# "article:modified_time" content="2016-04-01T18:31:53+00:00" />
|
2016-04-01 17:35:49 -06:00
|
|
|
|
|
|
|
if 'og:title' not in og:
|
|
|
|
# do some basic spidering of the HTML
|
|
|
|
title = tree.xpath("(//title)[1] | (//h1)[1] | (//h2)[1] | (//h3)[1]")
|
|
|
|
og['og:title'] = title[0].text.strip() if title else None
|
|
|
|
|
|
|
|
if 'og:image' not in og:
|
|
|
|
# TODO: extract a favicon failing all else
|
2016-04-03 05:56:29 -06:00
|
|
|
meta_image = tree.xpath(
|
|
|
|
"//*/meta[translate(@itemprop, 'IMAGE', 'image')='image']/@content"
|
|
|
|
)
|
2016-04-01 17:35:49 -06:00
|
|
|
if meta_image:
|
|
|
|
og['og:image'] = self._rebase_url(meta_image[0], media_info['uri'])
|
|
|
|
else:
|
2016-04-01 19:29:57 -06:00
|
|
|
# TODO: consider inlined CSS styles as well as width & height attribs
|
2016-04-01 17:35:49 -06:00
|
|
|
images = tree.xpath("//img[@src][number(@width)>10][number(@height)>10]")
|
2016-04-03 05:56:29 -06:00
|
|
|
images = sorted(images, key=lambda i: (
|
|
|
|
-1 * int(i.attrib['width']) * int(i.attrib['height'])
|
|
|
|
))
|
2016-04-01 17:35:49 -06:00
|
|
|
if not images:
|
|
|
|
images = tree.xpath("//img[@src]")
|
|
|
|
if images:
|
2016-04-02 18:33:12 -06:00
|
|
|
og['og:image'] = images[0].attrib['src']
|
2016-04-01 17:35:49 -06:00
|
|
|
|
|
|
|
# pre-cache the image for posterity
|
2016-04-03 05:56:29 -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.
|
2016-04-01 17:35:49 -06:00
|
|
|
if 'og:image' in og and og['og:image']:
|
2016-04-03 05:56:29 -06:00
|
|
|
image_info = yield self._download_url(
|
|
|
|
self._rebase_url(og['og:image'], media_info['uri']), requester.user
|
|
|
|
)
|
2016-04-01 17:35:49 -06:00
|
|
|
|
|
|
|
if self._is_media(image_info['media_type']):
|
|
|
|
# TODO: make sure we don't choke on white-on-transparent images
|
2016-04-19 04:24:59 -06:00
|
|
|
dims = yield self.media_repo._generate_local_thumbnails(
|
2016-04-03 05:56:29 -06:00
|
|
|
image_info['filesystem_id'], image_info
|
|
|
|
)
|
2016-04-01 19:29:57 -06:00
|
|
|
if dims:
|
|
|
|
og["og:image:width"] = dims['width']
|
|
|
|
og["og:image:height"] = dims['height']
|
|
|
|
else:
|
|
|
|
logger.warn("Couldn't get dims for %s" % og["og:image"])
|
2016-04-01 20:06:39 -06:00
|
|
|
|
2016-04-03 05:56:29 -06:00
|
|
|
og["og:image"] = "mxc://%s/%s" % (
|
|
|
|
self.server_name, image_info['filesystem_id']
|
|
|
|
)
|
2016-04-01 17:35:49 -06:00
|
|
|
og["og:image:type"] = image_info['media_type']
|
2016-04-03 16:57:05 -06:00
|
|
|
og["matrix:image:size"] = image_info['media_length']
|
2016-04-01 17:35:49 -06:00
|
|
|
else:
|
|
|
|
del og["og:image"]
|
|
|
|
|
|
|
|
if 'og:description' not in og:
|
2016-04-03 05:56:29 -06:00
|
|
|
meta_description = tree.xpath(
|
|
|
|
"//*/meta"
|
|
|
|
"[translate(@name, 'DESCRIPTION', 'description')='description']"
|
|
|
|
"/@content")
|
2016-04-01 17:35:49 -06:00
|
|
|
if meta_description:
|
|
|
|
og['og:description'] = meta_description[0]
|
|
|
|
else:
|
2016-04-08 11:37:15 -06:00
|
|
|
# grab any text nodes which are inside the <body/> tag...
|
|
|
|
# unless they are within an HTML5 semantic markup tag...
|
|
|
|
# <header/>, <nav/>, <aside/>, <footer/>
|
|
|
|
# ...or if they are within a <script/> or <style/> tag.
|
|
|
|
# This is a very very very coarse approximation to a plain text
|
|
|
|
# render of the page.
|
2016-04-03 05:56:29 -06:00
|
|
|
text_nodes = tree.xpath("//text()[not(ancestor::header | ancestor::nav | "
|
|
|
|
"ancestor::aside | ancestor::footer | "
|
|
|
|
"ancestor::script | ancestor::style)]" +
|
2016-04-01 17:35:49 -06:00
|
|
|
"[ancestor::body]")
|
|
|
|
text = ''
|
|
|
|
for text_node in text_nodes:
|
|
|
|
if len(text) < 500:
|
|
|
|
text += text_node + ' '
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
text = re.sub(r'[\t ]+', ' ', text)
|
|
|
|
text = re.sub(r'[\t \r\n]*[\r\n]+', '\n', text)
|
|
|
|
text = text.strip()[:500]
|
|
|
|
og['og:description'] = text if text else None
|
|
|
|
|
2016-04-03 05:56:29 -06:00
|
|
|
# TODO: delete the url downloads to stop diskfilling,
|
|
|
|
# as we only ever cared about its OG
|
|
|
|
defer.returnValue(og)
|
2016-04-01 17:35:49 -06:00
|
|
|
|
2016-03-31 19:17:48 -06:00
|
|
|
def _rebase_url(self, url, base):
|
2016-04-14 08:23:48 -06:00
|
|
|
base = list(urlparse.urlparse(base))
|
|
|
|
url = list(urlparse.urlparse(url))
|
2016-04-03 05:56:29 -06:00
|
|
|
if not url[0]: # fix up schema
|
2016-04-01 17:35:49 -06:00
|
|
|
url[0] = base[0] or "http"
|
2016-04-03 05:56:29 -06:00
|
|
|
if not url[1]: # fix up hostname
|
2016-03-31 19:17:48 -06:00
|
|
|
url[1] = base[1]
|
|
|
|
if not url[2].startswith('/'):
|
|
|
|
url[2] = re.sub(r'/[^/]+$', '/', base[2]) + url[2]
|
2016-04-14 08:23:48 -06:00
|
|
|
return urlparse.urlunparse(url)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2016-03-28 20:13:25 -06:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _download_url(self, url, user):
|
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?
|
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
# XXX: horrible duplication with base_resource's _download_remote_file()
|
|
|
|
file_id = random_string(24)
|
|
|
|
|
|
|
|
fname = self.filepaths.local_media_filepath(file_id)
|
2016-04-19 07:49:31 -06:00
|
|
|
self.media_repo._makedirs(fname)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
|
|
|
try:
|
|
|
|
with open(fname, "wb") as f:
|
2016-03-28 20:14:16 -06:00
|
|
|
logger.debug("Trying to get url '%s'" % url)
|
2016-04-02 17:31:57 -06:00
|
|
|
length, headers, uri, code = yield self.client.get_file(
|
2016-01-24 16:47:27 -07:00
|
|
|
url, output_stream=f, max_size=self.max_spider_size,
|
|
|
|
)
|
2016-04-01 20:06:39 -06:00
|
|
|
# FIXME: pass through 404s and other error messages nicely
|
|
|
|
|
2016-01-24 16:47:27 -07:00
|
|
|
media_type = headers["Content-Type"][0]
|
|
|
|
time_now_ms = self.clock.time_msec()
|
|
|
|
|
|
|
|
content_disposition = headers.get("Content-Disposition", None)
|
|
|
|
if content_disposition:
|
|
|
|
_, params = cgi.parse_header(content_disposition[0],)
|
|
|
|
download_name = None
|
|
|
|
|
|
|
|
# First check if there is a valid UTF-8 filename
|
|
|
|
download_name_utf8 = params.get("filename*", None)
|
|
|
|
if download_name_utf8:
|
|
|
|
if download_name_utf8.lower().startswith("utf-8''"):
|
|
|
|
download_name = download_name_utf8[7:]
|
|
|
|
|
|
|
|
# If there isn't check for an ascii name.
|
|
|
|
if not download_name:
|
|
|
|
download_name_ascii = params.get("filename", None)
|
|
|
|
if download_name_ascii and is_ascii(download_name_ascii):
|
|
|
|
download_name = download_name_ascii
|
|
|
|
|
|
|
|
if download_name:
|
|
|
|
download_name = urlparse.unquote(download_name)
|
|
|
|
try:
|
|
|
|
download_name = download_name.decode("utf-8")
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
download_name = None
|
|
|
|
else:
|
|
|
|
download_name = None
|
|
|
|
|
|
|
|
yield self.store.store_local_media(
|
2016-03-31 19:17:48 -06:00
|
|
|
media_id=file_id,
|
2016-01-24 16:47:27 -07:00
|
|
|
media_type=media_type,
|
|
|
|
time_now_ms=self.clock.time_msec(),
|
|
|
|
upload_name=download_name,
|
|
|
|
media_length=length,
|
2016-03-28 20:13:25 -06:00
|
|
|
user_id=user,
|
2016-01-24 16:47:27 -07:00
|
|
|
)
|
|
|
|
|
2016-04-08 14:36:48 -06:00
|
|
|
except Exception as e:
|
2016-01-24 16:47:27 -07:00
|
|
|
os.remove(fname)
|
2016-04-08 14:36:48 -06:00
|
|
|
raise SynapseError(
|
|
|
|
500, ("Failed to download content: %s" % e),
|
|
|
|
Codes.UNKNOWN
|
|
|
|
)
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2016-03-28 20:13:25 -06:00
|
|
|
defer.returnValue({
|
2016-01-24 16:47:27 -07:00
|
|
|
"media_type": media_type,
|
|
|
|
"media_length": length,
|
|
|
|
"download_name": download_name,
|
|
|
|
"created_ts": time_now_ms,
|
|
|
|
"filesystem_id": file_id,
|
|
|
|
"filename": fname,
|
2016-03-31 16:52:58 -06:00
|
|
|
"uri": uri,
|
2016-04-02 17:31:57 -06:00
|
|
|
"response_code": code,
|
|
|
|
# FIXME: we should calculate a proper expiration based on the
|
|
|
|
# Cache-Control and Expire headers. But for now, assume 1 hour.
|
|
|
|
"expires": 60 * 60 * 1000,
|
2016-04-02 19:02:46 -06:00
|
|
|
"etag": headers["ETag"][0] if "ETag" in headers else None,
|
2016-03-28 19:07:57 -06:00
|
|
|
})
|
2016-01-24 16:47:27 -07:00
|
|
|
|
2016-03-28 20:13:25 -06:00
|
|
|
def _is_media(self, content_type):
|
2016-01-24 16:47:27 -07:00
|
|
|
if content_type.lower().startswith("image/"):
|
|
|
|
return True
|
|
|
|
|
2016-03-28 20:13:25 -06:00
|
|
|
def _is_html(self, content_type):
|
2016-01-24 16:47:27 -07:00
|
|
|
content_type = content_type.lower()
|
2016-04-03 05:56:29 -06:00
|
|
|
if (
|
|
|
|
content_type.startswith("text/html") or
|
|
|
|
content_type.startswith("application/xhtml")
|
|
|
|
):
|
2016-01-24 16:47:27 -07:00
|
|
|
return True
|