upload_resource.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 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 synapse.http.server import respond_with_json
  16. from synapse.util.stringutils import random_string
  17. from synapse.api.errors import (
  18. cs_exception, SynapseError, CodeMessageException
  19. )
  20. from twisted.web.server import NOT_DONE_YET
  21. from twisted.internet import defer
  22. from .base_resource import BaseMediaResource
  23. import logging
  24. logger = logging.getLogger(__name__)
  25. class UploadResource(BaseMediaResource):
  26. def render_POST(self, request):
  27. self._async_render_POST(request)
  28. return NOT_DONE_YET
  29. def render_OPTIONS(self, request):
  30. respond_with_json(request, 200, {}, send_cors=True)
  31. return NOT_DONE_YET
  32. @defer.inlineCallbacks
  33. def _async_render_POST(self, request):
  34. try:
  35. auth_user = yield self.auth.get_user_by_req(request)
  36. # TODO: The checks here are a bit late. The content will have
  37. # already been uploaded to a tmp file at this point
  38. content_length = request.getHeader("Content-Length")
  39. if content_length is None:
  40. raise SynapseError(
  41. msg="Request must specify a Content-Length", code=400
  42. )
  43. if int(content_length) > self.max_upload_size:
  44. raise SynapseError(
  45. msg="Upload request body is too large",
  46. code=413,
  47. )
  48. headers = request.requestHeaders
  49. if headers.hasHeader("Content-Type"):
  50. media_type = headers.getRawHeaders("Content-Type")[0]
  51. else:
  52. raise SynapseError(
  53. msg="Upload request missing 'Content-Type'",
  54. code=400,
  55. )
  56. #if headers.hasHeader("Content-Disposition"):
  57. # disposition = headers.getRawHeaders("Content-Disposition")[0]
  58. # TODO(markjh): parse content-dispostion
  59. media_id = random_string(24)
  60. fname = self.filepaths.local_media_filepath(media_id)
  61. self._makedirs(fname)
  62. # This shouldn't block for very long because the content will have
  63. # already been uploaded at this point.
  64. with open(fname, "wb") as f:
  65. f.write(request.content.read())
  66. yield self.store.store_local_media(
  67. media_id=media_id,
  68. media_type=media_type,
  69. time_now_ms=self.clock.time_msec(),
  70. upload_name=None,
  71. media_length=content_length,
  72. user_id=auth_user,
  73. )
  74. media_info = {
  75. "media_type": media_type,
  76. "media_length": content_length,
  77. }
  78. yield self._generate_local_thumbnails(media_id, media_info)
  79. respond_with_json(
  80. request, 200, {"content_token": media_id}, send_cors=True
  81. )
  82. except CodeMessageException as e:
  83. logger.exception(e)
  84. respond_with_json(request, e.code, cs_exception(e), send_cors=True)
  85. except:
  86. logger.exception("Failed to store file")
  87. respond_with_json(
  88. request,
  89. 500,
  90. {"error": "Internal server error"},
  91. send_cors=True
  92. )