lib/editor/tiny/amd/src/uploader.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. * Tiny Media plugin for Moodle.
  17. *
  18. * @module editor_tiny/uploader
  19. * @copyright 2022 Andrew Lyons <andrew@nicols.co.uk>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import {
  23. notifyUploadStarted,
  24. notifyUploadCompleted,
  25. } from 'core_form/events';
  26. import {getFilePicker} from 'editor_tiny/options';
  27. // This image uploader is based on advice given at:
  28. // https://www.tiny.cloud/docs/tinymce/6/upload-images/
  29. export default (editor, filePickerType, blob, fileName, progress) => new Promise((resolve, reject) => {
  30. notifyUploadStarted(editor.targetElm.id);
  31. const xhr = new XMLHttpRequest();
  32. // Add the progress handler.
  33. xhr.upload.addEventListener('progress', (e) => {
  34. progress(e.loaded / e.total * 100);
  35. });
  36. xhr.addEventListener('load', () => {
  37. if (xhr.status === 403) {
  38. reject({
  39. message: `HTTP error: ${xhr.status}`,
  40. remove: true,
  41. });
  42. return;
  43. }
  44. if (xhr.status < 200 || xhr.status >= 300) {
  45. reject(`HTTP Error: ${xhr.status}`);
  46. return;
  47. }
  48. const response = JSON.parse(xhr.responseText);
  49. if (!response) {
  50. reject(`Invalid JSON: ${xhr.responseText}`);
  51. return;
  52. }
  53. notifyUploadCompleted(editor.targetElm.id);
  54. let location;
  55. if (response.url) {
  56. location = response.url;
  57. } else if (response.event && response.event === 'fileexists' && response.newfile) {
  58. // A file with this name is already in use here - rename to avoid conflict.
  59. // Chances are, it's a different image (stored in a different folder on the user's computer).
  60. // If the user wants to reuse an existing image, they can copy/paste it within the editor.
  61. location = response.newfile.url;
  62. }
  63. if (location && typeof location === 'string') {
  64. resolve(location);
  65. return;
  66. }
  67. // Try to parse the error response into a JSON object.
  68. const errorString = xhr.responseText;
  69. let output = '';
  70. try {
  71. output = JSON.parse(errorString);
  72. } catch (error) {
  73. // If the JSON parsing process returns an error, then it returns the original.
  74. output = errorString;
  75. }
  76. reject(output);
  77. });
  78. xhr.addEventListener('error', () => {
  79. reject({
  80. message: `Upload failed due to an XHR transport error. Code: ${xhr.status}`,
  81. remove: true,
  82. });
  83. });
  84. const formData = new FormData();
  85. const options = getFilePicker(editor, filePickerType);
  86. formData.append('repo_upload_file', blob, fileName);
  87. formData.append('itemid', options.itemid);
  88. Object.values(options.repositories).some((repository) => {
  89. if (repository.type === 'upload') {
  90. formData.append('repo_id', repository.id);
  91. return true;
  92. }
  93. return false;
  94. });
  95. formData.append('env', options.env);
  96. formData.append('sesskey', M.cfg.sesskey);
  97. formData.append('client_id', options.client_id);
  98. formData.append('savepath', options.savepath ?? '/');
  99. formData.append('ctx_id', options.context.id);
  100. // Accepted types can be either a string or an array, but an array is
  101. // expected in the processing script, so make sure we are sending an array.
  102. const acceptedTypes = options.accepted_types;
  103. if (Array.isArray(acceptedTypes)) {
  104. acceptedTypes.forEach(function(type) {
  105. formData.append('accepted_types[]', type);
  106. });
  107. } else {
  108. formData.append('accepted_types[]', acceptedTypes);
  109. }
  110. xhr.open('POST', `${M.cfg.wwwroot}/repository/repository_ajax.php?action=upload`, true);
  111. xhr.send(formData);
  112. });