DragUploader.ts 25.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

/**
 * Module: TYPO3/CMS/Backend/DragUploader
 */
17
import {SeverityEnum} from './Enum/Severity';
18
19
20
import * as $ from 'jquery';
import moment = require('moment');
import NProgress = require('nprogress');
21
import Modal = require('./Modal');
22
import Notification = require('./Notification');
23
import {MessageUtility} from './Utility/MessageUtility';
24
25
26
27
28
29
30
31

/**
 * Possible actions for conflicts w/ existing files
 */
enum Action {
  OVERRIDE = 'replace',
  RENAME = 'rename',
  SKIP = 'cancel',
32
  USE_EXISTING = 'useExisting',
33
34
35
36
37
38
39
40
41
42
43
44
}

/**
 * Properties of a file as returned from the AJAX action; essential, this is a serialized instance of
 * \TYPO3\CMS\Core\Resource\File plus some extra properties (see FileController::flattenResultDataValue())
 */
interface UploadedFile {
  name: string;
  id: number;
  uid: number;
  icon: string;
  extension: string;
45
  permissions: { read: boolean; write: boolean };
46
47
48
49
50
51
52
53
54
  size: number;
  // formatted as ddmmyy
  date: string;

  mtime: Date;
  thumbUrl: string;
  type: string;
}

55
56
57
58
interface InternalFile extends File {
  lastModified: any;
}

59
60
61
62
63
64
65
66
67
68
69
interface DragUploaderOptions {
  /**
   * CSS selector for the element where generated messages are inserted. (required)
   */
  outputSelector: string;
  /**
   * Color of the message text. (optional)
   */
  outputColor?: string;
}

70
71
72
73
74
75
76
77
78
79
80
81
82
class DragUploaderPlugin {
  public irreObjectUid: number;
  public $fileList: JQuery;
  public fileListColumnCount: number;
  public filesExtensionsAllowed: string;
  public fileDenyPattern: RegExp | null;
  public maxFileSize: number;
  public $trigger: JQuery;
  public target: string;

  /**
   * Array of files which are asked for being overridden
   */
83
  private askForOverride: Array<{ original: UploadedFile, uploaded: InternalFile, action: Action }> = [];
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

  private percentagePerFile: number = 1;

  private $body: JQuery;
  private $element: JQuery;
  private $dropzone: JQuery;
  private $dropzoneMask: JQuery;
  private fileInput: HTMLInputElement;
  private browserCapabilities: { fileReader: boolean; DnD: boolean; Progress: boolean };
  private dropZoneInsertBefore: boolean;
  private queueLength: number;

