summary refs log tree commit diff
path: root/synapse/media/v1/download_resource.py
blob: c243f16a74e4778c9ea3e7318752606218ad6b1b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# -*- coding: utf-8 -*-
# Copyright 2014 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.

from synapse.http.server import respond_with_json
from synapse.util.stringutils import random_string
from synapse.api.errors import (
    cs_exception, CodeMessageException, cs_error, Codes
)

from twisted.protocols.basic import FileSender
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import defer

import os

import logging

logger = logging.getLogger(__name__)


class DownloadResource(Resource):
    isLeaf = True

    def __init__(self, hs, filepaths):
        Resource.__init__(self)
        self.client = hs.get_http_client()
        self.clock = hs.get_clock()
        self.server_name = hs.hostname
        self.store = hs.get_datastore()
        self.filepaths = filepaths

    def render_GET(self, request):
        self._async_render_GET(request)
        return NOT_DONE_YET

    def _respond_404(self, request):
        respond_with_json(
            request, 404,
            cs_error(
                "Not found %r" % (request.postpath,),
                code=Codes.NOT_FOUND,
            ),
            send_cors=True
        )

    @defer.inlineCallbacks
    def _async_render_GET(self, request):

        try:
            server_name, media_id = request.postpath
        except:
            self._respond_404(request)
            return

        try:
            if server_name == self.server_name:
                yield self._respond_local_file(request, media_id)
            else:
                yield self._respond_remote_file(request, server_name, media_id)
        except CodeMessageException as e:
            logger.exception(e)
            respond_with_json(request, e.code, cs_exception(e), send_cors=True)
        except:
            logger.exception("Failed to serve file")
            respond_with_json(
                request,
                500,
                {"error": "Internal server error"},
                send_cors=True
            )

    @defer.inlineCallbacks
    def _download_remote_file(self, server_name, media_id):
        filesystem_id = random_string(24)

        fname = self.filepaths.remote_media_filepath(
            server_name, filesystem_id
        )
        os.makedirs(os.path.dirname(fname))

        try:
            with open(fname, "wb") as f:
                length, headers = yield self.client.get_file(
                    server_name,
                    "/".join((
                        "/_matrix/media/v1/download", server_name, media_id,
                    )),
                    output_stream=f,
                )
        except:
            os.remove(fname)
            raise

        media_type = headers["Content-Type"][0]
        time_now_ms = self.clock.time_msec()

        yield self.store.store_cached_remote_media(
            origin=server_name,
            media_id=media_id,
            media_type=media_type,
            time_now_ms=self.clock.time_msec(),
            upload_name=None,
            media_length=length,
            filesystem_id=filesystem_id,
        )

        defer.returnValue({
            "media_type": media_type,
            "media_length": length,
            "upload_name": None,
            "created_ts": time_now_ms,
            "filesystem_id": filesystem_id,
        })

    @defer.inlineCallbacks
    def _respond_remote_file(self, request, server_name, media_id):
        media_info = yield self.store.get_cached_remote_media(
            server_name, media_id
        )

        if not media_info:
            media_info = yield self._download_remote_file(
                server_name, media_id
            )

        filesystem_id = media_info["filesystem_id"]

        file_path = self.filepaths.remote_media_filepath(
            server_name, filesystem_id
        )

        if os.path.isfile(file_path):
            media_type = media_info["media_type"]
            request.setHeader(b"Content-Type", media_type.encode("UTF-8"))

            # cache for at least a day.
            # XXX: we might want to turn this off for data we don't want to
            # recommend caching as it's sensitive or private - or at least
            # select private. don't bother setting Expires as all our
            # clients are smart enough to be happy with Cache-Control
            request.setHeader(
                b"Cache-Control", b"public,max-age=86400,s-maxage=86400"
            )

            with open(file_path, "rb") as f:
                yield FileSender().beginFileTransfer(f, request)

            request.finish()
        else:
            self._respond_404()

    @defer.inlineCallbacks
    def _respond_local_file(self, request, media_id):
        media_info = yield self.store.get_local_media(media_id)
        if not media_info:
            self._respond_404()
            return

        file_path = self.filepaths.local_media_filepath(media_id)

        logger.debug("Searching for %s", file_path)

        if os.path.isfile(file_path):
            media_type = media_info["media_type"]
            request.setHeader(b"Content-Type", media_type.encode("UTF-8"))

            # cache for at least a day.
            # XXX: we might want to turn this off for data we don't want to
            # recommend caching as it's sensitive or private - or at least
            # select private. don't bother setting Expires as all our
            # clients are smart enough to be happy with Cache-Control
            request.setHeader(
                b"Cache-Control", b"public,max-age=86400,s-maxage=86400"
            )

            with open(file_path, "rb") as f:
                yield FileSender().beginFileTransfer(f, request)

            request.finish()
        else:
            self._respond_404()