summaryrefslogtreecommitdiff
path: root/src/client/scripts/select-file.ts
blob: 70e68e88c03868757f3e8c899ebb508f28fd11da (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
import { faUpload, faCloud } from '@fortawesome/free-solid-svg-icons';
import { selectDriveFile } from './select-drive-file';
import { apiUrl } from '../config';

export function selectFile(component: any, src: any, label: string | null, multiple = false) {
	return new Promise((res, rej) => {
		const chooseFileFromPc = () => {
			const input = document.createElement('input');
			input.type = 'file';
			input.multiple = multiple;
			input.onchange = () => {
				const dialog = component.$root.dialog({
					type: 'waiting',
					text: component.$t('uploading') + '...',
					showOkButton: false,
					showCancelButton: false,
					cancelableByBgClick: false
				});

				const promises = Array.from(input.files).map(file => new Promise((ok, err) => {
					const data = new FormData();
					data.append('file', file);
					data.append('i', component.$store.state.i.token);

					fetch(apiUrl + '/drive/files/create', {
						method: 'POST',
						body: data
					})
					.then(response => response.json())
					.then(ok)
					.catch(err);
				}));

				Promise.all(promises).then(driveFiles => {
					res(multiple ? driveFiles : driveFiles[0]);
				}).catch(e => {
					component.$root.dialog({
						type: 'error',
						text: e
					});
				}).finally(() => {
					dialog.close();
				});
			};
			input.click();
		};

		const chooseFileFromDrive = () => {
			selectDriveFile(component.$root, multiple).then(files => {
				res(files);
			});
		};

		const chooseFileFromUrl = () => {

		};

		component.$root.menu({
			items: [label ? {
				text: label,
				type: 'label'
			} : undefined, {
				text: component.$t('upload'),
				icon: faUpload,
				action: chooseFileFromPc
			}, {
				text: component.$t('fromDrive'),
				icon: faCloud,
				action: chooseFileFromDrive
			}, /*{
				text: component.$t('fromUrl'),
				icon: faLink,
				action: chooseFileFromUrl
			}*/],
			source: src
		});
	});
}