  constructor(element: HTMLElement) {
    this.$body = $('body');
    this.$element = $(element);
    const hasTrigger = this.$element.data('dropzoneTrigger') !== undefined;
    this.$trigger = $(this.$element.data('dropzoneTrigger'));
    this.$dropzone = $('<div />').addClass('dropzone').hide();
    this.irreObjectUid = this.$element.data('fileIrreObject');

    const dropZoneEscapedTarget = this.$element.data('dropzoneTarget');
    if (this.irreObjectUid && this.$element.nextAll(dropZoneEscapedTarget).length !== 0) {
      this.dropZoneInsertBefore = true;
      this.$dropzone.insertBefore(dropZoneEscapedTarget);
    } else {
      this.dropZoneInsertBefore = false;
      this.$dropzone.insertAfter(dropZoneEscapedTarget);
    }
    this.$dropzoneMask = $('<div />').addClass('dropzone-mask').appendTo(this.$dropzone);
    this.fileInput = <HTMLInputElement>document.createElement('input');
    this.fileInput.setAttribute('type', 'file');
    this.fileInput.setAttribute('multiple', 'multiple');
    this.fileInput.setAttribute('name', 'files[]');
    this.fileInput.classList.add('upload-file-picker');
    this.$body.append(this.fileInput);

    this.$fileList = $(this.$element.data('progress-container'));
    this.fileListColumnCount = $('thead tr:first th', this.$fileList).length;
    this.filesExtensionsAllowed = this.$element.data('file-allowed');
    this.fileDenyPattern = this.$element.data('file-deny-pattern') ? new RegExp(this.$element.data('file-deny-pattern'), 'i') : null;
    this.maxFileSize = parseInt(this.$element.data('max-file-size'), 10);
    this.target = this.$element.data('target-folder');

    this.browserCapabilities = {
      fileReader: typeof FileReader !== 'undefined',
      DnD: 'draggable' in document.createElement('span'),
130
      Progress: 'upload' in new XMLHttpRequest,
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
    };


    if (!this.browserCapabilities.DnD) {
      console.warn('Browser has no Drag and drop capabilities; cannot initialize DragUploader');
      return;
    }

    this.$body.on('dragover', this.dragFileIntoDocument);
    this.$body.on('dragend', this.dragAborted);
    this.$body.on('drop', this.ignoreDrop);

    this.$dropzone.on('dragenter', this.fileInDropzone);
    this.$dropzoneMask.on('dragenter', this.fileInDropzone);
    this.$dropzoneMask.on('dragleave', this.fileOutOfDropzone);
    this.$dropzoneMask.on('drop', (ev: JQueryEventObject) => this.handleDrop(<JQueryTypedEvent<DragEvent>>ev));

    this.$dropzone.prepend(
      '<div class="dropzone-hint">' +
      '<div class="dropzone-hint-media">' +
      '<div class="dropzone-hint-icon"></div>' +
      '</div>' +
      '<div class="dropzone-hint-body">' +
      '<h3 class="dropzone-hint-title">' +
      TYPO3.lang['file_upload.dropzonehint.title'] +
      '</h3>' +
      '<p class="dropzone-hint-message">' +
      TYPO3.lang['file_upload.dropzonehint.message'] +
      '</p>' +
      '</div>' +
161
      '</div>',
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
    ).click(() => {
      this.fileInput.click();
    });
    $('<span />').addClass('dropzone-close').click(this.hideDropzone).appendTo(this.$dropzone);

    // no filelist then create own progress table
    if (this.$fileList.length === 0) {
      this.$fileList = $('<table />')
        .attr('id', 'typo3-filelist')
        .addClass('table table-striped table-hover upload-queue')
        .html('<tbody></tbody>').hide();

      if (this.dropZoneInsertBefore) {
        this.$fileList.insertAfter(this.$dropzone);
      } else {
        this.$fileList.insertBefore(this.$dropzone);
      }
      this.fileListColumnCount = 7;
    }

    this.fileInput.addEventListener('change', () => {
      this.processFiles(Array.apply(null, this.fileInput.files));
    });

    this.bindUploadButton(hasTrigger === true ? this.$trigger : this.$element);
  }

  public showDropzone(): void {
    this.$dropzone.show();
  }

  /**
   *
   * @param {Event} event
   */
  public hideDropzone(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    this.$dropzone.hide();
  }

  /**
   * @param {Event} event
   * @returns {boolean}
   */
  public dragFileIntoDocument = (event: Event): boolean => {
    event.stopPropagation();
    event.preventDefault();
    $(event.currentTarget).addClass('drop-in-progress');
    this.showDropzone();
    return false;
  }

  /**
   *
   * @param {Event} event
   * @returns {Boolean}
   */
  public dragAborted = (event: Event): boolean => {
    event.stopPropagation();
    event.preventDefault();
    $(event.currentTarget).removeClass('drop-in-progress');
    return false;
  }

  public ignoreDrop = (event: Event): boolean => {
    // stops the browser from redirecting.
    event.stopPropagation();
    event.preventDefault();
    this.dragAborted(event);
    return false;
  }

  public handleDrop = (event: JQueryTypedEvent<DragEvent>): void => {
    this.ignoreDrop(event);
    this.processFiles(event.originalEvent.dataTransfer.files);
    this.$dropzone.removeClass('drop-status-ok');
  }

