cloudservicesuploadadapter.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module easy-image/cloudservicesuploadadapter
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
  10. import UploadGateway from '@ckeditor/ckeditor-cloud-services-core/src/uploadgateway/uploadgateway';
  11. import CloudServices from '@ckeditor/ckeditor5-cloud-services/src/cloudservices';
  12. /**
  13. * A plugin that enables upload to [CKEditor Cloud Services](https://ckeditor.com/ckeditor-cloud-services/).
  14. *
  15. * It is mainly used by the {@link module:easy-image/easyimage~EasyImage} feature.
  16. *
  17. * After enabling this adapter you need to configure the CKEditor Cloud Services integration through
  18. * {@link module:cloud-services/cloudservices~CloudServicesConfig `config.cloudServices`}.
  19. *
  20. * @extends module:core/plugin~Plugin
  21. */
  22. export default class CloudServicesUploadAdapter extends Plugin {
  23. /**
  24. * @inheritDoc
  25. */
  26. static get requires() {
  27. return [ FileRepository, CloudServices ];
  28. }
  29. /**
  30. * @inheritDoc
  31. */
  32. init() {
  33. const editor = this.editor;
  34. const cloudServices = editor.plugins.get( CloudServices );
  35. const token = cloudServices.token;
  36. const uploadUrl = cloudServices.uploadUrl;
  37. if ( !token ) {
  38. return;
  39. }
  40. this._uploadGateway = new CloudServicesUploadAdapter._UploadGateway( token, uploadUrl );
  41. editor.plugins.get( FileRepository ).createUploadAdapter = loader => {
  42. return new Adapter( this._uploadGateway, loader );
  43. };
  44. }
  45. }
  46. /**
  47. * @private
  48. */
  49. class Adapter {
  50. constructor( uploadGateway, loader ) {
  51. this.uploadGateway = uploadGateway;
  52. this.loader = loader;
  53. }
  54. upload() {
  55. return this.loader.file.then( file => {
  56. this.fileUploader = this.uploadGateway.upload( file );
  57. this.fileUploader.on( 'progress', ( evt, data ) => {
  58. this.loader.uploadTotal = data.total;
  59. this.loader.uploaded = data.uploaded;
  60. } );
  61. return this.fileUploader.send();
  62. } );
  63. }
  64. abort() {
  65. this.fileUploader.abort();
  66. }
  67. }
  68. // Store the API in static property to easily overwrite it in tests.
  69. // Too bad dependency injection does not work in Webpack + ES 6 (const) + Babel.
  70. CloudServicesUploadAdapter._UploadGateway = UploadGateway;