filerepository.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module upload/filerepository
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import PendingActions from '@ckeditor/ckeditor5-core/src/pendingactions';
  10. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  11. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  12. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  13. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  14. import log from '@ckeditor/ckeditor5-utils/src/log';
  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 adpter" 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. log.error( 'filerepository-no-upload-adapter: Upload adapter is not defined.' );
  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.then( file => {
  166. this._loadersMap.set( file, loader );
  167. } );
  168. }
  169. // Catch the file promise rejection. If there are no `catch` clause, the browser
  170. // will throw an error (see https://github.com/ckeditor/ckeditor5-upload/pull/90).
  171. loader.file.catch( () => {
  172. // The error will be handled by `FileLoader` so no action is required here.
  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. * @private
  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. * Reads file using {@link module:upload/filereader~FileReader}.
  354. *
  355. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-read-wrong-status` when status
  356. * is different than `idle`.
  357. *
  358. * Example usage:
  359. *
  360. * fileLoader.read()
  361. * .then( data => { ... } )
  362. * .catch( err => {
  363. * if ( err === 'aborted' ) {
  364. * console.log( 'Reading aborted.' );
  365. * } else {
  366. * console.log( 'Reading error.', err );
  367. * }
  368. * } );
  369. *
  370. * @returns {Promise.<String>} Returns promise that will be resolved with read data. Promise will be rejected if error
  371. * occurs or if read process is aborted.
  372. */
  373. read() {
  374. if ( this.status != 'idle' ) {
  375. throw new CKEditorError( 'filerepository-read-wrong-status: You cannot call read if the status is different than idle.' );
  376. }
  377. this.status = 'reading';
  378. return this._filePromiseWrapper.promise
  379. .then( file => this._reader.read( file ) )
  380. .then( data => {
  381. this.status = 'idle';
  382. return data;
  383. } )
  384. .catch( err => {
  385. if ( err === 'aborted' ) {
  386. this.status = 'aborted';
  387. throw 'aborted';
  388. }
  389. this.status = 'error';
  390. throw this._reader.error ? this._reader.error : err;
  391. } );
  392. }
  393. /**
  394. * Reads file using the provided {@link module:upload/filerepository~UploadAdapter}.
  395. *
  396. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-upload-wrong-status` when status
  397. * is different than `idle`.
  398. * Example usage:
  399. *
  400. * fileLoader.upload()
  401. * .then( data => { ... } )
  402. * .catch( e => {
  403. * if ( e === 'aborted' ) {
  404. * console.log( 'Uploading aborted.' );
  405. * } else {
  406. * console.log( 'Uploading error.', e );
  407. * }
  408. * } );
  409. *
  410. * @returns {Promise.<Object>} Returns promise that will be resolved with response data. Promise will be rejected if error
  411. * occurs or if read process is aborted.
  412. */
  413. upload() {
  414. if ( this.status != 'idle' ) {
  415. throw new CKEditorError( 'filerepository-upload-wrong-status: You cannot call upload if the status is different than idle.' );
  416. }
  417. this.status = 'uploading';
  418. return this._filePromiseWrapper.promise
  419. .then( () => this._adapter.upload() )
  420. .then( data => {
  421. this.uploadResponse = data;
  422. this.status = 'idle';
  423. return data;
  424. } )
  425. .catch( err => {
  426. if ( this.status === 'aborted' ) {
  427. throw 'aborted';
  428. }
  429. this.status = 'error';
  430. throw err;
  431. } );
  432. }
  433. /**
  434. * Aborts loading process.
  435. */
  436. abort() {
  437. const status = this.status;
  438. this.status = 'aborted';
  439. if ( !this._filePromiseWrapper.isFulfilled ) {
  440. this._filePromiseWrapper.rejecter( 'aborted' );
  441. } else if ( status == 'reading' ) {
  442. this._reader.abort();
  443. } else if ( status == 'uploading' && this._adapter.abort ) {
  444. this._adapter.abort();
  445. }
  446. this._destroy();
  447. }
  448. /**
  449. * Performs cleanup.
  450. *
  451. * @private
  452. */
  453. _destroy() {
  454. this._filePromiseWrapper = undefined;
  455. this._reader = undefined;
  456. this._adapter = undefined;
  457. this.data = undefined;
  458. this.uploadResponse = undefined;
  459. }
  460. /**
  461. * Wraps a given file promise into another promise giving additional
  462. * control (resolving, rejecting, checking if fulfilled) over it.
  463. *
  464. * @private
  465. * @param filePromise The initial file promise to be wrapped.
  466. * @returns {module:upload/filerepository~FilePromiseWrapper}
  467. */
  468. _createFilePromiseWrapper( filePromise ) {
  469. const wrapper = {};
  470. wrapper.promise = new Promise( ( resolve, reject ) => {
  471. wrapper.resolver = resolve;
  472. wrapper.rejecter = reject;
  473. wrapper.isFulfilled = false;
  474. filePromise
  475. .then( file => {
  476. wrapper.isFulfilled = true;
  477. resolve( file );
  478. } )
  479. .catch( err => {
  480. wrapper.isFulfilled = true;
  481. reject( err );
  482. } );
  483. } );
  484. return wrapper;
  485. }
  486. }
  487. mix( FileLoader, ObservableMixin );
  488. /**
  489. * Upload adapter interface used by the {@link module:upload/filerepository~FileRepository file repository}
  490. * to handle file upload. An upload adapter is a bridge between the editor and server that handles file uploads.
  491. * It should contain a logic necessary to initiate an upload process and monitor its progress.
  492. *
  493. * Learn how to develop your own upload adapter for CKEditor 5 in the
  494. * {@glink framework/guides/deep-dive/upload-adapter "Custom upload adapter" guide}.
  495. *
  496. * @interface UploadAdapter
  497. */
  498. /**
  499. * Executes the upload process.
  500. * This method should return a promise that will resolve when data will be uploaded to server. Promise should be
  501. * resolved with an object containing information about uploaded file:
  502. *
  503. * {
  504. * default: 'http://server/default-size.image.png'
  505. * }
  506. *
  507. * Additionally, other image sizes can be provided:
  508. *
  509. * {
  510. * default: 'http://server/default-size.image.png',
  511. * '160': 'http://server/size-160.image.png',
  512. * '500': 'http://server/size-500.image.png',
  513. * '1000': 'http://server/size-1000.image.png',
  514. * '1052': 'http://server/default-size.image.png'
  515. * }
  516. *
  517. * NOTE: When returning multiple images, the widest returned one should equal the default one. It is essential to
  518. * correctly set `width` attribute of the image. See this discussion:
  519. * https://github.com/ckeditor/ckeditor5-easy-image/issues/4 for more information.
  520. *
  521. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  522. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  523. *
  524. * @method module:upload/filerepository~UploadAdapter#upload
  525. * @returns {Promise.<Object>} Promise that should be resolved when data is uploaded.
  526. */
  527. /**
  528. * Aborts the upload process.
  529. * After aborting it should reject promise returned from {@link #upload upload()}.
  530. *
  531. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  532. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  533. *
  534. * @method module:upload/filerepository~UploadAdapter#abort
  535. */
  536. /**
  537. * Object returned by {@link module:upload/filerepository~FileLoader#_createFilePromiseWrapper} method
  538. * to add more control over the initial file promise passed to {@link module:upload/filerepository~FileLoader}.
  539. *
  540. * @typedef {Object} module:upload/filerepository~FilePromiseWrapper
  541. * @property {Promise.<File>} promise Wrapper promise which can be chained for further processing.
  542. * @property {Function} resolver Resolves the promise when called.
  543. * @property {Function} rejecter Rejects the promise when called.
  544. * @property {Boolean} isFulfilled Whether original promise is already fulfilled.
  545. */