| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528 |
- /**
- * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
- * For licensing, see LICENSE.md.
- */
- /**
- * @module upload/filerepository
- */
- import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
- import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
- import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
- import Collection from '@ckeditor/ckeditor5-utils/src/collection';
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
- import log from '@ckeditor/ckeditor5-utils/src/log';
- import FileReader from './filereader.js';
- import uid from '@ckeditor/ckeditor5-utils/src/uid.js';
- /**
- * File repository plugin. A central point for managing file upload.
- *
- * To use it, first you need an upload adapter. Upload adapter's job is to handle communication with the server
- * (sending the file and handling server's response). You can use one of the existing plugins introducing upload adapters
- * (e.g. {@link module:easy-image/cloudservicesuploadadapter~CloudServicesUploadAdapter} or
- * {@link module:adapter-ckfinder/uploadadapter~CKFinderUploadAdapter}) or write your own one
- * (which boils down to setting the {@link ~FileRepository#createAdapter} factory function – see
- * {@link ~Adapter `Adapter` interface} documentation).
- *
- * Then, you can use {@link ~FileRepository#createLoader `createLoader()`} and the returned {@link ~FileLoader} instance to
- * load and upload files.
- *
- * @extends module:core/plugin~Plugin
- */
- export default class FileRepository extends Plugin {
- /**
- * @inheritDoc
- */
- static get pluginName() {
- return 'FileRepository';
- }
- /**
- * @inheritDoc
- */
- init() {
- /**
- * Collection of loaders associated with this repository.
- *
- * @member {module:utils/collection~Collection} #loaders
- */
- this.loaders = new Collection();
- /**
- * A factory function which should be defined before using `FileRepository`.
- *
- * It should return a new instance of {@link module:upload/filerepository~Adapter} that will be used to upload files.
- * {@link module:upload/filerepository~FileLoader} instance associated with the adapter
- * will be passed to that function.
- *
- * For more information and example see {@link module:upload/filerepository~Adapter}.
- *
- * @member {Function} #createAdapter
- */
- /**
- * Number of bytes uploaded.
- *
- * @readonly
- * @observable
- * @member {Number} #uploaded
- */
- this.set( 'uploaded', 0 );
- /**
- * Number of total bytes to upload.
- *
- * It might be different than the file size because of headers and additional data.
- * It contains `null` if value is not available yet, so it's better to use {@link #uploadedPercent} to monitor
- * the progress.
- *
- * @readonly
- * @observable
- * @member {Number|null} #uploadTotal
- */
- this.set( 'uploadTotal', null );
- /**
- * Upload progress in percents.
- *
- * @readonly
- * @observable
- * @member {Number} #uploadedPercent
- */
- this.bind( 'uploadedPercent' ).to( this, 'uploaded', this, 'uploadTotal', ( uploaded, total ) => {
- return total ? ( uploaded / total * 100 ) : 0;
- } );
- }
- afterInit() {
- if ( !this.createAdapter ) {
- /**
- * You need to enable an upload adapter in order to be able to upload files.
- *
- * This warning shows up when {@link module:upload/filerepository~FileRepository} is being used
- * without {@link #createAdapter definining an upload adapter}.
- *
- * If you see this warning when using one of the {@glink builds/index CKEditor 5 Builds}
- * it means that you did not configure any of the upload adapters available by default in those builds.
- * See:
- *
- * * {@link module:core/editor/editorconfig~EditorConfig#cloudServices `config.cloudServices`} for
- * Easy Image with Cloud Services integration,
- * * {@link module:core/editor/editorconfig~EditorConfig#ckfinder `config.ckfinder`} for CKFinder
- * file upload integration.
- *
- * If you do not need file upload functionality at all and you use one of the builds, you can disable the built-in
- * upload adapters to hide this warning:
- *
- * ClassicEditor
- * .create( document.querySelector( '#editor' ), {
- * removePlugins: [ 'EasyImage', 'CKFinderUploadAdapter' ]
- * } )
- * .then( ... )
- * .catch( ... );
- *
- * If you wish to implement your own upload adapter refer to the {@link ~Adapter `Adapter` interface} documentation.
- *
- * @error filerepository-no-adapter
- */
- log.warn( 'filerepository-no-adapter: Upload adapter is not defined.' );
- return null;
- }
- }
- /**
- * Returns the loader associated with specified file.
- *
- * To get loader by id use `fileRepository.loaders.get( id )`.
- *
- * @param {File} file Native file handle.
- * @returns {module:upload/filerepository~FileLoader|null}
- */
- getLoader( file ) {
- for ( const loader of this.loaders ) {
- if ( loader.file == file ) {
- return loader;
- }
- }
- return null;
- }
- /**
- * Creates a loader instance for the given file.
- *
- * Requires {@link #createAdapter} factory to be defined.
- *
- * @param {File} file Native File object.
- * @returns {module:upload/filerepository~FileLoader|null}
- */
- createLoader( file ) {
- if ( !this.createAdapter ) {
- log.error( 'filerepository-no-adapter: Upload adapter is not defined.' );
- return null;
- }
- const loader = new FileLoader( file );
- loader._adapter = this.createAdapter( loader );
- this.loaders.add( loader );
- loader.on( 'change:uploaded', () => {
- let aggregatedUploaded = 0;
- for ( const loader of this.loaders ) {
- aggregatedUploaded += loader.uploaded;
- }
- this.uploaded = aggregatedUploaded;
- } );
- loader.on( 'change:uploadTotal', () => {
- let aggregatedTotal = 0;
- for ( const loader of this.loaders ) {
- if ( loader.uploadTotal ) {
- aggregatedTotal += loader.uploadTotal;
- }
- }
- this.uploadTotal = aggregatedTotal;
- } );
- return loader;
- }
- /**
- * Destroys the given loader.
- *
- * @param {File|module:upload/filerepository~FileLoader} fileOrLoader File associated with that loader or loader
- * itself.
- */
- destroyLoader( fileOrLoader ) {
- const loader = fileOrLoader instanceof FileLoader ? fileOrLoader : this.getLoader( fileOrLoader );
- loader._destroy();
- this.loaders.remove( loader );
- }
- }
- mix( FileRepository, ObservableMixin );
- /**
- * File loader class.
- * It is used to control the process of file reading and uploading using specified adapter.
- */
- class FileLoader {
- /**
- * Creates a new instance of `FileLoader`.
- *
- * @param {File} file A native file instance.
- * @param {module:upload/filerepository~Adapter} adapter
- */
- constructor( file, adapter ) {
- /**
- * Unique id of FileLoader instance.
- *
- * @readonly
- * @member {Number}
- */
- this.id = uid();
- /**
- * A `File` instance associated with this file loader.
- *
- * @readonly
- * @member {File}
- */
- this.file = file;
- /**
- * Adapter instance associated with this file loader.
- *
- * @private
- * @member {module:upload/filerepository~Adapter}
- */
- this._adapter = adapter;
- /**
- * FileReader used by FileLoader.
- *
- * @protected
- * @member {module:upload/filereader~FileReader}
- */
- this._reader = new FileReader();
- /**
- * Current status of FileLoader. It can be one of the following:
- *
- * * 'idle',
- * * 'reading',
- * * 'uploading',
- * * 'aborted',
- * * 'error'.
- *
- * When reading status can change in a following way:
- *
- * `idle` -> `reading` -> `idle`
- * `idle` -> `reading -> `aborted`
- * `idle` -> `reading -> `error`
- *
- * When uploading status can change in a following way:
- *
- * `idle` -> `uploading` -> `idle`
- * `idle` -> `uploading` -> `aborted`
- * `idle` -> `uploading` -> `error`
- *
- * @readonly
- * @observable
- * @member {String} #status
- */
- this.set( 'status', 'idle' );
- /**
- * Number of bytes uploaded.
- *
- * @readonly
- * @observable
- * @member {Number} #uploaded
- */
- this.set( 'uploaded', 0 );
- /**
- * Number of total bytes to upload.
- *
- * @readonly
- * @observable
- * @member {Number|null} #uploadTotal
- */
- this.set( 'uploadTotal', null );
- /**
- * Upload progress in percents.
- *
- * @readonly
- * @observable
- * @member {Number} #uploadedPercent
- */
- this.bind( 'uploadedPercent' ).to( this, 'uploaded', this, 'uploadTotal', ( uploaded, total ) => {
- return total ? ( uploaded / total * 100 ) : 0;
- } );
- /**
- * Response of the upload.
- *
- * @readonly
- * @observable
- * @member {Object|null} #uploadResponse
- */
- this.set( 'uploadResponse', null );
- }
- /**
- * Reads file using {@link module:upload/filereader~FileReader}.
- *
- * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-read-wrong-status` when status
- * is different than `idle`.
- *
- * Example usage:
- *
- * fileLoader.read()
- * .then( data => { ... } )
- * .catch( err => {
- * if ( err === 'aborted' ) {
- * console.log( 'Reading aborted.' );
- * } else {
- * console.log( 'Reading error.', err );
- * }
- * } );
- *
- * @returns {Promise} Returns promise that will be resolved with read data. Promise will be rejected if error
- * occurs or if read process is aborted.
- */
- read() {
- if ( this.status != 'idle' ) {
- throw new CKEditorError( 'filerepository-read-wrong-status: You cannot call read if the status is different than idle.' );
- }
- this.status = 'reading';
- return this._reader.read( this.file )
- .then( data => {
- this.status = 'idle';
- return data;
- } )
- .catch( err => {
- if ( err === 'aborted' ) {
- this.status = 'aborted';
- throw 'aborted';
- }
- this.status = 'error';
- throw this._reader.error;
- } );
- }
- /**
- * Reads file using the provided {@link module:upload/filerepository~Adapter}.
- *
- * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `filerepository-upload-wrong-status` when status
- * is different than `idle`.
- * Example usage:
- *
- * fileLoader.upload()
- * .then( data => { ... } )
- * .catch( e => {
- * if ( e === 'aborted' ) {
- * console.log( 'Uploading aborted.' );
- * } else {
- * console.log( 'Uploading error.', e );
- * }
- * } );
- *
- * @returns {Promise} Returns promise that will be resolved with response data. Promise will be rejected if error
- * occurs or if read process is aborted.
- */
- upload() {
- if ( this.status != 'idle' ) {
- throw new CKEditorError( 'filerepository-upload-wrong-status: You cannot call upload if the status is different than idle.' );
- }
- this.status = 'uploading';
- return this._adapter.upload()
- .then( data => {
- this.uploadResponse = data;
- this.status = 'idle';
- return data;
- } )
- .catch( err => {
- if ( this.status === 'aborted' ) {
- throw 'aborted';
- }
- this.status = 'error';
- throw err;
- } );
- }
- /**
- * Aborts loading process.
- */
- abort() {
- const status = this.status;
- this.status = 'aborted';
- if ( status == 'reading' ) {
- this._reader.abort();
- }
- if ( status == 'uploading' && this._adapter.abort ) {
- this._adapter.abort();
- }
- this._destroy();
- }
- /**
- * Performs cleanup.
- *
- * @private
- */
- _destroy() {
- this._reader = undefined;
- this._adapter = undefined;
- this.data = undefined;
- this.uploadResponse = undefined;
- this.file = undefined;
- }
- }
- mix( FileLoader, ObservableMixin );
- /**
- * Adapter interface used by FileRepository to handle file upload. Adapter is a bridge between the editor and server that
- * handles file uploads. It should contain logic necessary to initiate upload process and monitor its progress.
- *
- * It should implement two methods:
- *
- * * {@link module:upload/filerepository~Adapter#upload `upload()`},
- * * {@link module:upload/filerepository~Adapter#abort `abort()`}.
- *
- * Example adapter implementation:
- *
- * class Adapter {
- * constructor( loader ) {
- * // Save Loader instance to update upload progress.
- * this.loader = loader;
- * }
- *
- * upload() {
- * // Update loader's progress.
- * server.onUploadProgress( data => {
- * loader.uploadTotal = data.total;
- * loader.uploaded = data.uploaded;
- * } ):
- *
- * // Return promise that will be resolved when file is uploaded.
- * return server.upload( loader.file );
- * }
- *
- * abort() {
- * // Reject promise returned from upload() method.
- * server.abortUpload();
- * }
- * }
- *
- * Then adapter can be set to be used by {@link module:upload/filerepository~FileRepository FileRepository}:
- *
- * editor.plugins.get( 'FileRepository' ).createAdapter = function( loader ) {
- * return new Adapter( loader );
- * };
- *
- * @interface Adapter
- */
- /**
- * Executes the upload process.
- * This method should return a promise that will resolve when data will be uploaded to server. Promise should be
- * resolved with an object containing information about uploaded file:
- *
- * {
- * default: 'http://server/default-size.image.png'
- * }
- *
- * Additionally, other image sizes can be provided:
- *
- * {
- * default: 'http://server/default-size.image.png',
- * '160': 'http://server/size-160.image.png',
- * '500': 'http://server/size-500.image.png',
- * '1000': 'http://server/size-1000.image.png'
- * }
- *
- * Take a look at {@link module:upload/filerepository~Adapter example Adapter implementation} and
- * {@link module:upload/filerepository~FileRepository#createAdapter createAdapter method}.
- *
- * @method module:upload/filerepository~Adapter#upload
- * @returns {Promise} Promise that should be resolved when data is uploaded.
- */
- /**
- * Aborts the upload process.
- * After aborting it should reject promise returned from {@link #upload upload()}.
- *
- * Take a look at {@link module:upload/filerepository~Adapter example Adapter implementation} and
- * {@link module:upload/filerepository~FileRepository#createAdapter createAdapter method}.
- *
- * @method module:upload/filerepository~Adapter#abort
- */
|