  /**
   * @param {FileList} files
   */
  public processFiles(files: FileList): void {
    this.queueLength = files.length;

    if (!this.$fileList.is(':visible')) {
      this.$fileList.show();
    }

    NProgress.start();
    this.percentagePerFile = 1 / files.length;

    // Check for each file if is already exist before adding it to the queue
    const ajaxCalls: JQueryXHR[] = [];
    $.each(files, (i: string, file) => {
      ajaxCalls[parseInt(i, 10)] = $.ajax({
        url: TYPO3.settings.ajaxUrls.file_exists,
        data: {
          fileName: file.name,
261
          fileTarget: this.target,
262
263
264
265
266
267
268
269
        },
        cache: false,
        success: (response: any) => {
          const fileExists = typeof response.uid !== 'undefined';
          if (fileExists) {
            this.askForOverride.push({
              original: response,
              uploaded: file,
270
              action: this.irreObjectUid ? Action.USE_EXISTING : Action.SKIP,
271
272
273
274
275
276
            });
            NProgress.inc(this.percentagePerFile);
          } else {
            // Unused var _ is necessary as "no-unused-expression" is active
            const _ = new FileQueueItem(this, file, Action.SKIP);
          }
277
        },
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
      });
    });

    $.when.apply($, ajaxCalls).done(() => {
      this.drawOverrideModal();
      NProgress.done();
    });

    this.fileInput.value = '';
  }

  public fileInDropzone = (): void => {
    this.$dropzone.addClass('drop-status-ok');
  }

  public fileOutOfDropzone = (): void => {
    this.$dropzone.removeClass('drop-status-ok');
  }

  /**
   * Bind file picker to default upload button
   *
   * @param {Object} button
   */
  public bindUploadButton(button: JQuery): void {
    button.click((event: Event) => {
      event.preventDefault();
      this.fileInput.click();
      this.showDropzone();
    });
  }

  /**
   * Decrements the queue and renders a flash message if queue is empty
   */
  public decrementQueueLength(): void {
    if (this.queueLength > 0) {
      this.queueLength--;
      if (this.queueLength === 0) {
        $.ajax({
          url: TYPO3.settings.ajaxUrls.flashmessages_render,
          cache: false,
          success: (data) => {
321
            $.each(data, (index: number, flashMessage: { title: string, message: string, severity: number }) => {
322
323
              Notification.showMessage(flashMessage.title, flashMessage.message, flashMessage.severity);
            });
324
          },
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
        });
      }
    }
  }

