aboutsummaryrefslogtreecommitdiff
path: root/static/api/images.js
blob: 3b8c3943deef22635edc7aba942fb06d7d09cf22 (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
import * as sfw from 'sfw';
const { Input } = sfw.element.native;
import * as rest from './rest.js';

class FileUploader {
	constructor(url, files) {
		this.onprogress = () => {}
		this.ondone = () => {}
		this.url = url;
		this.sessions = [];
		this.files = files;
	}

	send() {
		let count = 0;
		this.sessions = this.sessions.concat(this.files.map(
			(file) => new Promise((resolve) => {
				const xhr = new XMLHttpRequest();
				xhr.addEventListener("loadend", (event) => {
					count += 1;

					this.onprogress(count, this.files.length)

					resolve(xhr.readyState === 4 && xhr.status === 200);

					if (count == this.files.length) {
						this.ondone();
					}
				});

				xhr.open("POST", this.url, true);
				xhr.setRequestHeader("Content-Type", "application/octet-stream");
				xhr.send(file.slice());
			})
		));
	}
}

export async function upload_to_timeline() {
	const input = Input.new({
		type: 'file',
		multiple: true,
		accept: 'image/jpeg',
	})
	input.click();


	return new Promise((resolve) => {
		input.onchange = () => {
			resolve(new FileUploader('/api/image/upload', [...input.files]));
		}
	})
}

export async function upload_to_profile(id) {
	const input = Input.new({
		type: 'file',
		multiple: false,
		accept: 'image/jpeg',
	})
	input.click();

	return new Promise((resolve) => {
		input.onchange = () => {
			resolve(new FileUploader(`/api/profile/image/upload/${id}`, [...input.files]));
		}
	})
}

export function list() {
	return rest.get('/api/image/list')
		.then(r => {
			r.images.forEach(i => {
				i.date = new Date(i.date * 1000)
			});
			return r.images;
		});
}


export function remove(id) {
	return rest.post('/api/image/remove', { id: id });
}