/
upload.component.ts
316 lines (260 loc) · 9.52 KB
/
upload.component.ts
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {
CreateAudioFileValue,
CreateDocumentFileValue,
CreateFileValue,
CreateStillImageFileValue,
UpdateAudioFileValue,
UpdateDocumentFileValue,
UpdateFileValue,
UpdateStillImageFileValue
} from '@dasch-swiss/dsp-js';
import { NotificationService } from '@dasch-swiss/dsp-ui';
import { UploadedFileResponse, UploadFileService } from './upload-file.service';
// https://stackoverflow.com/questions/45661010/dynamic-nested-reactive-form-expressionchangedafterithasbeencheckederror
const resolvedPromise = Promise.resolve(null);
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit {
@Input() parentForm?: FormGroup;
@Input() representation: 'stillImage' | 'movingImage' | 'audio' | 'document' | 'text';
// only StillImageRepresentation and DocumentPresentation is supported so far
@Input() formName: string;
@Output() fileInfo: EventEmitter<CreateFileValue> = new EventEmitter<CreateFileValue>();
file: File;
form: FormGroup;
fileControl: FormControl;
isLoading = false;
thumbnailUrl: string;
allowedFileTypes: string[];
// todo: maybe we can use this list to display which file format is allowed to
supportedImageTypes = ['image/jpeg', 'image/jp2', 'image/tiff', 'image/tiff-fx', 'image/png'];
supportedDocumentTypes = ['application/pdf'];
supportedAudioTypes = ['audio/mpeg'];
// readonly fromLabels = {
// upload: 'Upload file',
// drag_drop: 'Drag and drop or click to upload'
// };
constructor(
private _fb: FormBuilder,
private _notification: NotificationService,
private _upload: UploadFileService
) { }
ngOnInit(): void {
this.initializeForm();
this._supportedFileTypes();
}
/**
* adds file and uploads to SIPI, checking before if conditions met
* @param event DragDrop event containing upload files
*/
addFile(event: any): void {
let files: File[] = [];
files = event.target?.files ? event.target.files : event;
// only one file at a time supported
if (this._isMoreThanOneFile(files)) {
const error = 'ERROR: Only one file allowed at a time';
this._notification.openSnackBar(error);
this.file = null;
} else {
const formData = new FormData();
this.file = files[0];
// only certain filetypes are supported
if (!this._isFileTypeSupported(this.file.type)) {
const error = 'ERROR: File type not supported';
this._notification.openSnackBar(error);
this.file = null;
} else {
// show loading indicator only for files > 1MB
this.isLoading = this.file.size > 1048576;
formData.append(this.file.name, this.file);
this._upload.upload(formData).subscribe(
(res: UploadedFileResponse) => {
// prepare thumbnail url to display something after upload
switch (this.representation) {
case 'stillImage':
const temporaryUrl = res.uploadedFiles[0].temporaryUrl;
const thumbnailUri = '/full/256,/0/default.jpg';
this.thumbnailUrl = `${temporaryUrl}${thumbnailUri}`;
break;
case 'document':
// the preview thumbnail is deactivated for the moment;
// --> TODO: it will be activated as soon as we implement a pdf viewer
// this.thumbnailUrl = res.uploadedFiles[0].temporaryUrl;
this.thumbnailUrl = undefined;
break;
default:
this.thumbnailUrl = undefined;
break;
}
this.fileControl.setValue(res.uploadedFiles[0]);
const fileValue = this.getNewValue();
if (fileValue) {
this.fileInfo.emit(fileValue);
}
this.isLoading = false;
},
(e: Error) => {
this._notification.openSnackBar(e.message);
this.isLoading = false;
this.file = null;
this.thumbnailUrl = null;
}
);
}
}
}
/**
* converts file size to display in KB or MB
* @param val file size to be converted
*/
convertBytes(val: number): string {
const kilo = 1024;
const mega = kilo * kilo;
let result: number;
if (val >= mega) {
result = val / mega;
return `${result.toFixed(2)} MB`;
} else {
result = val / kilo;
return `${result.toFixed(2)} KB`;
}
}
/**
* converts date to a readable format.
* @param date date to be converted
*/
convertDate(date: number): string {
return new Date(+`Date(${date})`.replace(/\D/g, '')).toLocaleDateString();
}
/**
* removes the attachment
*/
deleteAttachment(): void {
this.fileControl.reset();
}
/**
* initializes form group
*/
initializeForm(): void {
this.fileControl = new FormControl(null, Validators.required);
this.fileControl.valueChanges.subscribe(
val => {
// check if the form has been reset
if (val === null) {
this.file = null;
this.thumbnailUrl = null;
}
}
);
this.form = this._fb.group({
file: this.fileControl
}, { updateOn: 'blur' });
if (this.parentForm !== undefined) {
resolvedPromise.then(() => {
this.parentForm.addControl('file', this.form);
});
}
}
/**
* resets form group
*/
resetForm(): void {
this.form.reset();
}
/**
* create a new file value.
*/
getNewValue(): CreateFileValue | false {
if (!this.form.valid) {
return false;
}
const filename = this.fileControl.value.internalFilename;
let fileValue: CreateStillImageFileValue | CreateDocumentFileValue;
switch (this.representation) {
case 'stillImage':
fileValue = new CreateStillImageFileValue();
break;
case 'document':
fileValue = new CreateDocumentFileValue();
break;
case 'audio':
fileValue = new CreateAudioFileValue();
break;
default:
// --> TODO for UPLOAD: expand with other representation file types
break;
}
fileValue.filename = filename;
return fileValue;
}
/**
* create an updated file value.
*
* @param id the current file value's id.
*/
getUpdatedValue(id: string): UpdateFileValue | false {
if (!this.form.valid) {
return false;
}
const filename = this.fileControl.value.internalFilename;
let fileValue: UpdateStillImageFileValue | UpdateDocumentFileValue | UpdateAudioFileValue;
switch (this.representation) {
case 'stillImage':
fileValue = new UpdateStillImageFileValue();
break;
case 'document':
fileValue = new UpdateDocumentFileValue();
break;
case 'audio':
fileValue = new UpdateAudioFileValue();
break;
default:
// --> TODO for UPLOAD: expand with other representation file types
break;
}
// const fileValue = new UpdateStillImageFileValue();
fileValue.filename = filename;
fileValue.id = id;
return fileValue;
}
/**
* checks if added file type is supported for certain resource type
* @param fileType file type to be checked
*/
private _isFileTypeSupported(fileType: string): boolean {
return this._supportedFileTypes().includes(fileType);
}
/**
* returns supported file types list for certain resource type
*/
private _supportedFileTypes(): string[] {
this.allowedFileTypes = [];
switch (this.representation) {
case 'stillImage':
this.allowedFileTypes = this.supportedImageTypes;
break;
case 'document':
this.allowedFileTypes = this.supportedDocumentTypes;
break;
case 'audio':
this.allowedFileTypes = this.supportedAudioTypes;
break;
default:
this.allowedFileTypes = [];
break;
}
return this.allowedFileTypes;
}
/**
* checks if more than one file dropped
* @param files files array to be checked
*/
private _isMoreThanOneFile(files: File[]): boolean {
return files.length > 1;
}
}