aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/Utils.hx
blob: 4e2fc9d8330edc555082dfaaf15097bcdb8f1afc (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
package server;

import js.node.url.URL;
import js.node.Https;
import js.node.Os;
import sys.FileSystem;

class Utils {

	public static function ensureDir(path:String):Void {
		if (!FileSystem.exists(path)) FileSystem.createDirectory(path);
	}

	public static function getGlobalIp(callback:(ip:String)->Void):Void {
		function onError(e):Void {
			trace("Warning: connection error, server is local.");
			callback("127.0.0.1");
		}
		final url = new URL("https://myexternalip.com/raw");
		Https.get({ // this overload for node < v10.9.0
			timeout: 5000,
			protocol: url.protocol,
			host: url.host,
			path: url.pathname
		}, r -> {
			r.setEncoding("utf8");
			final data = new StringBuf();
			r.on("data", chunk -> data.add(chunk));
			r.on("end", _ -> callback(data.toString()));
		}).on("error", onError)
			.on("timeout", onError);
	}

	public static function getLocalIp():String {
		final ifaces = Os.networkInterfaces();
		for (field in Reflect.fields(ifaces)) {
			final type = Reflect.field(ifaces, field);

			for (ifname in Reflect.fields(type)) {
				final iface = Reflect.field(type, ifname);
				// skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
				if ('IPv4' != iface.family || iface.internal != false) continue;
				// this interface has only one ipv4 address
				return iface.address;
			}
		}
		return "127.0.0.1";
	}

	public static function sortedPush(ids:Array<Int>, id:Int):Void {
		for (i => n in ids) {
			if (id < n) {
				ids.insert(i, id);
				return;
			}
		}
		ids.push(id);
	}

	public static function shuffle<T>(arr:Array<T>):Void {
		for (i => a in arr) {
			final n = Std.random(arr.length);
			final b = arr[n];
			arr[i] = b;
			arr[n] = a;
		}
	}

}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage