Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * The course file uploader.
18
 *
19
 * This module is used to upload files directly into the course.
20
 *
21
 * @module     core_courseformat/local/courseeditor/fileuploader
22
 * @copyright  2022 Ferran Recio <ferran@moodle.com>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
/**
27
 * @typedef {Object} Handler
28
 * @property {String} extension the handled extension or * for any
29
 * @property {String} message the handler message
30
 * @property {String} module the module name
31
 */
32
 
33
import Config from 'core/config';
34
import ModalSaveCancel from 'core/modal_save_cancel';
35
import ModalEvents from 'core/modal_events';
36
import Templates from 'core/templates';
37
import {getFirst} from 'core/normalise';
38
import {prefetchStrings} from 'core/prefetch';
39
import {getString, getStrings} from 'core/str';
40
import {getCourseEditor} from 'core_courseformat/courseeditor';
41
import {processMonitor} from 'core/process_monitor';
42
import {debounce} from 'core/utils';
43
 
44
// Uploading url.
45
const UPLOADURL = Config.wwwroot + '/course/dndupload.php';
46
const DEBOUNCETIMER = 500;
47
const USERCANIGNOREFILESIZELIMITS = -1;
48
 
49
/** @var {ProcessQueue} uploadQueue the internal uploadQueue instance.  */
50
let uploadQueue = null;
51
/** @var {Object} handlerManagers the courseId indexed loaded handler managers. */
52
let handlerManagers = {};
53
/** @var {Map} courseUpdates the pending course sections updates. */
54
let courseUpdates = new Map();
55
/** @var {Object} errors the error messages. */
56
let errors = null;
57
 
58
// Load global strings.
59
prefetchStrings('moodle', ['addresourceoractivity', 'upload']);
60
prefetchStrings('core_error', ['dndmaxbytes', 'dndread', 'dndupload', 'dndunkownfile']);
61
 
62
/**
63
 * Class to upload a file into the course.
64
 * @private
65
 */
66
class FileUploader {
67
    /**
68
     * Class constructor.
69
     *
70
     * @param {number} courseId the course id
71
     * @param {number} sectionId the section id
72
     * @param {number} sectionNum the section number
73
     * @param {File} fileInfo the file information object
74
     * @param {Handler} handler the file selected file handler
75
     */
76
    constructor(courseId, sectionId, sectionNum, fileInfo, handler) {
77
        this.courseId = courseId;
78
        this.sectionId = sectionId;
79
        this.sectionNum = sectionNum;
80
        this.fileInfo = fileInfo;
81
        this.handler = handler;
82
    }
83
 
84
    /**
85
     * Execute the file upload and update the state in the given process.
86
     *
87
     * @param {LoadingProcess} process the process to store the upload result
88
     */
89
    execute(process) {
90
        const fileInfo = this.fileInfo;
91
        const xhr = this._createXhrRequest(process);
92
        const formData = this._createUploadFormData();
93
 
94
        // Try reading the file to check it is not a folder, before sending it to the server.
95
        const reader = new FileReader();
96
        reader.onload = function() {
97
            // File was read OK - send it to the server.
98
            xhr.open("POST", UPLOADURL, true);
99
            xhr.send(formData);
100
        };
101
        reader.onerror = function() {
102
            // Unable to read the file (it is probably a folder) - display an error message.
103
            process.setError(errors.dndread);
104
        };
105
        if (fileInfo.size > 0) {
106
            // If this is a non-empty file, try reading the first few bytes.
107
            // This will trigger reader.onerror() for folders and reader.onload() for ordinary, readable files.
108
            reader.readAsText(fileInfo.slice(0, 5));
109
        } else {
110
            // If you call slice() on a 0-byte folder, before calling readAsText, then Firefox triggers reader.onload(),
111
            // instead of reader.onerror().
112
            // So, for 0-byte files, just call readAsText on the whole file (and it will trigger load/error functions as expected).
113
            reader.readAsText(fileInfo);
114
        }
115
    }
116
 
117
    /**
118
     * Returns the bind version of execute function.
119
     *
120
     * This method is used to queue the process into a ProcessQueue instance.
121
     *
122
     * @returns {Function} the bind function to execute the process
123
     */
124
    getExecutionFunction() {
125
        return this.execute.bind(this);
126
    }
127
 
128
    /**
129
     * Generate a upload XHR file request.
130
     *
131
     * @param {LoadingProcess} process the current process
132
     * @return {XMLHttpRequest} the XHR request
133
     */
134
    _createXhrRequest(process) {
135
        const xhr = new XMLHttpRequest();
136
        // Update the progress bar as the file is uploaded.
137
        xhr.upload.addEventListener(
138
            'progress',
139
            (event) => {
140
                if (event.lengthComputable) {
141
                    const percent = Math.round((event.loaded * 100) / event.total);
142
                    process.setPercentage(percent);
143
                }
144
            },
145
            false
146
        );
147
        // Wait for the AJAX call to complete.
148
        xhr.onreadystatechange = () => {
149
            if (xhr.readyState == 1) {
150
                // Add a 1% just to indicate that it is uploading.
151
                process.setPercentage(1);
152
            }
153
            // State 4 is DONE. Otherwise the connection is still ongoing.
154
            if (xhr.readyState != 4) {
155
                return;
156
            }
157
            if (xhr.status == 200) {
158
                var result = JSON.parse(xhr.responseText);
159
                if (result && result.error == 0) {
160
                    // All OK.
161
                    this._finishProcess(process);
162
                } else {
163
                    process.setError(result.error);
164
                }
165
            } else {
166
                process.setError(errors.dndupload);
167
            }
168
        };
169
        return xhr;
170
    }
171
 
172
    /**
173
     * Upload a file into the course.
174
     *
175
     * @return {FormData|null} the new form data object
176
     */
177
    _createUploadFormData() {
178
        const formData = new FormData();
179
        try {
180
            formData.append('repo_upload_file', this.fileInfo);
181
        } catch (error) {
182
            throw Error(error.dndread);
183
        }
184
        formData.append('sesskey', Config.sesskey);
185
        formData.append('course', this.courseId);
186
        formData.append('section', this.sectionNum);
187
        formData.append('module', this.handler.module);
188
        formData.append('type', 'Files');
189
        return formData;
190
    }
191
 
192
    /**
193
     * Finishes the current process.
194
     * @param {LoadingProcess} process the process
195
     */
196
    _finishProcess(process) {
197
        addRefreshSection(this.courseId, this.sectionId);
198
        process.setPercentage(100);
199
        process.finish();
200
    }
201
}
202
 
