ozone-api-upload 6.2.5 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -157,18 +157,15 @@ export declare class UploadFileRequest implements XMLHttpRequestLike {
157
157
  setRequestHeader(key: string, value: string): void;
158
158
  protected _createRequest(): OzoneAPIRequest;
159
159
  private _buildUrl;
160
+ private createBlob;
161
+ private submitTask;
160
162
  /**
161
163
  * alias to send method.
162
- * @param {FormData} file
164
+ * @param {FormData} formData
163
165
  * @param {string} folderId
164
166
  * @param options TaskHandlerOption
165
167
  * @return {Promise<string | void>}
166
168
  */
167
- uploadFile(file: FormData, folderId?: string, options?: TaskHandlerOption): Promise<TaskResult | null>;
168
- private notifyOnError;
169
- _startUploadSession(file: FormData, folderId: string): Promise<UploadSessionResult>;
170
- _getUploadId(data: UploadSessionResult): Promise<UploadIdResult>;
171
- _performUpload(data: UploadIdResult): Promise<UploadIdResult>;
172
- _endUploadSession(data: UploadIdResult): Promise<UploadEndResult>;
169
+ uploadFile(formData: FormData, folderId?: string, options?: TaskHandlerOption): Promise<TaskResult | null>;
173
170
  _waitForTask(taskId: string, options: TaskHandlerOption): Promise<TaskResult | undefined>;
174
171
  }
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { OzoneConfig } from 'ozone-config';
11
11
  import { OzoneAPIRequest } from 'ozone-api-request';
12
12
  import { getDefaultClient } from 'ozone-default-client';