  /**
   * Renders the modal for existing files
   */
  public drawOverrideModal(): void {
    const amountOfItems = Object.keys(this.askForOverride).length;
    if (amountOfItems === 0) {
      return;
    }
    const $modalContent = $('<div/>').append(
      $('<p/>').text(TYPO3.lang['file_upload.existingfiles.description']),
      $('<table/>', {class: 'table'}).append(
        $('<thead/>').append(
          $('<tr />').append(
            $('<th/>'),
            $('<th/>').text(TYPO3.lang['file_upload.header.originalFile']),
            $('<th/>').text(TYPO3.lang['file_upload.header.uploadedFile']),
346
347
348
349
            $('<th/>').text(TYPO3.lang['file_upload.header.action']),
          ),
        ),
      ),
350
351
352
353
354
355
356
    );
    for (let i = 0; i < amountOfItems; ++i) {
      const $record = $('<tr />').append(
        $('<td />').append(
          (this.askForOverride[i].original.thumbUrl !== ''
              ? $('<img />', {src: this.askForOverride[i].original.thumbUrl, height: 40})
              : $(this.askForOverride[i].original.icon)
357
          ),
358
359
        ),
        $('<td />').html(
360
          this.askForOverride[i].original.name + ' (' + (DragUploader.fileSizeAsString(this.askForOverride[i].original.size)) + ')' +
361
          '<br>' + moment.unix(this.askForOverride[i].original.mtime).format('YYYY-MM-DD HH:mm'),
362
363
        ),
        $('<td />').html(
364
          this.askForOverride[i].uploaded.name + ' (' + (DragUploader.fileSizeAsString(this.askForOverride[i].uploaded.size)) + ')' +
365
366
367
368
369
370
          '<br>' +
          moment(
            this.askForOverride[i].uploaded.lastModified
              ? this.askForOverride[i].uploaded.lastModified
              : this.askForOverride[i].uploaded.lastModifiedDate,
          ).format('YYYY-MM-DD HH:mm'),
371
372
373
374
375
376
        ),
        $('<td />').append(
          $('<select />', {class: 'form-control t3js-actions', 'data-override': i}).append(
            (this.irreObjectUid ? $('<option/>').val(Action.USE_EXISTING).text(TYPO3.lang['file_upload.actions.use_existing']) : ''),
            $('<option />').val(Action.SKIP).text(TYPO3.lang['file_upload.actions.skip']),
            $('<option />').val(Action.RENAME).text(TYPO3.lang['file_upload.actions.rename']),
377
378
379
            $('<option />').val(Action.OVERRIDE).text(TYPO3.lang['file_upload.actions.override']),
          ),
        ),
380
381
382
383
384
      );
      $modalContent.find('table').append('<tbody />').append($record);
    }

    const $modal = Modal.confirm(
385
      TYPO3.lang['file_upload.existingfiles.title'], $modalContent, SeverityEnum.warning,
386
387
388
389
390
      [
        {
          text: $(this).data('button-close-text') || TYPO3.lang['file_upload.button.cancel'] || 'Cancel',
          active: true,
          btnClass: 'btn-default',
391
          name: 'cancel',
392
393
394
395
        },
        {
          text: $(this).data('button-ok-text') || TYPO3.lang['file_upload.button.continue'] || 'Continue with selected actions',
          btnClass: 'btn-warning',
396
397
          name: 'continue',
        },
398
      ],
399
      ['modal-inner-scroll'],
400
401
402
403
404
405
406
407
408
409
410
    );
    $modal.find('.modal-dialog').addClass('modal-lg');

    $modal.find('.modal-footer').prepend(
      $('<span/>').addClass('form-inline').append(
        $('<label/>').text(TYPO3.lang['file_upload.actions.all.label']),
        $('<select/>', {class: 'form-control t3js-actions-all'}).append(
          $('<option/>').val('').text(TYPO3.lang['file_upload.actions.all.empty']),
          (this.irreObjectUid ? $('<option/>').val(Action.USE_EXISTING).text(TYPO3.lang['file_upload.actions.all.use_existing']) : ''),
          $('<option/>').val(Action.SKIP).text(TYPO3.lang['file_upload.actions.all.skip']),
          $('<option/>').val(Action.RENAME).text(TYPO3.lang['file_upload.actions.all.rename']),
411
412
413
          $('<option/>').val(Action.OVERRIDE).text(TYPO3.lang['file_upload.actions.all.override']),
        ),
      ),
414
415
416
    );

    const uploader = this;
417
    $modal.on('change', '.t3js-actions-all', function (this: HTMLInputElement): void {
418
419
420
421
422
423
424
425
426
427
428
429
430
431
      const $this = $(this),
        value = $this.val();

      if (value !== '') {
        // mass action was selected, apply action to every file
        $modal.find('.t3js-actions').each((i, select) => {
          const $select = $(select),
            index = parseInt($select.data('override'), 10);
          $select.val(value).prop('disabled', 'disabled');
          uploader.askForOverride[index].action = <Action>$select.val();
        });
      } else {
        $modal.find('.t3js-actions').removeProp('disabled');
      }
432
    }).on('change', '.t3js-actions', function (this: HTMLInputElement): void {
433
434
435
      const $this = $(this),
        index = parseInt($this.data('override'), 10);
      uploader.askForOverride[index].action = <Action>$this.val();
436
    }).on('button.clicked', function (this: HTMLInputElement, e: Event): void {
437
438
439
440
441
442
443
444
      if ((<HTMLInputElement>(e.target)).name === 'cancel') {
        uploader.askForOverride = [];
        Modal.dismiss();
      } else if ((<HTMLInputElement>(e.target)).name === 'continue') {
        $.each(uploader.askForOverride, (key, fileInfo) => {
          if (fileInfo.action === Action.USE_EXISTING) {
            DragUploader.addFileToIrre(
              uploader.irreObjectUid,
445
              fileInfo.original,
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
            );
          } else if (fileInfo.action !== Action.SKIP) {
            // Unused var _ is necessary as "no-unused-expression" is active
            const _ = new FileQueueItem(uploader, fileInfo.uploaded, fileInfo.action);
          }
        });
        uploader.askForOverride = [];
        Modal.dismiss();
      }
    }).on('hidden.bs.modal', () => {
      this.askForOverride = [];
    });
  }
}