203
/**
204
 * The file handler manager class.
205
 *
206
 * @private
207
 */
208
class HandlerManager {
209
 
210
    /** @var {Object} lastHandlers the last handlers selected per each file extension. */
211
    lastHandlers = {};
212
 
213
    /** @var {Handler[]|null} allHandlers all the available handlers. */
214
    allHandlers = null;
215
 
216
    /**
217
     * Class constructor.
218
     *
219
     * @param {Number} courseId
220
     */
221
    constructor(courseId) {
222
        this.courseId = courseId;
223
        this.lastUploadId = 0;
224
        this.courseEditor = getCourseEditor(courseId);
225
        if (!this.courseEditor) {
226
            throw Error('Unkown course editor');
227
        }
228
        this.maxbytes = this.courseEditor.get('course')?.maxbytes ?? 0;
229
    }
230
 
231
    /**
232
     * Load the course file handlers.
233
     */
234
    async loadHandlers() {
235
        this.allHandlers = await this.courseEditor.getFileHandlersPromise();
236
    }
237
 
238
    /**
239
     * Extract the file extension from a fileInfo.
240
     *
241
     * @param {File} fileInfo
242
     * @returns {String} the file extension or an empty string.
243
     */
244
    getFileExtension(fileInfo) {
245
        let extension = '';
246
        const dotpos = fileInfo.name.lastIndexOf('.');
247
        if (dotpos != -1) {
248
            extension = fileInfo.name.substring(dotpos + 1, fileInfo.name.length).toLowerCase();
249
        }
250
        return extension;
251
    }
252
 
253
    /**
254
     * Check if the file is valid.
255
     *
256
     * @param {File} fileInfo the file info
257
     */
258
    validateFile(fileInfo) {
259
        if (this.maxbytes !== USERCANIGNOREFILESIZELIMITS && fileInfo.size > this.maxbytes) {
260
            throw Error(errors.dndmaxbytes);
261
        }
262
    }
263
 
264
    /**
265
     * Get the file handlers of an specific file.
266
     *
267
     * @param {File} fileInfo the file indo
268
     * @return {Array} Array of handlers
269
     */
270
    filterHandlers(fileInfo) {
271
        const extension = this.getFileExtension(fileInfo);
272
        return this.allHandlers.filter(handler => handler.extension == '*' || handler.extension == extension);
273
    }
274
 
275
    /**
276
     * Get the Handler to upload a specific file.
277
     *
278
     * It will ask the used if more than one handler is available.
279
     *
280
     * @param {File} fileInfo the file info
281
     * @returns {Promise<Handler|null>} the selected handler or null if the user cancel
282
     */
283
    async getFileHandler(fileInfo) {
284
        const fileHandlers = this.filterHandlers(fileInfo);
285
        if (fileHandlers.length == 0) {
286
            throw Error(errors.dndunkownfile);
287
        }
288
        let fileHandler = null;
289
        if (fileHandlers.length == 1) {
290
            fileHandler = fileHandlers[0];
291
        } else {
292
            fileHandler = await this.askHandlerToUser(fileHandlers, fileInfo);
293
        }
294
        return fileHandler;
295
    }
296
 
297
    /**
298
     * Ask the user to select a specific handler.
299
     *
300
     * @param {Handler[]} fileHandlers
301
     * @param {File} fileInfo the file info
302
     * @return {Promise<Handler>} the selected handler
303
     */
304
    async askHandlerToUser(fileHandlers, fileInfo) {
305
        const extension = this.getFileExtension(fileInfo);
306
        // Build the modal parameters from the event data.
307
        const modalParams = {
308
            title: getString('addresourceoractivity', 'moodle'),
309
            body: Templates.render(
310
                'core_courseformat/fileuploader',
311
                this.getModalData(
312
                    fileHandlers,
313
                    fileInfo,
314
                    this.lastHandlers[extension] ?? null
315
                )
316
            ),
317
            saveButtonText: getString('upload', 'moodle'),
318
        };
319
        // Create the modal.
320
        const modal = await this.modalBodyRenderedPromise(modalParams);
321
        const selectedHandler = await this.modalUserAnswerPromise(modal, fileHandlers);
322
        // Cancel action.
323
        if (selectedHandler === null) {
324
            return null;
325
        }
326
        // Save last selected handler.
327
        this.lastHandlers[extension] = selectedHandler.module;
328
        return selectedHandler;
329
    }
330
 
331
    /**
332
     * Generated the modal template data.
333
     *
334
     * @param {Handler[]} fileHandlers
335
     * @param {File} fileInfo the file info
336
     * @param {String|null} defaultModule the default module if any
337
     * @return {Object} the modal template data.
338
     */
339
    getModalData(fileHandlers, fileInfo, defaultModule) {
340
        const data = {
341
            filename: fileInfo.name,
342
            uploadid: ++this.lastUploadId,
343
            handlers: [],
344
        };
345
        let hasDefault = false;
346
        fileHandlers.forEach((handler, index) => {
347
            const isDefault = (defaultModule == handler.module);
348
            data.handlers.push({
349
                ...handler,
350
                selected: isDefault,
351
                labelid: `fileuploader_${data.uploadid}`,
352
                value: index,
353
            });
354
            hasDefault = hasDefault || isDefault;
355
        });
356
        if (!hasDefault && data.handlers.length > 0) {
357
            const lastHandler = data.handlers.pop();
358
            lastHandler.selected = true;
359
            data.handlers.push(lastHandler);
360
        }
361
        return data;
362
    }
363
 
364
    /**
365
     * Get the user handler choice.
366
     *
367
     * Wait for the user answer in the modal and resolve with the selected index.
368
     *
369
     * @param {Modal} modal the modal instance
370
     * @param {Handler[]} fileHandlers the availabvle file handlers
371
     * @return {Promise} with the option selected by the user.
372
     */
373
    modalUserAnswerPromise(modal, fileHandlers) {
374
        const modalBody = getFirst(modal.getBody());
375
        return new Promise((resolve, reject) => {
376
            modal.getRoot().on(
377
                ModalEvents.save,
378
                event => {
379
                    // Get the selected option.
380
                    const index = modalBody.querySelector('input:checked').value;
381
                    event.preventDefault();
382
                    modal.destroy();
383
                    if (!fileHandlers[index]) {
384
                        reject('Invalid handler selected');
385
                    }
386
                    resolve(fileHandlers[index]);
387
 
388
                }
389
            );
390
            modal.getRoot().on(
391
                ModalEvents.cancel,
392
                () => {
393
                    resolve(null);
394
                }
395
            );
396
        });
397
    }
398
 
399
    /**
400
     * Create a new modal and return a Promise to the body rendered.
401
     *
402
     * @param {Object} modalParams the modal params
403
     * @returns {Promise} the modal body rendered promise
404
     */
405
    modalBodyRenderedPromise(modalParams) {
406
        return new Promise((resolve, reject) => {
407
            ModalSaveCancel.create(modalParams).then((modal) => {
408
                modal.setRemoveOnClose(true);
409
                // Handle body loading event.
410
                modal.getRoot().on(ModalEvents.bodyRendered, () => {
411
                    resolve(modal);
412
                });
413
                // Configure some extra modal params.
414
                if (modalParams.saveButtonText !== undefined) {
415
                    modal.setSaveButtonText(modalParams.saveButtonText);
416
                }
417
                modal.show();
418
                return;
419
            }).catch(() => {
420
                reject(`Cannot load modal content`);
421
            });
422
        });
423
    }
424
}
425
 
426
/**
427
 * Add a section to refresh.
428
 *
429
 * @param {number} courseId the course id
430
 * @param {number} sectionId the seciton id
431
 */
432
function addRefreshSection(courseId, sectionId) {
433
    let refresh = courseUpdates.get(courseId);
434
    if (!refresh) {
435
        refresh = new Set();
436
    }
437
    refresh.add(sectionId);
438
    courseUpdates.set(courseId, refresh);
439
    refreshCourseEditors();
440
}
441
 
442
/**
443
 * Debounced processing all pending course refreshes.
444
 * @private
445
 */
446
const refreshCourseEditors = debounce(
447
    () => {
448
        const refreshes = courseUpdates;
449
        courseUpdates = new Map();
450
        refreshes.forEach((sectionIds, courseId) => {
451
            const courseEditor = getCourseEditor(courseId);
452
            if (!courseEditor) {
453
                return;
454
            }
455
            courseEditor.dispatch('sectionState', [...sectionIds]);
456
        });
457
    },
458
    DEBOUNCETIMER
459
);
460
 
461
/**
462
 * Load and return the course handler manager instance.
463
 *
464
 * @param {Number} courseId the course Id to load
465
 * @returns {Promise<HandlerManager>} promise of the the loaded handleManager
466
 */
467
async function loadCourseHandlerManager(courseId) {
468
    if (handlerManagers[courseId] !== undefined) {
469
        return handlerManagers[courseId];
470
    }
471
    const handlerManager = new HandlerManager(courseId);
472
    await handlerManager.loadHandlers();
473
    handlerManagers[courseId] = handlerManager;
474
    return handlerManagers[courseId];
475
}
476
 
