download_resource.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 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. from .base_resource import BaseMediaResource, parse_media_id
  16. from synapse.http.server import request_handler
  17. from twisted.web.server import NOT_DONE_YET
  18. from twisted.internet import defer
  19. import logging
  20. logger = logging.getLogger(__name__)
  21. class DownloadResource(BaseMediaResource):
  22. def render_GET(self, request):
  23. self._async_render_GET(request)
  24. return NOT_DONE_YET
  25. @request_handler
  26. @defer.inlineCallbacks
  27. def _async_render_GET(self, request):
  28. server_name, media_id, name = parse_media_id(request)
  29. if server_name == self.server_name:
  30. yield self._respond_local_file(request, media_id, name)
  31. else:
  32. yield self._respond_remote_file(
  33. request, server_name, media_id, name
  34. )
  35. @defer.inlineCallbacks
  36. def _respond_local_file(self, request, media_id, name):
  37. media_info = yield self.store.get_local_media(media_id)
  38. if not media_info:
  39. self._respond_404(request)
  40. return
  41. media_type = media_info["media_type"]
  42. media_length = media_info["media_length"]
  43. upload_name = name if name else media_info["upload_name"]
  44. file_path = self.filepaths.local_media_filepath(media_id)
  45. yield self._respond_with_file(
  46. request, media_type, file_path, media_length,
  47. upload_name=upload_name,
  48. )
  49. @defer.inlineCallbacks
  50. def _respond_remote_file(self, request, server_name, media_id, name):
  51. media_info = yield self._get_remote_media(server_name, media_id)
  52. media_type = media_info["media_type"]
  53. media_length = media_info["media_length"]
  54. filesystem_id = media_info["filesystem_id"]
  55. upload_name = name if name else media_info["upload_name"]
  56. file_path = self.filepaths.remote_media_filepath(
  57. server_name, filesystem_id
  58. )
  59. yield self._respond_with_file(
  60. request, media_type, file_path, media_length,
  61. upload_name=upload_name,
  62. )