class FileQueueItem {
  private $row: JQuery;
  private $iconCol: JQuery;
  private $fileName: JQuery;
  private $progress: JQuery;
  private $progressContainer: JQuery;
  private $progressBar: JQuery;
  private $progressPercentage: JQuery;
  private $progressMessage: JQuery;
  private dragUploader: DragUploaderPlugin;
471
  private file: InternalFile;
472
473
474
  private override: Action;
  private upload: XMLHttpRequest;

475
  constructor(dragUploader: DragUploaderPlugin, file: InternalFile, override: Action) {
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
    this.dragUploader = dragUploader;
    this.file = file;
    this.override = override;

    this.$row = $('<tr />').addClass('upload-queue-item uploading');
    this.$iconCol = $('<td />').addClass('col-icon').appendTo(this.$row);
    this.$fileName = $('<td />').text(file.name).appendTo(this.$row);
    this.$progress = $('<td />').attr('colspan', this.dragUploader.fileListColumnCount - 2).appendTo(this.$row);
    this.$progressContainer = $('<div />').addClass('upload-queue-progress').appendTo(this.$progress);
    this.$progressBar = $('<div />').addClass('upload-queue-progress-bar').appendTo(this.$progressContainer);
    this.$progressPercentage = $('<span />').addClass('upload-queue-progress-percentage').appendTo(this.$progressContainer);
    this.$progressMessage = $('<span />').addClass('upload-queue-progress-message').appendTo(this.$progressContainer);


    // position queue item in filelist
    if ($('tbody tr.upload-queue-item', this.dragUploader.$fileList).length === 0) {
      this.$row.prependTo($('tbody', this.dragUploader.$fileList));
      this.$row.addClass('last');
    } else {
      this.$row.insertBefore($('tbody tr.upload-queue-item:first', this.dragUploader.$fileList));
    }

    // set dummy file icon
    this.$iconCol.html('<span class="t3-icon t3-icon-mimetypes t3-icon-other-other">&nbsp;</span>');

    // check file size
    if (this.dragUploader.maxFileSize > 0 && this.file.size > this.dragUploader.maxFileSize) {
      this.updateMessage(TYPO3.lang['file_upload.maxFileSizeExceeded']
        .replace(/\{0\}/g, this.file.name)
        .replace(/\{1\}/g, DragUploader.fileSizeAsString(this.dragUploader.maxFileSize)));
      this.$row.addClass('error');

      // check filename/extension against deny pattern
    } else if (this.dragUploader.fileDenyPattern && this.file.name.match(this.dragUploader.fileDenyPattern)) {
      this.updateMessage(TYPO3.lang['file_upload.fileNotAllowed'].replace(/\{0\}/g, this.file.name));
      this.$row.addClass('error');

    } else if (!this.checkAllowedExtensions()) {
      this.updateMessage(TYPO3.lang['file_upload.fileExtensionExpected']
515
        .replace(/\{0\}/g, this.dragUploader.filesExtensionsAllowed),
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
      );
      this.$row.addClass('error');
    } else {
      this.updateMessage('- ' + DragUploader.fileSizeAsString(this.file.size));

      const formData = new FormData();
      formData.append('data[upload][1][target]', this.dragUploader.target);
      formData.append('data[upload][1][data]', '1');
      formData.append('overwriteExistingFiles', this.override);
      formData.append('redirect', '');
      formData.append('upload_1', this.file);

      const s = $.extend(true, {}, $.ajaxSettings, {
        url: TYPO3.settings.ajaxUrls.file_process,
        contentType: false,
        processData: false,
        data: formData,
        cache: false,
        type: 'POST',
535
        success: (data: { upload?: UploadedFile[] }) => this.uploadSuccess(data),
536
        error: (response: XMLHttpRequest) => this.uploadError(response),
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
      });

      s.xhr = () => {
        const xhr = $.ajaxSettings.xhr();
        xhr.upload.addEventListener('progress', (e: ProgressEvent) => this.updateProgress(e));
        return xhr;
      };

      // start upload
      this.upload = $.ajax(s);
    }
  }