477
/**
478
 * Load all the erros messages at once in the module "errors" variable.
479
 * @param {Number} courseId the course id
480
 */
481
async function loadErrorStrings(courseId) {
482
    if (errors !== null) {
483
        return;
484
    }
485
    const courseEditor = getCourseEditor(courseId);
486
    const maxbytestext = courseEditor.get('course')?.maxbytestext ?? '0';
487
 
488
    errors = {};
489
    const allStrings = [
490
        {key: 'dndmaxbytes', component: 'core_error', param: {size: maxbytestext}},
491
        {key: 'dndread', component: 'core_error'},
492
        {key: 'dndupload', component: 'core_error'},
493
        {key: 'dndunkownfile', component: 'core_error'},
494
    ];
11 efrain 495
 
1 efrain 496
    const loadedStrings = await getStrings(allStrings);
497
    allStrings.forEach(({key}, index) => {
498
        errors[key] = loadedStrings[index];
499
    });
500
}
501
 
502
/**
503
 * Start a batch file uploading into the course.
504
 *
505
 * @private
506
 * @param {number} courseId the course id.
507
 * @param {number} sectionId the section id.
508
 * @param {number} sectionNum the section number.
509
 * @param {File} fileInfo the file information object
510
 * @param {HandlerManager} handlerManager the course handler manager
511
 */
512
const queueFileUpload = async function(courseId, sectionId, sectionNum, fileInfo, handlerManager) {
513
    let handler;
514
    uploadQueue = await processMonitor.createProcessQueue();
515
    try {
516
        handlerManager.validateFile(fileInfo);
517
        handler = await handlerManager.getFileHandler(fileInfo);
518
    } catch (error) {
519
        uploadQueue.addError(fileInfo.name, error.message);
520
        return;
521
    }
522
    // If we don't have a handler means the user cancel the upload.
523
    if (!handler) {
524
        return;
525
    }
526
    const fileProcessor = new FileUploader(courseId, sectionId, sectionNum, fileInfo, handler);
527
    uploadQueue.addPending(fileInfo.name, fileProcessor.getExecutionFunction());
528
};
529
 
530
/**
531
 * Upload a file to the course.
532
 *
533
 * This method will show any necesary modal to handle the request.
534
 *
535
 * @param {number} courseId the course id
536
 * @param {number} sectionId the section id
537
 * @param {number} sectionNum the section number
538
 * @param {Array} files and array of files
539
 */
540
export const uploadFilesToCourse = async function(courseId, sectionId, sectionNum, files) {
541
    // Get the course handlers.
542
    const handlerManager = await loadCourseHandlerManager(courseId);
543
    await loadErrorStrings(courseId);
544
    for (let index = 0; index < files.length; index++) {
545
        const fileInfo = files[index];
546
        await queueFileUpload(courseId, sectionId, sectionNum, fileInfo, handlerManager);
547
    }
548
};