-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLargeFileUploadTask.php
More file actions
347 lines (318 loc) · 13.6 KB
/
Copy pathLargeFileUploadTask.php
File metadata and controls
347 lines (318 loc) · 13.6 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
namespace Microsoft\Graph\Core\Tasks;
use DateTime;
use DateTimeInterface;
use Exception;
use GuzzleHttp\Psr7\Utils;
use Http\Promise\Promise;
use InvalidArgumentException;
use Microsoft\Graph\Core\Models\LargeFileUploadSession;
use Microsoft\Kiota\Abstractions\HttpMethod;
use Microsoft\Kiota\Abstractions\RequestAdapter;
use Microsoft\Kiota\Abstractions\RequestInformation;
use Microsoft\Kiota\Abstractions\Serialization\AdditionalDataHolder;
use Microsoft\Kiota\Abstractions\Serialization\Parsable;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
class LargeFileUploadTask
{
/** @var Parsable|LargeFileUploadSession */
private $uploadSession;
private RequestAdapter $adapter;
private StreamInterface $stream;
private int $chunks;
private ?string $nextRange = null;
private int $fileSize;
private int $maxChunkSize;
/**
* @var callable(array{int, int}): void | null $onChunkUploadComplete
*/
private $onChunkUploadComplete = null;
public function __construct(Parsable $uploadSession, RequestAdapter $adapter, StreamInterface $stream, int $maxChunkSize = 4 * 1024 * 1024){
$this->uploadSession = $uploadSession;
$this->adapter = $adapter;
$this->stream = $stream;
$this->fileSize = $stream->getSize() ?? 0;
$this->maxChunkSize = $maxChunkSize;
/** @var string[] $cleanedValue */
$cleanedValue = $this->checkValueExists($uploadSession, 'getNextExpectedRange',
['nextExpectedRange', 'NextExpectedRange']);
$this->nextRange = $cleanedValue[0];
$this->chunks = (int)ceil($this->fileSize / $maxChunkSize);
}
/**
* Get the upload session used for the upload task.
* @return Parsable
*/
public function getUploadSession(): Parsable {
return $this->uploadSession;
}
/**
* Creates an upload session given the URL.
* The URL should not include the hostname since that is already included in the baseUrl for the requestAdapter.
* @param RequestAdapter $adapter
* @param Parsable&AdditionalDataHolder $requestBody
* @param string $url
* @return Promise<LargeFileUploadSession|null>
*/
public static function createUploadSession(RequestAdapter $adapter, $requestBody, string $url): Promise {
$requestInformation = new RequestInformation();
$baseUrl = rtrim($adapter->getBaseUrl(), '/');
$path = ltrim($url, '/');
$newUrl = "$baseUrl/$path";
$requestInformation->setUri($newUrl);
$requestInformation->httpMethod = HttpMethod::POST;
$requestInformation->setContentFromParsable($adapter, 'application/json', $requestBody);
return $adapter->sendAsync($requestInformation, [LargeFileUploadSession::class, 'createFromDiscriminatorValue']);
}
/**
* Get the current request adapter used for the upload task.
* @return RequestAdapter
*/
public function getAdapter(): RequestAdapter {
return $this->adapter;
}
/**
* Get the total number of chunks the file requires to fully upload.
* @return int
*/
public function getChunks(): int {
return $this->chunks;
}
/**
* Checks if the current upload session is expired.
* @param Parsable|null $uploadSession
* @return bool
* @throws Exception
*/
private function uploadSessionExpired(?Parsable $uploadSession): bool {
$now = new DateTime((new DateTime('now'))->format(DateTimeInterface::ATOM));
$validatedValue = $this->checkValueExists($uploadSession ?? $this->uploadSession, 'getExpirationDateTime', ['ExpirationDateTime', 'expirationDateTime']);
if (!$validatedValue[0]) {
throw new Exception('The upload session does not contain an expiry datetime.');
}
/** @var DateTime|null $expiry */
$expiry = $validatedValue[1];
if ($expiry === null){
throw new InvalidArgumentException('The upload session does not contain a valid expiry date.');
}
$then = new DateTime($expiry->format(DateTimeInterface::ATOM));
$interval = $now->diff($then);
if ($interval->invert !== 0){
return true;
}
return false;
}
/**
* Perform the actual upload for the whole file in bits.
* @param callable(array{int, int}): void | null $afterChunkUpload
* @return Promise<LargeFileUploadSession|null>
* @throws Exception
*/
public function upload(?callable $afterChunkUpload = null): Promise {
// Rewind at this point to take care of failures.
$this->stream->rewind();
if ($this->uploadSessionExpired($this->uploadSession)){
throw new RuntimeException('The upload session is expired.');
}
$this->onChunkUploadComplete ??= $afterChunkUpload;
$session = $this->nextChunk($this->stream, 0,max(0, min($this->maxChunkSize - 1, $this->fileSize - 1)));
$processNext = $session;
/// The logic below is to be used to accurately determine the range uploaded
/// even in scenarios where we are resuming existing upload sessions.
$rangeParts = explode("-", $this->nextRange[0] ?? '0-');
$end = min(intval($rangeParts[0]) + $this->maxChunkSize - 1, $this->fileSize);
$uploadedRange = [$rangeParts[0], $end];
while($this->chunks > 0){
$session = $processNext;
$promise = $session->then(
function (?LargeFileUploadSession $lfuSession) use (&$processNext, &$uploadedRange){
if (is_null($lfuSession)) {
return $lfuSession;
}
$nextRange = $lfuSession->getNextExpectedRanges();
$oldUrl = $this->getValidatedUploadUrl($this->uploadSession);
$lfuSession->setUploadUrl($oldUrl);
if (!is_null($this->onChunkUploadComplete)) {
call_user_func($this->onChunkUploadComplete, $uploadedRange);
}
if (empty($nextRange)) {
return $lfuSession;
}
$rangeParts = explode("-", $nextRange[0]);
$end = min(intval($rangeParts[0]) + $this->maxChunkSize, $this->fileSize);
$uploadedRange = [$rangeParts[0], $end];
$this->setNextRange($nextRange[0] . "-");
$processNext = $this->nextChunk($this->stream);
return $lfuSession;
}, function ($error) {
throw $error;
});
if ($promise !== null) {
$promise->wait();
}
$this->chunks--;
}
return $session;
}
/**
* @param string|null $nextRange
*/
private function setNextRange(?string $nextRange): void {
$this->nextRange = $nextRange;
}
/**
* Upload the next chunk of file.
* @return Promise<LargeFileUploadSession|null>
* @throws Exception
*/
public function nextChunk(StreamInterface $file, int $rangeStart = 0, int $rangeEnd = 0): Promise {
$uploadUrl = $this->getValidatedUploadUrl($this->uploadSession);
if (empty($uploadUrl)) {
throw new InvalidArgumentException('The upload session URL must not be empty.');
}
$info = new RequestInformation();
$info->setUri($uploadUrl);
$info->httpMethod = HttpMethod::PUT;
if (empty($this->nextRange)) {
$this->setNextRange($rangeStart.'-'.$rangeEnd);
}
$rangeParts = explode('-', ($this->nextRange ?? '-'));
$start = intval($rangeParts[0]);
$end = intval($rangeParts[1] ?? 0);
if ($start === 0 && $end === 0) {
$chunkData = $file->read($this->maxChunkSize);
$end = min($this->maxChunkSize - 1, $this->fileSize - 1);
} else if ($start === 0){
$chunkData = $file->read($end + 1);
}
else if ($end === 0){
$file->seek($start);
$chunkData = $file->read($this->maxChunkSize);
$end = $start + strlen($chunkData) - 1;
} else {
$file->seek($start);
$end = min($end, $this->maxChunkSize + $start);
$chunkData = $file->read($end - $start + 1);
}
$info->setHeaders(array_merge($info->getHeaders()->getAll(), ['Content-Range' => 'bytes '.($start).'-'.($end).'/'.$this->fileSize]));
$info->setHeaders(array_merge($info->getHeaders()->getAll(), ['Content-Length' => (string) strlen($chunkData)]));
$info->setStreamContent(Utils::streamFor($chunkData));
return $this->adapter->sendAsync($info, [LargeFileUploadSession::class, 'createFromDiscriminatorValue']);
}
/**
* Get the file stream.
* @return StreamInterface
*/
public function getFile(): StreamInterface {
return $this->stream;
}
/**
* Cancel an existing upload session from the File upload task.
* @return Promise<LargeFileUploadSession|Parsable>
* @throws Exception
*/
public function cancel(): Promise {
$requestInformation = new RequestInformation();
$requestInformation->httpMethod = HttpMethod::DELETE;
$uploadUrl = $this->getValidatedUploadUrl($this->uploadSession);
$requestInformation->setUri($uploadUrl);
return $this->adapter->sendNoContentAsync($requestInformation)
->then(function ($result) {
if (method_exists($this->uploadSession, 'setIsCancelled')){
$this->uploadSession->setIsCancelled(true);
}
else if (method_exists($this->uploadSession, 'setAdditionalData') && method_exists($this->uploadSession, 'getAdditionalData')){
$current = $this->uploadSession->getAdditionalData();
$new = array_merge($current, ['isCancelled' => true]);
$this->uploadSession->setAdditionalData($new);
}
return $this->uploadSession;
});
}
/**
* @param Parsable $parsable
* @param array<string> $propertyCandidates
* @return array{boolean,mixed}
*/
private function additionalDataContains(Parsable $parsable, array $propertyCandidates): array {
if (!is_subclass_of($parsable, AdditionalDataHolder::class)) {
throw new InvalidArgumentException('The object passed does not contain propert(y|ies) ['.implode(',',$propertyCandidates).'] and does not implement AdditionalDataHolder');
}
$additionalData = $parsable->getAdditionalData();
foreach ($propertyCandidates as $propertyCandidate) {
if (isset($additionalData[$propertyCandidate])) {
return [true, $additionalData[$propertyCandidate]];
}
}
return [false, null];
}
/**
* @param Parsable $parsable
* @param string $getterName
* @param array<string> $propertyNamesInAdditionalData
* @return array{bool, mixed}
*/
private function checkValueExists(Parsable $parsable, string $getterName, array $propertyNamesInAdditionalData): array {
$checkedAdditionalData = $this->additionalDataContains($parsable, $propertyNamesInAdditionalData);
if (is_subclass_of($parsable, AdditionalDataHolder::class) && $checkedAdditionalData[0]) {
return [true, $checkedAdditionalData[1]];
}
if (method_exists($parsable, $getterName)) {
return [true, $parsable->{$getterName}()];
}
return [false, null];
}
/**
* Resumes an upload task.
* @return Promise<LargeFileUploadSession|null>
* @throws Exception
*/
public function resume(): Promise {
if ($this->uploadSessionExpired($this->uploadSession)) {
throw new RuntimeException('The upload session is expired.');
}
/** @var array{bool,mixed} $validatedValue */
$validatedValue = $this->checkValueExists($this->uploadSession, 'getNextExpectedRanges', ['NextExpectedRanges', 'nextExpectedRanges']);
if (!$validatedValue[0]) {
throw new RuntimeException('The object passed does not contain a valid "nextExpectedRanges" property.');
}
/** @var string[] $nextRanges */
$nextRanges = $validatedValue[1];
if (count($nextRanges) === 0) {
throw new RuntimeException('No more bytes expected.');
}
$nextRange = $nextRanges[0];
$this->nextRange = $nextRange;
return $this->upload();
}
/**
* Validates the URL and returns it if it is valid otherwise throw an exception.
* @param Parsable $uploadSession
* @return string
*/
private function getValidatedUploadUrl(Parsable $uploadSession): string {
if (!method_exists($uploadSession, 'getUploadUrl')) {
throw new RuntimeException('The upload session does not contain a valid upload url');
}
$result = $uploadSession->getUploadUrl();
if ($result === null || trim($result) === '') {
throw new RuntimeException('The upload URL cannot be empty.');
}
return $result;
}
/**
* Get the next range required by the API.
* @return string|null
*/
public function getNextRange(): ?string {
return $this->nextRange;
}
/**
* Get the filesize of the file being uploaded.
* @return int
*/
public function getFileSize(): int {
return $this->fileSize;
}
}