  /**
   * @param {string} message
   */
  public updateMessage(message: string): void {
    this.$progressMessage.text(message);
  }

  /**
   * Remove the progress bar
   */
  public removeProgress(): void {
    if (this.$progress) {
      this.$progress.remove();
    }
  }

  public uploadStart(): void {
    this.$progressPercentage.text('(0%)');
    this.$progressBar.width('1%');
    this.dragUploader.$trigger.trigger('uploadStart', [this]);
  }

  /**
   * @param {XMLHttpRequest} response
   */
  public uploadError(response: XMLHttpRequest): void {
    this.updateMessage(TYPO3.lang['file_upload.uploadFailed'].replace(/\{0\}/g, this.file.name));
    const error = $(response.responseText);
    if (error.is('t3err')) {
      this.$progressPercentage.text(error.text());
    } else {
      this.$progressPercentage.text('(' + response.statusText + ')');
    }
    this.$row.addClass('error');
    this.dragUploader.decrementQueueLength();
    this.dragUploader.$trigger.trigger('uploadError', [this, response]);
  }

  /**
   * @param {ProgressEvent} event
   */
  public updateProgress(event: ProgressEvent): void {
    const percentage = Math.round((event.loaded / event.total) * 100) + '%';
    this.$progressBar.outerWidth(percentage);
    this.$progressPercentage.text(percentage);
    this.dragUploader.$trigger.trigger('updateProgress', [this, percentage, event]);
  }

  /**
   * @param {{upload?: UploadedFile[]}} data
   */
601
  public uploadSuccess(data: { upload?: UploadedFile[] }): void {
602
603
604
605
606
607
608
609
610
611
612
613
614
615
    if (data.upload) {
      this.dragUploader.decrementQueueLength();
      this.$row.removeClass('uploading');
      this.$fileName.text(data.upload[0].name);
      this.$progressPercentage.text('');
      this.$progressMessage.text('100%');
      this.$progressBar.outerWidth('100%');

      // replace file icon
      if (data.upload[0].icon) {
        this.$iconCol
          .html(
            '<a href="#" class="t3js-contextmenutrigger" data-uid="'
            + data.upload[0].id + '" data-table="sys_file">'
616
            + data.upload[0].icon + '&nbsp;</span></a>',
617
618
619
620
621
622
          );
      }

      if (this.dragUploader.irreObjectUid) {
        DragUploader.addFileToIrre(
          this.dragUploader.irreObjectUid,
623
          data.upload[0],
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
        );
        setTimeout(
          () => {
            this.$row.remove();
            if ($('tr', this.dragUploader.$fileList).length === 0) {
              this.dragUploader.$fileList.hide();
              this.dragUploader.$trigger.trigger('uploadSuccess', [this, data]);
            }
          },
          3000);
      } else {
        setTimeout(
          () => {
            this.showFileInfo(data.upload[0]);
            this.dragUploader.$trigger.trigger('uploadSuccess', [this, data]);
          },
          3000);
      }
    }
  }

