|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +''' |
| 3 | +------------------------------------------------------------------------------ |
| 4 | + Copyright (c) 2015 Microsoft Corporation |
| 5 | +
|
| 6 | + Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + of this software and associated documentation files (the "Software"), to deal |
| 8 | + in the Software without restriction, including without limitation the rights |
| 9 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + copies of the Software, and to permit persons to whom the Software is |
| 11 | + furnished to do so, subject to the following conditions: |
| 12 | +
|
| 13 | + The above copyright notice and this permission notice shall be included in |
| 14 | + all copies or substantial portions of the Software. |
| 15 | +
|
| 16 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 | + THE SOFTWARE. |
| 23 | +------------------------------------------------------------------------------ |
| 24 | +''' |
| 25 | + |
| 26 | +from ..error import OneDriveError |
| 27 | +from ..model.upload_session import UploadSession |
| 28 | +from ..model.item import Item |
| 29 | +from ..options import HeaderOption |
| 30 | +from ..request.item_request_builder import ItemRequestBuilder |
| 31 | +from ..request_builder_base import RequestBuilderBase |
| 32 | +from ..request_base import RequestBase |
| 33 | +from ..helpers.file_slice import FileSlice |
| 34 | +import asyncio |
| 35 | +import json |
| 36 | +import math |
| 37 | +import os |
| 38 | +import time |
| 39 | + |
| 40 | +__PART_SIZE = 10 * 1024 * 1024 # recommended file size. Should be multiple of 320 * 1024 |
| 41 | +__MAX_SINGLE_FILE_UPLOAD = 100 * 1024 * 1024 |
| 42 | + |
| 43 | +class ItemUploadFragment(RequestBase): |
| 44 | + def __init__(self, request_url, client, options, file_handle): |
| 45 | + super(ItemUploadFragment, self).__init__(request_url, client, options) |
| 46 | + self.method = "PUT" |
| 47 | + self._file_handle = file_handle |
| 48 | + |
| 49 | + def post(self): |
| 50 | + """Sends the POST request |
| 51 | +
|
| 52 | + Returns: |
| 53 | + :class:`UploadSession<onedrivesdk.model.upload_session.UploadSession>`: |
| 54 | + The resulting entity from the operation |
| 55 | + """ |
| 56 | + entity = UploadSession(json.loads(self.send(data=self._file_handle).content)) |
| 57 | + return entity |
| 58 | + |
| 59 | + @asyncio.coroutine |
| 60 | + def post_async(self): |
| 61 | + """Sends the POST request using an asyncio coroutine |
| 62 | +
|
| 63 | + Yields: |
| 64 | + :class:`UploadedSession<onedrivesdk.model.upload_session.UploadedSession>`: |
| 65 | + The resulting entity from the operation |
| 66 | + """ |
| 67 | + future = self._client._loop.run_in_executor(None, |
| 68 | + self.post) |
| 69 | + entity = yield from future |
| 70 | + return entity |
| 71 | + |
| 72 | +class ItemUploadFragmentBuilder(RequestBuilderBase): |
| 73 | + def __init__(self, request_url, client, content_local_path): |
| 74 | + super(ItemUploadFragmentBuilder, self).__init__(request_url, client) |
| 75 | + self._method_options = {} |
| 76 | + self._file_handle = open(content_local_path, "rb") |
| 77 | + self._total_length = os.stat(content_local_path).st_size |
| 78 | + |
| 79 | + def __enter__(self): |
| 80 | + return self |
| 81 | + |
| 82 | + def __exit__(self, type, value, traceback): |
| 83 | + self._file_handle.close() |
| 84 | + |
| 85 | + def request(self, begin, length, options=None): |
| 86 | + """Builds the request for the ItemUploadFragment |
| 87 | +
|
| 88 | + Args: |
| 89 | + options (list of :class:`Option<onedrivesdk.options.Option>`): |
| 90 | + Default to None, list of options to include in the request |
| 91 | +
|
| 92 | + Returns: |
| 93 | + :class:`ItemUploadFragment<onedrivesdk.request.item_upload_fragment.ItemUploadFragment>`: |
| 94 | + The request |
| 95 | + """ |
| 96 | + opts = None |
| 97 | + if not (options is None or len(options) == 0): |
| 98 | + opts = options.copy() |
| 99 | + else: |
| 100 | + opts = [] |
| 101 | + |
| 102 | + self.content_type = "application/octet-stream" |
| 103 | + |
| 104 | + opts.append(HeaderOption("Content-Range", "bytes %d-%d/%d" % (begin, begin + length - 1, self._total_length))) |
| 105 | + opts.append(HeaderOption("Content-Length", length)) |
| 106 | + |
| 107 | + file_slice = FileSlice(self._file_handle, begin, length=length) |
| 108 | + req = ItemUploadFragment(self._request_url, self._client, opts, file_slice) |
| 109 | + return req |
| 110 | + |
| 111 | + def post(self, begin, length, options=None): |
| 112 | + """Sends the POST request |
| 113 | +
|
| 114 | + Returns: |
| 115 | + :class:`UploadedFragment<onedrivesdk.model.uploaded_fragment.UploadedFragment>`: |
| 116 | + The resulting UploadSession from the operation |
| 117 | + """ |
| 118 | + return self.request(begin, length, options).post() |
| 119 | + |
| 120 | + @asyncio.coroutine |
| 121 | + def post_async(self, begin, length, options=None): |
| 122 | + """Sends the POST request using an asyncio coroutine |
| 123 | +
|
| 124 | + Yields: |
| 125 | + :class:`UploadedFragment<onedrivesdk.model.uploaded_fragment.UploadedFragment>`: |
| 126 | + The resulting UploadSession from the operation |
| 127 | + """ |
| 128 | + entity = yield from self.request(begin, length, options).post_async() |
| 129 | + return entity |
| 130 | + |
| 131 | + |
| 132 | +def fragment_upload(self, local_path, conflict_behavior=None, upload_status=None): |
| 133 | + """Uploads file using PUT using multipart upload if needed. |
| 134 | +
|
| 135 | + Args: |
| 136 | + local_path (str): The path to the local file to upload. |
| 137 | + conflict_behavior (str): conflict behavior if the file is already |
| 138 | + uploaded. Use None value if file should be replaced or "rename", if |
| 139 | + the new file should get a new name |
| 140 | + upload_status (func): function(current_part, total_parts) to be called |
| 141 | + with upload status for each 10MB part |
| 142 | +
|
| 143 | + Returns: |
| 144 | + Created entity. |
| 145 | + """ |
| 146 | + file_size = os.stat(local_path).st_size |
| 147 | + if file_size <= __MAX_SINGLE_FILE_UPLOAD: |
| 148 | + # fallback to single shot upload if file is small enough |
| 149 | + return self.content.request().upload(local_path) |
| 150 | + else: |
| 151 | + # multipart upload needed for larger files |
| 152 | + if conflict_behavior: |
| 153 | + item = Item({'@name.conflictBehavior': conflict_behavior}) |
| 154 | + else: |
| 155 | + item = Item({}) |
| 156 | + |
| 157 | + session = self.create_session(item).post() |
| 158 | + |
| 159 | + with ItemUploadFragmentBuilder(session.upload_url, self._client, local_path) as upload_builder: |
| 160 | + total_parts = math.ceil(file_size / __PART_SIZE) |
| 161 | + for i in range(total_parts): |
| 162 | + if upload_status: |
| 163 | + upload_status(i, total_parts) |
| 164 | + |
| 165 | + length = min(__PART_SIZE, file_size - i * __PART_SIZE) |
| 166 | + tries = 0 |
| 167 | + while True: |
| 168 | + try: |
| 169 | + tries += 1 |
| 170 | + resp = upload_builder.post(i * __PART_SIZE, length) |
| 171 | + except OneDriveError as exc: |
| 172 | + if exc.status_code in (500, 502, 503, 504) and tries < 5: |
| 173 | + time.sleep(5) |
| 174 | + continue |
| 175 | + elif exc.status_code == 401: |
| 176 | + self._client.auth_provider.refresh_token() |
| 177 | + continue |
| 178 | + else: |
| 179 | + raise exc |
| 180 | + break # while True |
| 181 | + if upload_status: |
| 182 | + upload_status(total_parts, total_parts) # job completed |
| 183 | + # return last response |
| 184 | + return resp |
| 185 | + |
| 186 | +ItemRequestBuilder.fragment_upload = fragment_upload |
0 commit comments