course/format/amd/src/local/courseeditor/fileuploader.js

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