13
+ import { Request } from 'typescript-http-client';
13
14
  /**
14
15
  * UploadFileRequest is a JavaScrip class that can be use as an
15
16
  * XMLHttpRequest to upload media using ozone v2 upload chanel.
@@ -154,123 +155,80 @@ export class UploadFileRequest {
154
155
  .join('/');
155
156
  });
156
157
  }
157
- /**
158
- * alias to send method.
159
- * @param {FormData} file
160
- * @param {string} folderId
161
- * @param options TaskHandlerOption
162
- * @return {Promise<string | void>}
163
- */
164
- uploadFile(file, folderId = '0', options = {}) {
165
- return this._startUploadSession(file, folderId)
166
- .then((result) => this._getUploadId(result))
167
- .then((result) => this._performUpload(result))
168
- .then((result) => this._endUploadSession(result))
169
- .then((result) => this._waitForTask(result.uploadFileId, options))
170
- .then((result) => {
171
- if (!(result === null || result === void 0 ? void 0 : result.mediaId)) {
172
- throw Error('No media define in Ozone');
173
- }
174
- this.status = 200;
175
- this._readyState = 4;
176
- this._mediaId = result.mediaId;
177
- if (this.eventTarget) {
178
- this.eventTarget.dispatchEvent(new CustomEvent('ozone-upload-completed', { bubbles: true, detail: { mediaId: result.mediaId } }));
158
+ createBlob(file) {
159
+ return __awaiter(this, void 0, void 0, function* () {
160
+ try {
161
+ const url = yield this._buildUrl('blob');
162
+ const blobRequest = new Request(url).setMethod('PUT').setBody(file);
163
+ blobRequest.timeout = Infinity;
164
+ blobRequest.upload.onprogress = this.upload.onprogress;
165
+ blobRequest.contentType = 'application/octet-stream';
166
+ return yield getDefaultClient().call(blobRequest);
179
167
  }
180
- return result;
181
- }).catch((error) => {
182
- this.status = 555;
183
- this._readyState = 4;
184
- console.error(error.message);
185
- return null;
186
- });
187
- }
188
- notifyOnError() {
189
- const self = this;
190
- return function (ev) {
191
- if (this.status === 0
192
- || this.status >= 500
193
- || this.status >= 400) {
194
- self.status = this.status;
195
- self._readyState = 4;
168
+ catch (err) {
169
+ console.error('Error creating blob', err);
170
+ throw err;
196
171
  }
197
- };
198
- }
199
- _startUploadSession(file, folderId) {
200
- return __awaiter(this, void 0, void 0, function* () {
201
- const request = this._createRequest();
202
- request.url = yield this._buildUrl('uploadStart');
203
- request.method = 'POST';
204
- request.onreadystatechange = this.notifyOnError();
205
- const config = yield OzoneConfig.get();
206
- const body = {
207
- mediaUploadChannelIdentifier: config.uploadChannel,
208
- autoCommit: false
209
- };
210
- request.body = JSON.stringify(body);
211
- return request.sendRequest()
212
- .then((xhr) => {
213
- const response = xhr.response;
214
- return {
215
- file: file,
216
- sessionId: response.result
217
- };
218
- });
219
172
  });
220
173
  }
221
- _getUploadId(data) {
174
+ submitTask(blobId, fileName, options) {
222
175
  return __awaiter(this, void 0, void 0, function* () {
223
- const request = this._createRequest();
224
- request.url = yield this._buildUrl('uploadId', data.sessionId);
225
- request.method = 'GET';
226
- request.onreadystatechange = this.notifyOnError();
227
- return request.sendRequest()
228
- .then((xhr) => {
229
- const response = xhr.response;
230
- const resultInfo = data;
231
- resultInfo.uploadId = response.result;
232
- resultInfo.folderId = response.folderId;
233
- return resultInfo;
234
- });
235
- });
236
- }
237
- _performUpload(data) {
238
- return __awaiter(this, void 0, void 0, function* () {
239
- const request = this._createRequest();
240
- request.url = yield this._buildUrl('upload', data.uploadId);
241
- request.method = 'POST';
242
- request.onreadystatechange = this.notifyOnError();
243
- const xhr = request.createXMLHttpRequest(false);
244
- xhr.upload.onprogress = this.upload.onprogress;
245
- request.body = data.file;
246
- return request.sendRequest(xhr)
247
- .then(() => {
248
- return data;
249
- });
176
+ try {
177
+ const url = yield this._buildUrl('task');
178
+ const taskRequest = new Request(url, {
179
+ method: 'POST',
180
+ body: JSON.stringify({
181
+ $type: 'importblobasmedia',
182
+ blob: blobId,
183
+ media: { name: fileName, type: 'media' },
184
+ mediaInputChannel: 'inputChannel'
185
+ })
186
+ });
187
+ const taskId = yield getDefaultClient().call(taskRequest);
188
+ return yield getDefaultClient().taskClient().waitForTask(taskId, {
189
+ skipWaitingOnSubTask: options.skipWaitingOnSubTask
190
+ }).waitResult;
191
+ }
192
+ catch (err) {
193
+ console.error('Error submit upload task', err);
194
+ throw err;
195
+ }
250
196
  });
251
197
  }
252
- _endUploadSession(data) {
198
+ /**
199
+ * alias to send method.
200
+ * @param {FormData} formData
201
+ * @param {string} folderId
202
+ * @param options TaskHandlerOption
203
+ * @return {Promise<string | void>}
204
+ */
205
+ uploadFile(formData, folderId = '0', options = {}) {
206
+ var _a;
253
207
  return __awaiter(this, void 0, void 0, function* () {
254
- const request = this._createRequest();
255
- request.url = yield this._buildUrl('uploadComplete', data.sessionId);
256
- request.method = 'POST';
257
- request.onreadystatechange = this.notifyOnError();
258
- const info = {
259
- 'selectedFileFieldNames': [['files']],
260
- mediaMetadatas: [
261
- {
262
- type: { type: 'PROPERTY', identifier: 'org.taktik.metadata.folderId' },
263
- valueObject: data.folderId
208
+ try {
209
+ const file = formData.get('file');
210
+ if (file instanceof File) {
211
+ const blob = yield this.createBlob(file);
212
+ if (blob.id) {
213
+ const result = yield this.submitTask(blob.id, file.name, options);
214
+ if (!(result === null || result === void 0 ? void 0 : result.mediaId)) {
215
+ console.error('No media define in Ozone');
216
+ return null;
217
+ }
218
+ this.status = 200;
219
+ this._mediaId = result.mediaId;
220
+ (_a = this.eventTarget) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new CustomEvent('ozone-upload-completed', { bubbles: true, detail: { mediaId: result.mediaId } }));
221
+ return result;
264
222
  }
265
- ]
266
- };
267
- request.body = JSON.stringify(info);
268
- return request.sendRequest()
269
- .then((xhr) => {
270
- const response = data;
271
- response.uploadFileId = xhr.response.file;
272
- return response;
273
- });
223
+ }
224
+ return null;
225
+ }
226
+ catch (err) {
227
+ this.status = 555;
228
+ this._readyState = 4;
229
+ console.error(err);
230
+ return null;
231
+ }
274
232
  });
275
233
  }
276
234
  _waitForTask(taskId, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ozone-api-upload",
3
- "version": "6.2.5",
3
+ "version": "6.3.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -25,10 +25,10 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "ozone-api-request": "^6.2.4",
28
- "ozone-config": "^6.2.4",
29
- "ozone-default-client": "^6.2.5",
30
- "ozone-typescript-client": "^6.2.5"
28
+ "ozone-config": "^6.3.0",
29
+ "ozone-default-client": "^6.2.6",
30
+ "ozone-typescript-client": "^6.2.6"
31
31
  },
32
32
  "repository": "https://github.com/taktik/ozone-components/packages/ozone-api/ozone-api-upload",
33
- "gitHead": "c8bbc5b6f832b1bda7cb9ba66a7ddebdf1bdca3d"
33
+ "gitHead": "3cf20be9cb77459d4fbecb82513db0b77b4bd8bb"
34
34
  }
@@ -3,7 +3,8 @@ import { OzoneAPIRequest } from 'ozone-api-request'
3
3
  import { getDefaultClient } from 'ozone-default-client'
4
4
  import { OzoneClient } from 'ozone-typescript-client'
5
5
  import TaskHandlerOption = OzoneClient.TaskHandlerOption
6
-
6
+ import { Request } from 'typescript-http-client'
7
+ import {Blob, UUID} from "ozone-type";
7
8
  export interface UploadSessionResult {
8
9
  file: FormData
9
10
  sessionId: string
@@ -44,6 +45,7 @@ export interface WaitResponse {
44
45
  }
45
46
  }
46
47
 
48
+
47
49
  export interface XMLHttpRequestLike {
48
50
  upload: {
49
51
  onprogress: { (event: Event): void }
@@ -236,137 +238,78 @@ export class UploadFileRequest implements XMLHttpRequestLike {
236
238
  .join('/')
237
239
  }
238
240
 
241
+ private async createBlob(file: File): Promise<Blob> {
242
+ try {
243
+ const url = await this._buildUrl('blob')
244
+ const blobRequest = new Request(url).setMethod('PUT').setBody(file)
245
+ blobRequest.timeout = Infinity
246
+ blobRequest.upload.onprogress = this.upload.onprogress
247
+ blobRequest.contentType = 'application/octet-stream'
248
+ return await getDefaultClient().call<Blob>(blobRequest)
249
+ } catch (err) {
250
+ console.error('Error creating blob', err)
251
+ throw err
252
+ }
253
+ }
254
+
255
+ private async submitTask(blobId: UUID, fileName: string, options: TaskHandlerOption): Promise<TaskResult | undefined> {
256
+ try {
257
+ const url = await this._buildUrl('task')
258
+ const taskRequest = new Request(url, {
259
+ method: 'POST',
260
+ body: JSON.stringify({
261
+ $type: 'importblobasmedia',
262
+ blob: blobId,
263
+ media: { name: fileName, type: 'media' },
264
+ mediaInputChannel: 'inputChannel'
265
+ })
266
+ })
267
+ const taskId = await getDefaultClient().call<UUID>(taskRequest)
268
+ return await getDefaultClient().taskClient().waitForTask<TaskResult>(taskId, {
269
+ skipWaitingOnSubTask: options.skipWaitingOnSubTask
270
+ }).waitResult
271
+ } catch (err) {
272
+ console.error('Error submit upload task', err)
273
+ throw err
274
+ }
275
+ }
276
+
239
277
  /**
240
278
  * alias to send method.
241
- * @param {FormData} file
279
+ * @param {FormData} formData
242
280
  * @param {string} folderId
243
281
  * @param options TaskHandlerOption
244
282
  * @return {Promise<string | void>}
245
283
  */
246
- uploadFile(file: FormData, folderId: string = '0', options: TaskHandlerOption = {}): Promise<TaskResult | null> {
247
-
248
- return this._startUploadSession(file, folderId)
249
- .then((result) => this._getUploadId(result))
250
- .then((result) => this._performUpload(result))
251
- .then((result) => this._endUploadSession(result))
252
- .then((result) => this._waitForTask(result.uploadFileId, options))
253
- .then((result) => {
254
- if (!result?.mediaId) {
255
- throw Error('No media define in Ozone')
256
- }
257
- this.status = 200
258
- this._readyState = 4
259
-
260
- this._mediaId = result.mediaId
261
-
262
- if (this.eventTarget) {
263
- this.eventTarget.dispatchEvent(
284
+ async uploadFile(formData: FormData, folderId: string = '0', options: TaskHandlerOption = {}): Promise<TaskResult | null> {
285
+ try {
286
+ const file = formData.get('file')
287
+ if (file instanceof File) {
288
+ const blob = await this.createBlob(file)
289
+ if (blob.id) {
290
+ const result = await this.submitTask(blob.id, file.name, options)
291
+ if (!result?.mediaId) {
292
+ console.error('No media define in Ozone')
293
+ return null
294
+ }
295
+ this.status = 200
296
+ this._mediaId = result.mediaId
297
+ this.eventTarget?.dispatchEvent(
264
298
  new CustomEvent('ozone-upload-completed',
265
299
  { bubbles: true, detail: { mediaId: result.mediaId } })
266
300
  )
301
+ return result
267
302
  }
268
- return result
269
- }).catch((error: Error) => {
270
- this.status = 555
271
- this._readyState = 4
272
- console.error(error.message)
273
- return null
274
- })
275
- }
276
-
277
- private notifyOnError(): ((this: XMLHttpRequest, ev: Event) => any) {
278
- const self = this
279
- return function(this: XMLHttpRequest, ev: Event) {
280
- if (this.status === 0
281
- || this.status >= 500
282
- || this.status >= 400) {
283
- self.status = this.status
284
- self._readyState = 4
285
303
  }
304
+ return null
305
+ } catch (err) {
306
+ this.status = 555
307
+ this._readyState = 4
308
+ console.error(err)
309
+ return null
286
310
  }
287
311
  }
288
312
 
289
- async _startUploadSession(file: FormData, folderId: string): Promise<UploadSessionResult> {
290
- const request = this._createRequest()
291
- request.url = await this._buildUrl('uploadStart')
292
- request.method = 'POST'
293
-
294
- request.onreadystatechange = this.notifyOnError()
295
-
296
- const config = await OzoneConfig.get()
297
- const body = {
298
- mediaUploadChannelIdentifier: config.uploadChannel,
299
- autoCommit: false
300
- }
301
- request.body = JSON.stringify(body)
302
- return request.sendRequest()
303
- .then((xhr: XMLHttpRequest) => {
304
- const response = xhr.response
305
- return {
306
- file: file,
307
- sessionId: response.result as string
308
- }
309
- })
310
- }
311
-
312
- async _getUploadId(data: UploadSessionResult): Promise<UploadIdResult> {
313
- const request = this._createRequest()
314
- request.url = await this._buildUrl('uploadId', data.sessionId)
315
- request.method = 'GET'
316
-
317
- request.onreadystatechange = this.notifyOnError()
318
-
319
- return request.sendRequest()
320
- .then((xhr: XMLHttpRequest) => {
321
- const response = xhr.response
322
- const resultInfo: UploadIdResult = data as UploadIdResult
323
- resultInfo.uploadId = response.result
324
- resultInfo.folderId = response.folderId
325
- return resultInfo
326
- })
327
- }
328
-
329
- async _performUpload(data: UploadIdResult): Promise<UploadIdResult> {
330
- const request = this._createRequest()
331
- request.url = await this._buildUrl('upload', data.uploadId)
332
- request.method = 'POST'
333
-
334
- request.onreadystatechange = this.notifyOnError()
335
- const xhr = request.createXMLHttpRequest(false)
336
- xhr.upload.onprogress = this.upload.onprogress
337
-
338
- request.body = data.file
339
- return request.sendRequest(xhr)
340
- .then(() => {
341
- return data
342
- })
343
- }
344
-
345
- async _endUploadSession(data: UploadIdResult): Promise<UploadEndResult> {
346
- const request = this._createRequest()
347
- request.url = await this._buildUrl('uploadComplete', data.sessionId)
348
- request.method = 'POST'
349
-
350
- request.onreadystatechange = this.notifyOnError()
351
- const info = {
352
- 'selectedFileFieldNames': [['files']],
353
- mediaMetadatas: [
354
- {
355
- type: { type: 'PROPERTY', identifier: 'org.taktik.metadata.folderId' },
356
- valueObject: data.folderId
357
- }
358
- ]
359
- }
360
- request.body = JSON.stringify(info)
361
-
362
- return request.sendRequest()
363
- .then((xhr: XMLHttpRequest) => {
364
- const response: UploadEndResult = data as UploadEndResult
365
- response.uploadFileId = xhr.response.file
366
- return response
367
- })
368
- }
369
-
370
313
  _waitForTask(taskId: string, options: TaskHandlerOption): Promise<TaskResult | undefined> {
371
314
  const taskClient = getDefaultClient().taskClient()
372
315
  const taskHandler = taskClient.waitForTask<TaskResult>(taskId, options)