summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/services/upload_helpers.js
blob: f5785397bf036aa028f1c09c168664ed6fcdc1ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import { VARIANT_DANGER } from '~/alert';
import axios from '~/lib/utils/axios_utils';
import { __, sprintf } from '~/locale';
import { bytesToMiB } from '~/lib/utils/number_utils';
import TappablePromise from '~/lib/utils/tappable_promise';
import { ALERT_EVENT } from '../constants';

const chain = (editor) => editor.chain().setMeta('preventAutolink', true);

const findUploadedFilePosition = (editor, filename) => {
  let position;

  editor.view.state.doc.descendants((descendant, pos) => {
    if (descendant.attrs.uploading === filename) {
      position = pos;
      return false;
    }

    for (const mark of descendant.marks) {
      if (mark.type.name === 'link' && mark.attrs.uploading === filename) {
        position = pos + 1;
        return false;
      }
    }

    return true;
  });

  return position;
};

export const acceptedMimes = {
  drawioDiagram: {
    mimes: ['image/svg+xml'],
    ext: 'drawio.svg',
  },
  image: {
    mimes: [
      'image/jpeg',
      'image/png',
      'image/gif',
      'image/svg+xml',
      'image/webp',
      'image/tiff',
      'image/bmp',
      'image/vnd.microsoft.icon',
      'image/x-icon',
    ],
  },
  audio: {
    mimes: [
      'audio/basic',
      'audio/mid',
      'audio/mpeg',
      'audio/x-aiff',
      'audio/ogg',
      'audio/vorbis',
      'audio/vnd.wav',
    ],
  },
  video: {
    mimes: ['video/mp4', 'video/quicktime'],
  },
};

const extractAttachmentLinkUrl = (html) => {
  const parser = new DOMParser();
  const { body } = parser.parseFromString(html, 'text/html');
  const link = body.querySelector('a');
  const src = link.getAttribute('href');
  const { canonicalSrc } = link.dataset;

  return { src, canonicalSrc };
};

class UploadError extends Error {}

const notifyUploadError = (eventHub, error) => {
  eventHub.$emit(ALERT_EVENT, {
    message:
      error instanceof UploadError
        ? error.message
        : __('An error occurred while uploading the file. Please try again.'),
    variant: VARIANT_DANGER,
  });
};

/**
 * Uploads a file with a post request to the URL indicated
 * in the uploadsPath parameter. The expected response of the
 * uploads service is a JSON object that contains, at least, a
 * link property. The link property should contain markdown link
 * definition (i.e. [GitLab](https://gitlab.com)).
 *
 * This Markdown will be rendered to extract its canonical and full
 * URLs using GitLab Flavored Markdown renderer in the backend.
 *
 * @param {Object} params
 * @param {String} params.uploadsPath An absolute URL that points to a service
 * that allows sending a file for uploading via POST request.
 * @param {String} params.renderMarkdown A function that accepts a markdown string
 * and returns a rendered version in HTML format.
 * @param {File} params.file The file to upload
 *
 * @returns {TappablePromise} Returns an object with two properties:
 *
 * canonicalSrc: The URL as defined in the Markdown
 * src: The absolute URL that points to the resource in the server
 */
export const uploadFile = ({ uploadsPath, renderMarkdown, file }) => {
  return new TappablePromise(async (tap) => {
    const maxFileSize = (gon.max_file_size || 10).toFixed(0);
    const fileSize = bytesToMiB(file.size);
    if (fileSize > maxFileSize) {
      throw new UploadError(
        sprintf(__('File is too big (%{fileSize}MiB). Max filesize: %{maxFileSize}MiB.'), {
          fileSize: fileSize.toFixed(2),
          maxFileSize,
        }),
      );
    }

    const formData = new FormData();
    formData.append('file', file, file.name);

    const { data } = await axios.post(uploadsPath, formData, {
      onUploadProgress: (e) => tap(e.loaded / e.total),
    });
    const { markdown } = data.link;
    const rendered = await renderMarkdown(markdown);

    return extractAttachmentLinkUrl(rendered);
  });
};

const uploadMedia = async ({ type, editor, file, uploadsPath, renderMarkdown, eventHub }) => {
  // needed to avoid mismatched transaction error
  await Promise.resolve();

  const objectUrl = URL.createObjectURL(file);
  const { selection } = editor.view.state;
  const currentNode = selection.$to.node();

  let position = selection.to;
  let content = {
    type,
    attrs: { uploading: file.name, src: objectUrl, alt: file.name },
  };
  let selectionIncrement = 0;

  // if the current node is not empty, we need to wrap the content in a new paragraph
  if (currentNode.content.size > 0 || currentNode.type.name === 'doc') {
    content = {
      type: 'paragraph',
      content: [content],
    };
    selectionIncrement = 1;
  }

  chain(editor)
    .insertContentAt(position, content)
    .setNodeSelection(position + selectionIncrement)
    .run();

  uploadFile({ file, uploadsPath, renderMarkdown })
    .tap((progress) => {
      chain(editor).setMeta('uploadProgress', { filename: file.name, progress }).run();
    })
    .then(({ canonicalSrc }) => {
      // the position might have changed while uploading, so we need to find it again
      position = findUploadedFilePosition(editor, file.name);

      editor.view.dispatch(
        editor.state.tr.setMeta('preventAutolink', true).setNodeMarkup(position, undefined, {
          uploading: false,
          src: objectUrl,
          alt: file.name,
          canonicalSrc,
        }),
      );

      chain(editor).setNodeSelection(position).run();
    })
    .catch((e) => {
      position = findUploadedFilePosition(editor, file.name);

      chain(editor)
        .deleteRange({ from: position, to: position + 1 })
        .run();

      notifyUploadError(eventHub, e);
    });
};

const uploadAttachment = async ({ editor, file, uploadsPath, renderMarkdown, eventHub }) => {
  // needed to avoid mismatched transaction error
  await Promise.resolve();

  const objectUrl = URL.createObjectURL(file);
  const { selection } = editor.view.state;
  const currentNode = selection.$to.node();

  let position = selection.to;
  let content = {
    type: 'text',
    text: file.name,
    marks: [{ type: 'link', attrs: { href: objectUrl, uploading: file.name } }],
  };

  // if the current node is not empty, we need to wrap the content in a new paragraph
  if (currentNode.content.size > 0 || currentNode.type.name === 'doc') {
    content = {
      type: 'paragraph',
      content: [content],
    };
  }

  chain(editor).insertContentAt(position, content).extendMarkRange('link').run();

  uploadFile({ file, uploadsPath, renderMarkdown })
    .tap((progress) => {
      chain(editor).setMeta('uploadProgress', { filename: file.name, progress }).run();
    })
    .then(({ src, canonicalSrc }) => {
      // the position might have changed while uploading, so we need to find it again
      position = findUploadedFilePosition(editor, file.name);

      chain(editor)
        .setTextSelection(position)
        .extendMarkRange('link')
        .updateAttributes('link', { href: src, canonicalSrc, uploading: false })
        .run();
    })
    .catch((e) => {
      position = findUploadedFilePosition(editor, file.name);

      chain(editor)
        .setTextSelection(position)
        .extendMarkRange('link')
        .unsetLink()
        .deleteSelection()
        .run();

      notifyUploadError(eventHub, e);
    });
};

export const handleFileEvent = ({ editor, file, uploadsPath, renderMarkdown, eventHub }) => {
  if (!file) return false;

  for (const [type, { mimes, ext }] of Object.entries(acceptedMimes)) {
    if (mimes.includes(file?.type) && (!ext || file?.name.endsWith(ext))) {
      uploadMedia({ type, editor, file, uploadsPath, renderMarkdown, eventHub });

      return true;
    }
  }

  uploadAttachment({ editor, file, uploadsPath, renderMarkdown, eventHub });

  return true;
};