  /**
   * @param {UploadedFile} fileInfo
   */
  public showFileInfo(fileInfo: UploadedFile): void {
    this.removeProgress();
    // add spacing cells when clibboard and/or extended view is enabled
    for (let i = 7; i < this.dragUploader.fileListColumnCount; i++) {
      $('<td />').text('').appendTo(this.$row);
    }
    $('<td />').text(fileInfo.extension.toUpperCase()).appendTo(this.$row);
    $('<td />').text(fileInfo.date).appendTo(this.$row);
    $('<td />').text(DragUploader.fileSizeAsString(fileInfo.size)).appendTo(this.$row);
    let permissions = '';
    if (fileInfo.permissions.read) {
      permissions += '<strong class="text-danger">' + TYPO3.lang['permissions.read'] + '</strong>';
    }
    if (fileInfo.permissions.write) {
      permissions += '<strong class="text-danger">' + TYPO3.lang['permissions.write'] + '</strong>';
    }
    $('<td />').html(permissions).appendTo(this.$row);
    $('<td />').text('-').appendTo(this.$row);
  }

  public checkAllowedExtensions(): boolean {
    if (!this.dragUploader.filesExtensionsAllowed) {
      return true;
    }
    const extension = this.file.name.split('.').pop();
    const allowed = this.dragUploader.filesExtensionsAllowed.split(',');

    return $.inArray(extension.toLowerCase(), allowed) !== -1;
  }
}

class DragUploader {
680
681
682
  public fileListColumnCount: number;
  public filesExtensionsAllowed: string;
  public fileDenyPattern: string;
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
  private static options: DragUploaderOptions;

  public static fileSizeAsString(size: number): string {
    const sizeKB: number = size / 1024;
    let str = '';

    if (sizeKB > 1024) {
      str = (sizeKB / 1024).toFixed(1) + ' MB';
    } else {
      str = sizeKB.toFixed(1) + ' KB';
    }
    return str;
  }

  /**
   * @param {number} irre_object
   * @param {UploadedFile} file
   */
  public static addFileToIrre(irre_object: number, file: UploadedFile): void {
702
703
704
705
706
707
    const message = {
      objectGroup: irre_object,
      table: 'sys_file',
      uid: file.uid,
    };
    MessageUtility.send(message);
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
  }

  public static init(): void {
    const me = this;
    const opts = me.options;

    // register the jQuery plugin "DragUploaderPlugin"
    $.fn.extend({
      dragUploader: function (options?: DragUploaderOptions | string): JQuery {
        return this.each((index: number, elem: HTMLElement): void => {
          const $this = $(elem);
          let data = $this.data('DragUploaderPlugin');
          if (!data) {
            $this.data('DragUploaderPlugin', (data = new DragUploaderPlugin(elem)));
          }
          if (typeof options === 'string') {
            data[options]();
          }
        });
727
      },
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
    });

    $(() => {
      $('.t3js-drag-uploader').dragUploader(opts);
    });
  }

}

/**
 * Function to apply the example plugin to the selected elements of a jQuery result.
 */
interface DragUploaderFunction {
  /**
   * Apply the example plugin to the elements selected in the jQuery result.
   *
   * @param options Options to use for this application of the example plugin.
   * @returns jQuery result.
   */
  (options: DragUploaderOptions): JQuery;
}

750
export const initialize = function (): void {
751
752
753
754
755
756
757
758
759
760
761
762
  DragUploader.init();

  // load required modules to hook in the post initialize function
  if (
    'undefined' !== typeof TYPO3.settings
    && 'undefined' !== typeof TYPO3.settings.RequireJS
    && 'undefined' !== typeof TYPO3.settings.RequireJS.PostInitializationModules
    && 'undefined' !== typeof TYPO3.settings.RequireJS.PostInitializationModules['TYPO3/CMS/Backend/DragUploader']
  ) {
    $.each(
      TYPO3.settings.RequireJS.PostInitializationModules['TYPO3/CMS/Backend/DragUploader'], (pos, moduleName) => {
        require([moduleName]);
763
      },
764
765
766
767
768
    );
  }
};

initialize();