upload_resource.py 3.9 KB

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