aboutsummaryrefslogtreecommitdiffstats
path: root/src/client/FileUploader.hx
blob: fbd8639eaccc8f506763685531c70d5901ae008e (plain) (blame)
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
package client;

import Types.ProgressType;
import Types.UploadResponse;
import client.Main.getEl;
import haxe.Json;
import js.Browser.document;
import js.Browser.window;
import js.html.File;
import js.html.InputElement;
import js.html.ProgressEvent;
import js.html.URL;
import js.html.XMLHttpRequest;

class FileUploader {
	final main:Main;

	public function new(main:Main) {
		this.main = main;
	}

	public function uploadFile(file:File):Void {
		if (!main.isAdmin()) {
			main.serverMessage("Only admins may upload files.", true, false);
			return;
		}
		var title = ~/[?#%\/\\]/g.replace(file.name, "").trim();
		if (title.length == 0) title = "video";
		final name = (window : Dynamic).encodeURIComponent(title);

		final checkboxTemp:InputElement = getEl("#addfromurl .add-temp");
		final isTemp = Main.isTempChecked(checkboxTemp);

		// send last chunk separately to allow server file streaming while uploading
		uploadLastChunk(file, name, data -> {
			if (data.errorId != null) {
				main.serverMessage(data.info, true, false);
				return;
			}
			final url = data.url;
			getFileDuration(file, duration -> {
				if (duration == 0 || Math.isNaN(duration) || !Math.isFinite(duration)) {
					main.serverMessage(Lang.get("addVideoError"), true, false);
					return;
				}
				uploadFullFile(name, file, url, () -> {
					main.addUploadedVideo(url, title, duration, true, isTemp);
				});
			});
		});
	}

	function getFileDuration(file:File, callback:(duration:Float) -> Void):Void {
		final objUrl = URL.createObjectURL(file);
		final video = document.createVideoElement();
		video.preload = "metadata";
		video.muted = true;
		video.onloadedmetadata = () -> {
			final duration = video.duration;
			URL.revokeObjectURL(objUrl);
			callback(duration);
		}
		video.onerror = e -> {
			URL.revokeObjectURL(objUrl);
			callback(0);
		}
		video.src = objUrl;
	}

	function uploadFullFile(name:String, file:File, url:String, onStarted:() -> Void):Void {
		final request = new XMLHttpRequest();
		request.open("POST", "/upload", true);
		request.setRequestHeader("content-name", name);
		request.setRequestHeader("x-client-uuid", main.settings.uuid ?? "");

		var added = false;
		function ensureAdded():Void {
			if (added) return;
			added = true;
			onStarted();
			main.registerUpload(url, () -> request.abort());
		}

		function sendProgress(type:ProgressType, ratio:Float):Void {
			main.send({
				type: Progress,
				progress: {
					type: type,
					ratio: ratio,
					url: url
				}
			});
		}

		var lastSentRatio = 0.0;
		request.upload.onprogress = (event:ProgressEvent) -> {
			ensureAdded();
			var ratio = 0.0;
			if (event.lengthComputable) {
				ratio = (event.loaded / event.total).clamp(0, 1);
			}
			if (ratio - lastSentRatio < 0.01 && ratio < 1) return;
			lastSentRatio = ratio;
			sendProgress(Uploading, ratio);
		}

		request.onload = (e:ProgressEvent) -> {
			main.unregisterUpload(url);
			final data:UploadResponse = try {
				Json.parse(request.responseText);
			} catch (e) {
				trace(e);
				sendProgress(Canceled, 0);
				return;
			}
			if (data.errorId != null) {
				main.serverMessage(data.info, true, false);
				sendProgress(Canceled, 0);
				return;
			}
			ensureAdded();
			sendProgress(Completed, 1);
		}
		request.onerror = (e:ProgressEvent) -> {
			main.unregisterUpload(url);
			sendProgress(Canceled, 0);
		}
		request.onabort = (e:ProgressEvent) -> main.unregisterUpload(url);

		request.send(file);
	}

	function uploadLastChunk(file:File, name:String, callback:(data:UploadResponse) -> Void):Void {
		final chunkSize = 1024 * 1024 * 5; // 5 MB
		final bufferOffset = (file.size - chunkSize).limitMin(0);
		final lastChunk = file.slice(bufferOffset);
		final chunkReq = window.fetch("/upload-last-chunk", {
			method: "POST",
			headers: {
				"content-name": name,
				"x-client-uuid": main.settings.uuid ?? "",
			},
			body: lastChunk,
		});
		chunkReq.then(e -> {
			e.json().then((data:UploadResponse) -> {
				callback(data);
			});
		});
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage