filerepository.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /**
  2. * @license Copyright (c) 2003-2018, 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. loader.on( 'change:uploaded', () => {
  170. let aggregatedUploaded = 0;
  171. for ( const loader of this.loaders ) {
  172. aggregatedUploaded += loader.uploaded;
  173. }
  174. this.uploaded = aggregatedUploaded;
  175. } );
  176. loader.on( 'change:uploadTotal', () => {
  177. let aggregatedTotal = 0;
  178. for ( const loader of this.loaders ) {
  179. if ( loader.uploadTotal ) {
  180. aggregatedTotal += loader.uploadTotal;
  181. }
  182. }
  183. this.uploadTotal = aggregatedTotal;
  184. } );
  185. return loader;
  186. }
  187. /**
  188. * Destroys the given loader.
  189. *
  190. * @param {File|Promise|module:upload/filerepository~FileLoader} fileOrPromiseOrLoader File or Promise associated
  191. * with that loader or loader itself.
  192. */
  193. destroyLoader( fileOrPromiseOrLoader ) {
  194. const loader = fileOrPromiseOrLoader instanceof FileLoader ? fileOrPromiseOrLoader : this.getLoader( fileOrPromiseOrLoader );
  195. loader._destroy();
  196. this.loaders.remove( loader );
  197. this._loadersMap.forEach( ( value, key ) => {
  198. if ( value === loader ) {
  199. this._loadersMap.delete( key );
  200. }
  201. } );
  202. }
  203. /**
  204. * Registers or deregisters pending action bound with upload progress.
  205. *
  206. * @private
  207. */
  208. _updatePendingAction() {
  209. const pendingActions = this.editor.plugins.get( PendingActions );
  210. if ( this.loaders.length ) {
  211. if ( !this._pendingAction ) {
  212. const t = this.editor.t;
  213. const getMessage = value => `${ t( 'Upload in progress' ) } ${ parseInt( value ) }%.`;
  214. this._pendingAction = pendingActions.add( getMessage( this.uploadedPercent ) );
  215. this._pendingAction.bind( 'message' ).to( this, 'uploadedPercent', getMessage );
  216. }
  217. } else {
  218. pendingActions.remove( this._pendingAction );
  219. this._pendingAction = null;
  220. }
  221. }
  222. }
  223. mix( FileRepository, ObservableMixin );
  224. /**
  225. * File loader class.
  226. *
  227. * It is used to control the process of reading the file and uploading it using the specified upload adapter.
  228. */
  229. class FileLoader {
  230. /**
  231. * Creates a new instance of `FileLoader`.
  232. *
  233. * @param {Promise.<File>} filePromise A promise which resolves to a file instance.
  234. * @param {Function} uploadAdapterCreator The function which returns {@link module:upload/filerepository~UploadAdapter} instance.
  235. */
  236. constructor( filePromise, uploadAdapterCreator ) {
  237. /**
  238. * Unique id of FileLoader instance.
  239. *
  240. * @readonly
  241. * @member {Number}
  242. */
  243. this.id = uid();
  244. /**
  245. * Additional wrapper over the initial file promise passed to this loader.
  246. *
  247. * @private
  248. * @member {module:upload/filerepository~FilePromiseWrapper}
  249. */
  250. this._filePromiseWrapper = this._createFilePromiseWrapper( filePromise );
  251. /**
  252. * Adapter instance associated with this file loader.
  253. *
  254. * @private
  255. * @member {module:upload/filerepository~UploadAdapter}
  256. */
  257. this._adapter = uploadAdapterCreator( this );
  258. /**
  259. * FileReader used by FileLoader.
  260. *
  261. * @protected
  262. * @member {module:upload/filereader~FileReader}
  263. */
  264. this._reader = new FileReader();
  265. /**
  266. * Current status of FileLoader. It can be one of the following:
  267. *
  268. * * 'idle',
  269. * * 'reading',
  270. * * 'uploading',
  271. * * 'aborted',
  272. * * 'error'.
  273. *
  274. * When reading status can change in a following way:
  275. *
  276. * `idle` -> `reading` -> `idle`
  277. * `idle` -> `reading -> `aborted`
  278. * `idle` -> `reading -> `error`
  279. *
  280. * When uploading status can change in a following way:
  281. *
  282. * `idle` -> `uploading` -> `idle`
  283. * `idle` -> `uploading` -> `aborted`
  284. * `idle` -> `uploading` -> `error`
  285. *
  286. * @readonly
  287. * @observable
  288. * @member {String} #status
  289. */
  290. this.set( 'status', 'idle' );
  291. /**
  292. * Number of bytes uploaded.
  293. *
  294. * @readonly
  295. * @observable
  296. * @member {Number} #uploaded
  297. */
  298. this.set( 'uploaded', 0 );
  299. /**
  300. * Number of total bytes to upload.
  301. *
  302. * @readonly
  303. * @observable
  304. * @member {Number|null} #uploadTotal
  305. */
  306. this.set( 'uploadTotal', null );
  307. /**
  308. * Upload progress in percents.
  309. *
  310. * @readonly
  311. * @observable
  312. * @member {Number} #uploadedPercent
  313. */
  314. this.bind( 'uploadedPercent' ).to( this, 'uploaded', this, 'uploadTotal', ( uploaded, total ) => {
  315. return total ? ( uploaded / total * 100 ) : 0;
  316. } );
  317. /**
  318. * Response of the upload.
  319. *
  320. * @readonly
  321. * @observable
  322. * @member {Object|null} #uploadResponse
  323. */
  324. this.set( 'uploadResponse', null );
  325. }
  326. /**
  327. * Returns a `Promise` which resolves to a `File` instance associated with this file loader.
  328. *
  329. * @type {Promise.<File>}
  330. */
  331. get file() {
  332. if ( !this._filePromiseWrapper ) {
  333. // Loader was destroyed, return promise which resolves to null.
  334. return Promise.resolve( null );
  335. } else {
  336. // The `this._filePromiseWrapper.promise` is chained and not simply returned to handle a case when:
  337. //
  338. // * The `loader.file.then( ... )` is called by external code (returned promise is pending).
  339. // * Then `loader._destroy()` is called (call is synchronous) which destroys the `loader`.
  340. // * Promise returned by the first `loader.file.then( ... )` call is resolved.
  341. //
  342. // Returning `this._filePromiseWrapper.promise` will still resolve to a `File` instance so there
  343. // is an additional check needed in the chain to see if `loader` was destroyed in the meantime.
  344. return this._filePromiseWrapper.promise.then( file => this._filePromiseWrapper ? file : null );
  345. }
  346. }
  347. /**
  348. * Reads file using {@link module:upload/filereader~FileReader}.
  349. *
  350. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-read-wrong-status` when status
  351. * is different than `idle`.
  352. *
  353. * Example usage:
  354. *
  355. * fileLoader.read()
  356. * .then( data => { ... } )
  357. * .catch( err => {
  358. * if ( err === 'aborted' ) {
  359. * console.log( 'Reading aborted.' );
  360. * } else {
  361. * console.log( 'Reading error.', err );
  362. * }
  363. * } );
  364. *
  365. * @returns {Promise.<String>} Returns promise that will be resolved with read data. Promise will be rejected if error
  366. * occurs or if read process is aborted.
  367. */
  368. read() {
  369. if ( this.status != 'idle' ) {
  370. throw new CKEditorError( 'filerepository-read-wrong-status: You cannot call read if the status is different than idle.' );
  371. }
  372. this.status = 'reading';
  373. return this._filePromiseWrapper.promise
  374. .then( file => this._reader.read( file ) )
  375. .then( data => {
  376. this.status = 'idle';
  377. return data;
  378. } )
  379. .catch( err => {
  380. if ( err === 'aborted' ) {
  381. this.status = 'aborted';
  382. throw 'aborted';
  383. }
  384. this.status = 'error';
  385. throw this._reader.error ? this._reader.error : err;
  386. } );
  387. }
  388. /**
  389. * Reads file using the provided {@link module:upload/filerepository~UploadAdapter}.
  390. *
  391. * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-upload-wrong-status` when status
  392. * is different than `idle`.
  393. * Example usage:
  394. *
  395. * fileLoader.upload()
  396. * .then( data => { ... } )
  397. * .catch( e => {
  398. * if ( e === 'aborted' ) {
  399. * console.log( 'Uploading aborted.' );
  400. * } else {
  401. * console.log( 'Uploading error.', e );
  402. * }
  403. * } );
  404. *
  405. * @returns {Promise.<Object>} Returns promise that will be resolved with response data. Promise will be rejected if error
  406. * occurs or if read process is aborted.
  407. */
  408. upload() {
  409. if ( this.status != 'idle' ) {
  410. throw new CKEditorError( 'filerepository-upload-wrong-status: You cannot call upload if the status is different than idle.' );
  411. }
  412. this.status = 'uploading';
  413. return this._filePromiseWrapper.promise
  414. .then( () => this._adapter.upload() )
  415. .then( data => {
  416. this.uploadResponse = data;
  417. this.status = 'idle';
  418. return data;
  419. } )
  420. .catch( err => {
  421. if ( this.status === 'aborted' ) {
  422. throw 'aborted';
  423. }
  424. this.status = 'error';
  425. throw err;
  426. } );
  427. }
  428. /**
  429. * Aborts loading process.
  430. */
  431. abort() {
  432. const status = this.status;
  433. this.status = 'aborted';
  434. if ( !this._filePromiseWrapper.isFulfilled ) {
  435. this._filePromiseWrapper.rejecter( 'aborted' );
  436. } else if ( status == 'reading' ) {
  437. this._reader.abort();
  438. } else if ( status == 'uploading' && this._adapter.abort ) {
  439. this._adapter.abort();
  440. }
  441. this._destroy();
  442. }
  443. /**
  444. * Performs cleanup.
  445. *
  446. * @private
  447. */
  448. _destroy() {
  449. this._filePromiseWrapper = undefined;
  450. this._reader = undefined;
  451. this._adapter = undefined;
  452. this.data = undefined;
  453. this.uploadResponse = undefined;
  454. }
  455. /**
  456. * Wraps a given file promise into another promise giving additional
  457. * control (resolving, rejecting, checking if fulfilled) over it.
  458. *
  459. * @private
  460. * @param filePromise The initial file promise to be wrapped.
  461. * @returns {module:upload/filerepository~FilePromiseWrapper}
  462. */
  463. _createFilePromiseWrapper( filePromise ) {
  464. const wrapper = {};
  465. wrapper.promise = new Promise( ( resolve, reject ) => {
  466. wrapper.resolver = resolve;
  467. wrapper.rejecter = reject;
  468. wrapper.isFulfilled = false;
  469. filePromise
  470. .then( file => {
  471. wrapper.isFulfilled = true;
  472. resolve( file );
  473. } )
  474. .catch( err => {
  475. wrapper.isFulfilled = true;
  476. reject( err );
  477. } );
  478. } );
  479. return wrapper;
  480. }
  481. }
  482. mix( FileLoader, ObservableMixin );
  483. /**
  484. * Upload adapter interface used by the {@link module:upload/filerepository~FileRepository file repository}
  485. * to handle file upload. An upload adapter is a bridge between the editor and server that handles file uploads.
  486. * It should contain a logic necessary to initiate an upload process and monitor its progress.
  487. *
  488. * Learn how to develop your own upload adapter for CKEditor 5 in the
  489. * {@glink framework/guides/deep-dive/upload-adapter "Custom upload adapter" guide}.
  490. *
  491. * @interface UploadAdapter
  492. */
  493. /**
  494. * Executes the upload process.
  495. * This method should return a promise that will resolve when data will be uploaded to server. Promise should be
  496. * resolved with an object containing information about uploaded file:
  497. *
  498. * {
  499. * default: 'http://server/default-size.image.png'
  500. * }
  501. *
  502. * Additionally, other image sizes can be provided:
  503. *
  504. * {
  505. * default: 'http://server/default-size.image.png',
  506. * '160': 'http://server/size-160.image.png',
  507. * '500': 'http://server/size-500.image.png',
  508. * '1000': 'http://server/size-1000.image.png',
  509. * '1052': 'http://server/default-size.image.png'
  510. * }
  511. *
  512. * NOTE: When returning multiple images, the widest returned one should equal the default one. It is essential to
  513. * correctly set `width` attribute of the image. See this discussion:
  514. * https://github.com/ckeditor/ckeditor5-easy-image/issues/4 for more information.
  515. *
  516. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  517. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  518. *
  519. * @method module:upload/filerepository~UploadAdapter#upload
  520. * @returns {Promise.<Object>} Promise that should be resolved when data is uploaded.
  521. */
  522. /**
  523. * Aborts the upload process.
  524. * After aborting it should reject promise returned from {@link #upload upload()}.
  525. *
  526. * Take a look at {@link module:upload/filerepository~UploadAdapter example Adapter implementation} and
  527. * {@link module:upload/filerepository~FileRepository#createUploadAdapter createUploadAdapter method}.
  528. *
  529. * @method module:upload/filerepository~UploadAdapter#abort
  530. */
  531. /**
  532. * Object returned by {@link module:upload/filerepository~FileLoader#_createFilePromiseWrapper} method
  533. * to add more control over the initial file promise passed to {@link module:upload/filerepository~FileLoader}.
  534. *
  535. * @typedef {Object} module:upload/filerepository~FilePromiseWrapper
  536. * @property {Promise.<File>} promise Wrapper promise which can be chained for further processing.
  537. * @property {Function} resolver Resolves the promise when called.
  538. * @property {Function} rejecter Rejects the promise when called.
  539. * @property {Boolean} isFulfilled Whether original promise is already fulfilled.
  540. */