aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/cache/Cache.hx
blob: cfe2f66e30b2b3f88818730ec6317952488fd707 (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
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
package server.cache;

import haxe.io.Path;
import js.node.Fs.Fs;
import sys.FileSystem;

class Cache {
	public final notEnoughSpaceErrorText = "Error: Not enough free space on server or file size is out of cache storage limit.";

	public final isYtReady = false;

	/** In bytes **/
	public var storageLimit(default, null) = 3 * 1024 * 1024 * 1024;

	final main:Main;

	public final cacheDir:String;
	public final freeSpaceBlock = 10 * 1024 * 1024; // 10MB

	final cachedFiles:Array<String> = [];
	var youtubeCache:YoutubeCache;
	var rawCache:RawCache;

	public function new(main:Main, cacheDir:String) {
		this.main = main;
		this.cacheDir = cacheDir;
		Utils.ensureDir(cacheDir);
		youtubeCache = new YoutubeCache(main, this);
		rawCache = new RawCache(main, this);
		isYtReady = youtubeCache.checkYtDeps();
		if (isYtReady) {
			youtubeCache.cleanYtInputFiles();
			youtubeCache.checkUpdate();
		}
	}

	public function getCachedFiles():Array<String> {
		return cachedFiles;
	}

	public function setCachedFiles(names:Array<String>) {
		cachedFiles.resize(0);
		for (name in names) cachedFiles.push(name);

		removeUntrackedFiles();
	}

	function removeUntrackedFiles():Void {
		final names = FileSystem.readDirectory(cacheDir);
		for (name in names) {
			if (name.startsWith(".")) continue;
			if (FileSystem.isDirectory('$cacheDir/$name')) continue;
			if (cachedFiles.contains(name)) continue;
			trace('Remove untracked cache $name');
			remove(name);
		}
	}

	public function log(client:Client, msg:String):Void {
		trace(msg);
		main.serverMessage(client, msg);
	}

	public function logByName(clientName:String, msg:String):Void {
		trace(msg);
		final client = main.clients.getByName(clientName) ?? return;
		main.serverMessage(client, msg);
	}

	public function logWithAdmins(client:Client, msg:String):Void {
		log(client, msg);
		final admins = main.clients.filter(client -> client.isAdmin);
		for (admin in admins) {
			if (client != admin) main.serverMessage(admin, msg);
		}
	}

	public function cacheYoutubeVideo(client:Client, url:String, callback:(name:String) -> Void) {
		youtubeCache.cacheYoutubeVideo(client, url, callback);
	}

	public function cacheRawVideo(client:Client, url:String, callback:(name:String) -> Void) {
		rawCache.cacheRawVideo(client, url, callback);
	}

	public function setStorageLimit(bytes:Int) {
		storageLimit = cast bytes;
		storageLimit = storageLimit.limitMin(0);
		getFreeDiskSpace(availSpace -> {
			final availSpace = (availSpace - freeSpaceBlock).limitMin(0);
			removeOlderCache();
			final freeSpace = getFreeSpace();
			if (availSpace < freeSpace) {
				// shrink limit lower than disk space
				storageLimit += availSpace - freeSpace;
				storageLimit = storageLimit.limitMin(0);
				removeOlderCache();
			}
		});
	}

	public function getFreeDiskSpace(callback:(availSpace:Int) -> Void):Void {
		final statfs = (Fs : Dynamic).statfs ?? {
			trace("Warning: no fs.statfs support in current nodejs version (needs v18+)");
			callback(storageLimit);
			return;
		}
		statfs("/", (err, stats) -> {
			if (err != null) {
				trace(err);
				callback(storageLimit);
				return;
			}
			callback(stats.bsize * stats.bavail);
		});
	}

	public function add(name:String) {
		if (!cachedFiles.contains(name)) {
			cachedFiles.unshift(name);
		}
	}

	public function remove(name:String):Void {
		cachedFiles.remove(name);
		removeFile(name);
	}

	public function exists(name:String):Bool {
		return cachedFiles.contains(name) && isFileExists(name);
	}

	/** Returns `true` if there is enough space to save `addFileSize` bytes. **/
	public function removeOlderCache(addFileSize = 0):Bool {
		var space = getUsedSpace(addFileSize);
		for (name in cachedFiles.reversed()) {
			if (space <= storageLimit) break;
			// do not remove cached items that are in playlist
			if (main.hasPlaylistUrl(getFileUrl(name))) continue;
			remove(name);
			space = getUsedSpace(addFileSize);
		}
		return space < storageLimit;
	}

	function removeFile(name:String):Void {
		final path = getFilePath(name);
		if (FileSystem.exists(path)) FileSystem.deleteFile(path);
	}

	public function getFreeFileName(fullName = "video.mp4"):String {
		final baseName = Path.withoutDirectory(Path.withoutExtension(fullName));
		final ext = Path.extension(fullName);
		var i = 1;
		while (true) {
			final n = i == 1 ? "" : '$i';
			final name = '$baseName$n.$ext';
			if (!isFileExists(name)) return name;
			i++;
		}
	}

	public function getFilePath(name:String):String {
		return '$cacheDir/$name';
	}

	public function getFileUrl(name:String):String {
		final folder = Path.withoutDirectory(cacheDir);
		return '/$folder/$name';
	}

	public function isFileExists(name:String):Bool {
		return FileSystem.exists(getFilePath(name));
	}

	public function findFile(callback:(name:String) -> Bool):Null<String> {
		final names = FileSystem.readDirectory(cacheDir);
		for (name in names) {
			if (callback(name)) return name;
		}
		return null;
	}

	public function getFreeSpace():Int {
		return storageLimit - getUsedSpace();
	}

	public function getUsedSpace(addFileSize = 0):Int {
		var total = addFileSize.limitMin(0);
		for (name in cachedFiles.reversed()) {
			final path = getFilePath(name);
			if (!FileSystem.exists(path)) {
				cachedFiles.remove(name);
				continue;
			}
			total += FileSystem.stat(path).size;
		}
		return total;
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage