filerepository.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 upload/filerepository
  7. */
  8. /* globals console */
  9. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  10. import PendingActions from '@ckeditor/ckeditor5-core/src/pendingactions';
  11. import CKEditorError, { attachLinkToDocumentation } from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  12. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  13. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  14. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  15. import FileReader from './filereader.js';
  16. import uid from '@ckeditor/ckeditor5-utils/src/uid.js';
  17. /**
  18. * File repository plugin. A central point for managing file upload.
  19. *
  20. * To use it, first you need an upload adapter. Upload adapter's job is to handle communication with the server
  21. * (sending the file and handling server's response). You can use one of the existing plugins introducing upload adapters
  22. * (e.g. {@link module:easy-image/cloudservicesuploadadapter~CloudServicesUploadAdapter} or
  23. * {@link module:adapter-ckfinder/uploadadapter~CKFinderUploadAdapter}) or write your own one – see
  24. * the {@glink framework/guides/deep-dive/upload-adapter "Custom image upload adapter" deep dive guide}.
  25. *
  26. * Then, you can use {@link module:upload/filerepository~FileRepository#createLoader `createLoader()`} and the returned
  27. * {@link module:upload/filerepository~FileLoader} instance to load and upload files.
  28. *
  29. * @extends module:core/plugin~Plugin
  30. */
  31. export default class FileRepository extends Plugin {
  32. /**
  33. * @inheritDoc
  34. */
  35. static get pluginName() {
  36. return 'FileRepository';
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. static get requires() {
  42. return [ PendingActions ];
  43. }
  44. /**
  45. * @inheritDoc
  46. */
  47. init() {
  48. /**
  49. * Collection of loaders associated with this repository.
  50. *
  51. * @member {module:utils/collection~Collection} #loaders
  52. */
  53. this.loaders = new Collection();
  54. // Keeps upload in a sync with pending actions.
  55. this.loaders.on( 'add', () => this._updatePendingAction() );
  56. this.loaders.on( 'remove', () => this._updatePendingAction() );
  57. /**
  58. * Loaders mappings used to retrieve loaders references.
  59. *
  60. * @private
  61. * @member {Map<File|Promise, FileLoader>} #_loadersMap
  62. */
  63. this._loadersMap = new Map();
  64. /**
  65. * Reference to a pending action registered in a {@link module:core/pendingactions~PendingActions} plugin
  66. * while upload is in progress. When there is no upload then value is `null`.
  67. *
  68. * @private
  69. * @member {Object} #_pendingAction
  70. */
  71. this._pendingAction = null;
  72. /**
  73. * A factory function which should be defined before using `FileRepository`.
  74. *
  75. * It should return a new instance of {@link module:upload/filerepository~UploadAdapter} that will be used to upload files.
  76. * {@link module:upload/filerepository~FileLoader} instance associated with the adapter
  77. * will be passed to that function.
  78. *
  79. * For more information and example see {@link module:upload/filerepository~UploadAdapter}.
  80. *
  81. * @member {Function} #createUploadAdapter
  82. */
  83. /**
  84. * Number of bytes uploaded.
  85. *
  86. * @readonly
  87. * @observable
  88. * @member {Number} #uploaded
  89. */
  90. this.set( 'uploaded', 0 );
  91. /**
  92. * Number of total bytes to upload.
  93. *
  94. * It might be different than the file size because of headers and additional data.
  95. * It contains `null` if value is not available yet, so it's better to use {@link #uploadedPercent} to monitor
  96. * the progress.
  97. *
  98. * @readonly
  99. * @observable
  100. * @member {Number|null} #uploadTotal
  101. */
  102. this.set( 'uploadTotal', null );
  103. /**
  104. * Upload progress in percents.
  105. *
  106. * @readonly
  107. * @observable
  108. * @member {Number} #uploadedPercent
  109. */
  110. this.bind( 'uploadedPercent' ).to( this, 'uploaded', this, 'uploadTotal', ( uploaded, total ) => {
  111. return total ? ( uploaded / total * 100 ) : 0;
  112. } );
  113. }
  114. /**
  115. * Returns the loader associated with specified file or promise.
  116. *
  117. * To get loader by id use `fileRepository.loaders.get( id )`.
  118. *
  119. * @param {File|Promise.<File>} fileOrPromise Native file or promise handle.
  120. * @returns {module:upload/filerepository~FileLoader|null}
  121. */
  122. getLoader( fileOrPromise ) {
  123. return this._loadersMap.get( fileOrPromise ) || null;
  124. }
  125. /**
  126. * Creates a loader instance for the given file.
  127. *
  128. * Requires {@link #createUploadAdapter} factory to be defined.
  129. *
  130. * @param {File|Promise.<File>} fileOrPromise Native File object or native Promise object which resolves to a File.
  131. * @returns {module:upload/filerepository~FileLoader|null}
  132. */
  133. createLoader( fileOrPromise ) {
  134. if ( !this.createUploadAdapter ) {
  135. /**
  136. * You need to enable an upload adapter in order to be able to upload files.
  137. *
  138. * This warning shows up when {@link module:upload/filerepository~FileRepository} is being used
  139. * without {@link #createUploadAdapter definining an upload adapter}.
  140. *
  141. * **If you see this warning when using one of the {@glink builds/index CKEditor 5 Builds}**
  142. * it means that you did not configure any of the upload adapters available by default in those builds.
  143. *
  144. * See the {@glink features/image-upload/image-upload comprehensive "Image upload overview"} to learn which upload
  145. * adapters are available in the builds and how to configure them.
  146. *
  147. * **If you see this warning when using a custom build** there is a chance that you enabled
  148. * a feature like {@link module:image/imageupload~ImageUpload},
  149. * or {@link module:image/imageupload/imageuploadui~ImageUploadUI} but you did not enable any upload adapter.
  150. * You can choose one of the existing upload adapters listed in the
  151. * {@glink features/image-upload/image-upload "Image upload overview"}.
  152. *
  153. * You can also implement your {@glink framework/guides/deep-dive/upload-adapter own image upload adapter}.
  154. *
  155. * @error filerepository-no-upload-adapter
  156. */
  157. console.warn( attachLinkToDocumentation( 'filerepository-no-upload-adapter' ) );
  158. return null;
  159. }
  160. const loader = new FileLoader( Promise.resolve( fileOrPromise ), this.createUploadAdapter );
  161. this.loaders.add( loader );
  162. this._loadersMap.set( fileOrPromise, loader );
  163. // Store also file => loader mapping so loader can be retrieved by file instance returned upon Promise resolution.
  164. if ( fileOrPromise instanceof Promise ) {
  165. loader.file
  166. .then( file => {
  167. this._loadersMap.set( file, loader );
  168. } )
  169. // Every then() must have a catch().
  170. // File loader state (and rejections) are handled in read() and upload().
  171. // Also, see the "does not swallow the file promise rejection" test.
  172. .catch( () => {} );
  173. }
  174. loader.on( 'change:uploaded', () => {
  175. let aggregatedUploaded = 0;
  176. for ( const loader of this.loaders ) {
  177. aggregatedUploaded += loader.uploaded;
  178. }
  179. this.uploaded = aggregatedUploaded;
  180. } );
  181. loader.on( 'change:uploadTotal', () => {
  182. let aggregatedTotal = 0;
  183. for ( const loader of this.loaders ) {
  184. if ( loader.uploadTotal ) {
  185. aggregatedTotal += loader.uploadTotal;
  186. }
  187. }
  188. this.uploadTotal = aggregatedTotal;
  189. } );
  190. return loader;
  191. }
  192. /**
  193. * Destroys the given loader.
  194. *
  195. * @param {File|Promise|module:upload/filerepository~FileLoader} fileOrPromiseOrLoader File or Promise associated
  196. * with that loader or loader itself.
  197. */
  198. destroyLoader( fileOrPromiseOrLoader ) {
  199. const loader = fileOrPromiseOrLoader instanceof FileLoader ? fileOrPromiseOrLoader : this.getLoader( fileOrPromiseOrLoader );
  200. loader._destroy();
  201. this.loaders.remove( loader );
  202. this._loadersMap.forEach( ( value, key ) => {
  203. if ( value === loader ) {
  204. this._loadersMap.delete( key );
  205. }
  206. } );
  207. }
  208. /**
  209. * Registers or deregisters pending action bound with upload progress.
  210. *
  211. * @private
  212. */
  213. _updatePendingAction() {
  214. const pendingActions = this.editor.plugins.get( PendingActions );
  215. if ( this.loaders.length ) {
  216. if ( !this._pendingAction ) {
  217. const t = this.editor.t;
  218. const getMessage = value => `${ t( 'Upload in progress' ) } ${ parseInt( value ) }%.`;
  219. this._pendingAction = pendingActions.add( getMessage( this.uploadedPercent ) );
  220. this._pendingAction.bind( 'message' ).to( this, 'uploadedPercent', getMessage );
  221. }
  222. } else {
  223. pendingActions.remove( this._pendingAction );
  224. this._pendingAction = null;
  225. }
  226. }
  227. }
  228. mix( FileRepository, ObservableMixin );
  229. /**
  230. * File loader class.
  231. *
  232. * It is used to control the process of reading the file and uploading it using the specified upload adapter.
  233. */
  234. class FileLoader {
  235. /**
  236. * Creates a new instance of `FileLoader`.
  237. *
  238. * @param {Promise.<File>} filePromise A promise which resolves to a file instance.
  239. * @param {Function} uploadAdapterCreator The function which returns {@link module:upload/filerepository~UploadAdapter} instance.
  240. */
  241. constructor( filePromise, uploadAdapterCreator ) {
  242. /**
  243. * Unique id of FileLoader instance.
  244. *
  245. * @readonly
  246. * @member {Number}
  247. */
  248. this.id = uid();
  249. /**
  250. * Additional wrapper over the initial file promise passed to this loader.
  251. *
  252. * @protected
  253. * @member {module:upload/filerepository~FilePromiseWrapper}
  254. */
  255. this._filePromiseWrapper = this._createFilePromiseWrapper( filePromise );
  256. /**
  257. * Adapter instance associated with this file loader.
  258. *
  259. * @private
  260. * @member {module:upload/filerepository~UploadAdapter}
  261. */
  262. this._adapter = uploadAdapterCreator( this );
  263. /**
  264. * FileReader used by FileLoader.
  265. *
  266. * @protected
  267. * @member {module:upload/filereader~FileReader}
  268. */
  269. this._reader = new FileReader();
  270. /**
  271. * Current status of FileLoader. It can be one of the following:
  272. *
  273. * * 'idle',
  274. * * 'reading',
  275. * * 'uploading',
  276. * * 'aborted',
  277. * * 'error'.
  278. *
  279. * When reading status can change in a following way:
  280. *
  281. * `idle` -> `reading` -> `idle`
  282. * `idle` -> `reading -> `aborted`
  283. * `idle` -> `reading -> `error`
  284. *
  285. * When uploading status can change in a following way:
  286. *
  287. * `idle` -> `uploading` -> `idle`
  288. * `idle` -> `uploading` -> `aborted`
  289. * `idle` -> `uploading` -> `error`
  290. *
  291. * @readonly
  292. * @observable
  293. * @member {String} #status
  294. */
  295. this.set( 'status', 'idle' );
  296. /**
  297. * Number of bytes uploaded.
  298. *
  299. * @readonly
  300. * @observable
  301. * @member {Number} #uploaded
  302. */
  303. this.set( 'uploaded', 0 );
  304. /**
  305. * Number of total bytes to upload.
  306. *
  307. * @readonly
  308. * @observable
  309. * @member {Number|null} #uploadTotal
  310. */
  311. this.set( 'uploadTotal', null );
  312. /**
  313. * Upload progress in percents.
  314. *
  315. * @readonly
  316. * @observable
  317. * @member {Number} #uploadedPercent
  318. */
  319. this.bind( 'uploadedPercent' ).to( this, 'uploaded', this, 'uploadTotal', ( uploaded, total ) => {
  320. return total ? ( uploaded / total * 100 ) : 0;
  321. } );
  322. /**
  323. * Response of the upload.
  324. *
  325. * @readonly
  326. * @observable
  327. * @member {Object|null} #uploadResponse
  328. */
  329. this.set( 'uploadResponse', null );
  330. }
  331. /**
  332. * A `Promise` which resolves to a `File` instance associated with this file loader.
  333. *
  334. * @type {Promise.<File|null>}
  335. */
  336. get file() {
  337. if ( !this._filePromiseWrapper ) {
  338. // Loader was destroyed, return promise which resolves to null.
  339. return Promise.resolve( null );
  340. } else {
  341. // The `this._filePromiseWrapper.promise` is chained and not simply returned to handle a case when:
  342. //
  343. // * The `loader.file.then( ... )` is called by external code (returned promise is pending).
  344. // * Then `loader._destroy()` is called (call is synchronous) which destroys the `loader`.
  345. // * Promise returned by the first `loader.file.then( ... )` call is resolved.
  346. //
  347. // Returning `this._filePromiseWrapper.promise` will still resolve to a `File` instance so there
  348. // is an additional check needed in the chain to see if `loader` was destroyed in the meantime.
  349. return this._filePromiseWrapper.promise.then( file => this._filePromiseWrapper ? file : null );
  350. }
  351. }
  352. /**
  353. * Returns the file data. To read its data, you need for first load the file
  354. * by using the {@link module:upload/filerepository~FileLoader#read `read()`} method.
  355. *
  356. * @type {File|undefined}
  357. */
  358. get data() {
  359. return this._reader.data;
  360. }
  361. /**
  362. * Reads file using {@link module:upload/filereader~FileReader}.
  363. *
  364. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-read-wrong-status` when status
  365. * is different than `idle`.
  366. *
  367. * Example usage:
  368. *
  369. * fileLoader.read()
  370. * .then( data => { ... } )
  371. * .catch( err => {
  372. * if ( err === 'aborted' ) {
  373. * console.log( 'Reading aborted.' );
  374. * } else {
  375. * console.log( 'Reading error.', err );
  376. * }
  377. * } );
  378. *
  379. * @returns {Promise.<String>} Returns promise that will be resolved with read data. Promise will be rejected if error
  380. * occurs or if read process is aborted.
  381. */
  382. read() {
  383. if ( this.status != 'idle' ) {
  384. /**
  385. * You cannot call read if the status is different than idle.
  386. *
  387. * @error filerepository-read-wrong-status
  388. */
  389. throw new CKEditorError( 'filerepository-read-wrong-status', this );
  390. }
  391. this.status = 'reading';
  392. return this.file
  393. .then( file => this._reader.read( file ) )
  394. .then( data => {
  395. // Edge case: reader was aborted after file was read - double check for proper status.
  396. // It can happen when image was deleted during its upload.
  397. if ( this.status !== 'reading' ) {
  398. throw this.status;
  399. }
  400. this.status = 'idle';
  401. return data;
  402. } )
  403. .catch( err => {
  404. if ( err === 'aborted' ) {
  405. this.status = 'aborted';
  406. throw 'aborted';
  407. }
  408. this.status = 'error';
  409. throw this._reader.error ? this._reader.error : err;
  410. } );
  411. }
  412. /**
  413. * Reads file using the provided {@link module:upload/filerepository~UploadAdapter}.
  414. *
  415. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-upload-wrong-status` when status
  416. * is different than `idle`.
  417. * Example usage:
  418. *
  419. * fileLoader.upload()
  420. * .then( data => { ... } )
  421. * .catch( e => {
  422. * if ( e === 'aborted' ) {
  423. * console.log( 'Uploading aborted.' );
  424. * } else {
  425. * console.log( 'Uploading error.', e );
  426. * }
  427. * } );
  428. *
  429. * @returns {Promise.<Object>} Returns promise that will be resolved with response data. Promise will be rejected if error
  430. * occurs or if read process is aborted.
  431. */
  432. upload() {
  433. if ( this.status != 'idle' ) {
  434. /**
  435. * You cannot call upload if the status is different than idle.
  436. *
  437. * @error filerepository-upload-wrong-status
  438. */
  439. throw new CKEditorError( 'filerepository-upload-wrong-status', this );
  440. }
  441. this.status = 'uploading';
  442. return this.file
  443. .then( () => this._adapter.upload() )
  444. .then( data => {
  445. this.uploadResponse = data;
  446. this.status = 'idle';
  447. return data;
  448. } )
  449. .catch( err => {
  450. if ( this.status === 'aborted' ) {
  451. throw 'aborted';
  452. }
  453. this.status = 'error';
  454. throw err;
  455. } );
  456. }
  457. /**
  458. * Aborts loading process.
  459. */
  460. abort() {
  461. const status = this.status;
  462. this.status = 'aborted';
  463. if ( !this._filePromiseWrapper.isFulfilled ) {
  464. // Edge case: file loader is aborted before read() is called
  465. // so it might happen that no one handled the rejection of this promise.
  466. // See https://github.com/ckeditor/ckeditor5-upload/pull/100
  467. this._filePromiseWrapper.promise.catch( () => {} );
  468. this._filePromiseWrapper.rejecter( 'aborted' );
  469. } else if ( status == 'reading' ) {
  470. this._reader.abort();
  471. } else if ( status == 'uploading' && this._adapter.abort ) {
  472. this._adapter.abort();
  473. }
  474. this._destroy();
  475. }
  476. /**
  477. * Performs cleanup.
  478. *
  479. * @private
  480. */
  481. _destroy() {
  482. this._filePromiseWrapper = undefined;
  483. this._reader = undefined;
  484. this._adapter = undefined;
  485. this.uploadResponse = undefined;
  486. }
  487. /**
  488. * Wraps a given file promise into another promise giving additional
  489. * control (resolving, rejecting, checking if fulfilled) over it.
  490. *
  491. * @private
  492. * @param filePromise The initial file promise to be wrapped.
  493. * @returns {module:upload/filerepository~FilePromiseWrapper}
  494. */
  495. _createFilePromiseWrapper( filePromise ) {
  496. const wrapper = {};
  497. wrapper.promise = new Promise( ( resolve, reject ) => {
  498. wrapper.rejecter = reject;
  499. wrapper.isFulfilled = false;
  500. filePromise
  501. .then( file => {
  502. wrapper.isFulfilled = true;
  503. resolve( file );
  504. } )
  505. .catch( err => {
  506. wrapper.isFulfilled = true;
  507. reject( err );
  508. } );
  509. } );
  510. return wrapper;
  511. }
  512. }
  513. mix( FileLoader, ObservableMixin );
  514. /**
  515. * Upload adapter interface used by the {@link module:upload/filerepository~FileRepository file repository}
  516. * to handle file upload. An upload adapter is a bridge between the editor and server that handles file uploads.
  517. * It should contain a logic necessary to initiate an upload process and monitor its progress.
  518. *
  519. * Learn how to develop your own upload adapter for CKEditor 5 in the
  520. * {@glink framework/guides/deep-dive/upload-adapter "Custom upload adapter" guide}.
  521. *
  522. * @interface UploadAdapter
  523. */
  524. /**
  525. * Executes the upload process.
  526. * This method should return a promise that will resolve when data will be uploaded to server. Promise should be
  527. * resolved with an object containing information about uploaded file:
  528. *
  529. * {
  530. * default: 'http://server/default-size.image.png'
  531. * }
  532. *
  533. * Additionally, other image sizes can be provided:
  534. *
  535. * {
  536. * default: 'http://server/default-size.image.png',
  537. * '160': 'http://server/size-160.image.png',
  538. * '500': 'http://server/size-500.image.png',
  539. * '1000': 'http://server/size-1000.image.png',
  540. * '1052': 'http://server/default-size.image.png'
  541. * }
  542. *
  543. * NOTE: When returning multiple images, the widest returned one should equal the default one. It is essential to
  544. * correctly set `width` attribute of the image. See this discussion:
  545. * https://github.com/ckeditor/ckeditor5-easy-image/issues/4 for more information.
  546. *
  547. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  548. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  549. *
  550. * @method module:upload/filerepository~UploadAdapter#upload
  551. * @returns {Promise.<Object>} Promise that should be resolved when data is uploaded.
  552. */
  553. /**
  554. * Aborts the upload process.
  555. * After aborting it should reject promise returned from {@link #upload upload()}.
  556. *
  557. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  558. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  559. *
  560. * @method module:upload/filerepository~UploadAdapter#abort
  561. */
  562. /**
  563. * Object returned by {@link module:upload/filerepository~FileLoader#_createFilePromiseWrapper} method
  564. * to add more control over the initial file promise passed to {@link module:upload/filerepository~FileLoader}.
  565. *
  566. * @protected
  567. * @typedef {Object} module:upload/filerepository~FilePromiseWrapper
  568. * @property {Promise.<File>} promise Wrapper promise which can be chained for further processing.
  569. * @property {Function} rejecter Rejects the promise when called.
  570. * @property {Boolean} isFulfilled Whether original promise is already fulfilled.
  571. */