aboutsummaryrefslogtreecommitdiff
path: root/src/lang.js
blob: b3cc251f8b1b21f39ee510bd09f23b1a6ac03363 (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
84
85
86
87
88
89
90
91
92
const fs = require("fs");

const json = require("./modules/json");

const enLang = json(__dirname + "/lang/en.json");
let lang = "";
var langObj = {};

function flatten_obj(data) {
	var obj = {};

	for (let i in data) {
		if (! data.hasOwnProperty(i)) {
			continue;
		}

		if (typeof data[i] == "object" && data[i] !== null) {
			var flattened = flatten_obj(data[i]);
			for (var ii in flattened) {
				if (! flattened.hasOwnProperty(ii)) {
					continue;
				}

				obj[i + "." + ii] = flattened[ii];
			}
		} else {
			obj[i] = data[i];
		}
	}

	return obj;
}

function _loadTranslation(forcedlang) {
	if (fs.existsSync("viper.json")) {
		// Validate viper.json
		let opts = {
			lang: "en",
			autolang: true,
		}

		try {
			opts = json("viper.json");
		}catch (e) {}

		lang = opts.lang;

		if (! lang) {lang = "en"}

		if (forcedlang) {lang = forcedlang}

		if (opts.autolang == false) {
			lang = opts.forcedlang;
			if (! lang) {lang = "en"}
		}

		if (! fs.existsSync(__dirname + `/lang/${lang}.json`)) {
			if (fs.existsSync(__dirname + `/lang/${lang.replace(/-.*$/, "")}.json`)) {
				lang = lang.replace(/-.*$/, "");
			} else {
				lang = "en";
			}
		}
	} else {
		lang = "en";
	}

	langObj = flatten_obj(json(__dirname + `/lang/${lang}.json`) || {});
}


module.exports = (string, forcedlang) => {
	if (lang === "") {
		_loadTranslation();
	}
	 
	if (forcedlang) {
		_loadTranslation(forcedlang);
	}

	if (langObj[string]) {
		return langObj[string];
	} else {
		if (enLang[string]) {
			return enLang[string];
		} else {
			// If it's not in the default lang either, it returns the
			// string, this is absolute fallback.
			return string;
		}
	}
}