-
Notifications
You must be signed in to change notification settings - Fork 60
/
translation.go
433 lines (402 loc) · 14.1 KB
/
translation.go
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package uadmin
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"strings"
"github.com/uadmin/uadmin/colors"
)
// var langMap map[string]map[string]string
// Translation is for multilingual fields
type translation struct {
Name string
Code string
Flag string
Default bool
Active bool
Value string
}
// InitalizeLanguage !
func initializeLanguage() {
// Load Multilanguage
// multiLanguage, err := ioutil.ReadFile("./templates/uadmin/multilingual.json")
// if err != nil {
// multiLanguage = []byte{}
// }
//
// err = json.Unmarshal(multiLanguage, &langMap)
// if err != nil {
// Trail(ERROR, "uadmin.initializeLanguage.json.Unmarshal %s", err.Error())
// }
langList := []Language{}
if Count(&langList, "") != 0 {
// Setup Active languages
activeLangs = []Language{}
Filter(&activeLangs, "active = ?", true)
// Setup default language
Get(&defaultLang, "`default` = ?", true)
return
}
langs := [][]string{
{"Abkhaz", "аҧсуа бызшәа, аҧсшәа", "ab"},
{"Afar", "Afaraf", "aa"},
{"Afrikaans", "Afrikaans", "af"},
{"Akan", "Akan", "ak"},
{"Albanian", "Shqip", "sq"},
{"Amharic", "አማርኛ", "am"},
{"Arabic", "العربية", "ar"},
{"Aragonese", "aragonés", "an"},
{"Armenian", "Հայերեն", "hy"},
{"Assamese", "অসমীয়া", "as"},
{"Avaric", "авар мацӀ, магӀарул мацӀ", "av"},
{"Avestan", "avesta", "ae"},
{"Aymara", "aymar aru", "ay"},
{"Azerbaijani", "azərbaycan dili", "az"},
{"Bambara", "bamanankan", "bm"},
{"Bashkir", "башҡорт теле", "ba"},
{"Basque", "euskara, euskera", "eu"},
{"Belarusian", "беларуская мова", "be"},
{"Bengali, Bangla", "বাংলা", "bn"},
{"Bihari", "भोजपुरी", "bh"},
{"Bislama", "Bislama", "bi"},
{"Bosnian", "bosanski jezik", "bs"},
{"Breton", "brezhoneg", "br"},
{"Bulgarian", "български език", "bg"},
{"Burmese", "ဗမာစာ", "my"},
{"Catalan", "català", "ca"},
{"Chamorro", "Chamoru", "ch"},
{"Chechen", "нохчийн мотт", "ce"},
{"Chichewa, Chewa, Nyanja", "chiCheŵa, chinyanja", "ny"},
{"Chinese", "中文 (Zhōngwén), 汉语, 漢語", "zh"},
{"Chuvash", "чӑваш чӗлхи", "cv"},
{"Cornish", "Kernewek", "kw"},
{"Corsican", "corsu, lingua corsa", "co"},
{"Cree", "ᓀᐦᐃᔭᐍᐏᐣ", "cr"},
{"Croatian", "hrvatski jezik", "hr"},
{"Czech", "čeština, český jazyk", "cs"},
{"Danish", "dansk", "da"},
{"Divehi, Dhivehi, Maldivian", "ދިވެހި", "dv"},
{"Dutch", "Nederlands, Vlaams", "nl"},
{"Dzongkha", "རྫོང་ཁ", "dz"},
{"English", "English", "en"},
{"Esperanto", "Esperanto", "eo"},
{"Estonian", "eesti, eesti keel", "et"},
{"Ewe", "Eʋegbe", "ee"},
{"Faroese", "føroyskt", "fo"},
{"Fijian", "vosa Vakaviti", "fj"},
{"Filipino", "Filipino", "fl"},
{"Finnish", "suomi, suomen kieli", "fi"},
{"French", "français, langue française", "fr"},
{"Fula, Fulah, Pulaar, Pular", "Fulfulde, Pulaar, Pular", "ff"},
{"Galician", "galego", "gl"},
{"Georgian", "ქართული", "ka"},
{"German", "Deutsch", "de"},
{"Greek (modern)", "ελληνικά", "el"},
{"Guaraní", "Avañe'ẽ", "gn"},
{"Gujarati", "ગુજરાતી", "gu"},
{"Haitian, Haitian Creole", "Kreyòl ayisyen", "ht"},
{"Hausa", "(Hausa) هَوُسَ", "ha"},
{"Hebrew (modern)", "עברית", "he"},
{"Herero", "Otjiherero", "hz"},
{"Hindi", "हिन्दी, हिंदी", "hi"},
{"Hiri Motu", "Hiri Motu", "ho"},
{"Hungarian", "magyar", "hu"},
{"Interlingua", "Interlingua", "ia"},
{"Indonesian", "Bahasa Indonesia", "id"},
{"Interlingue", "Originally called Occidental; then Interlingue after WWII", "ie"},
{"Irish", "Gaeilge", "ga"},
{"Igbo", "Asụsụ Igbo", "ig"},
{"Inupiaq", "Iñupiaq, Iñupiatun", "ik"},
{"Ido", "Ido", "io"},
{"Icelandic", "Íslenska", "is"},
{"Italian", "Italiano", "it"},
{"Inuktitut", "ᐃᓄᒃᑎᑐᑦ", "iu"},
{"Japanese", "日本語 (にほんご)", "ja"},
{"Javanese", "ꦧꦱꦗꦮ, Basa Jawa", "jv"},
{"Kalaallisut, Greenlandic", "kalaallisut, kalaallit oqaasii", "kl"},
{"Kannada", "ಕನ್ನಡ", "kn"},
{"Kanuri", "Kanuri", "kr"},
{"Kashmiri", "कश्मीरी, كشميري", "ks"},
{"Kazakh", "қазақ тілі", "kk"},
{"Khmer", "ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ", "km"},
{"Kikuyu, Gikuyu", "Gĩkũyũ", "ki"},
{"Kinyarwanda", "Ikinyarwanda", "rw"},
{"Kyrgyz", "Кыргызча, Кыргыз тили", "ky"},
{"Komi", "коми кыв", "kv"},
{"Kongo", "Kikongo", "kg"},
{"Korean", "한국어", "ko"},
{"Kurdish", "Kurdî, كوردی", "ku"},
{"Kwanyama, Kuanyama", "Kuanyama", "kj"},
{"Latin", "latine, lingua latina", "la"},
{"Luxembourgish, Letzeburgesch", "Lëtzebuergesch", "lb"},
{"Ganda", "Luganda", "lg"},
{"Limburgish, Limburgan, Limburger", "Limburgs", "li"},
{"Lingala", "Lingála", "ln"},
{"Lao", "ພາສາລາວ", "lo"},
{"Lithuanian", "lietuvių kalba", "lt"},
{"Luba-Katanga", "Tshiluba", "lu"},
{"Latvian", "latviešu valoda", "lv"},
{"Manx", "Gaelg, Gailck", "gv"},
{"Macedonian", "македонски јазик", "mk"},
{"Malagasy", "fiteny malagasy", "mg"},
{"Malay", "bahasa Melayu, بهاس ملايو", "ms"},
{"Malayalam", "മലയാളം", "ml"},
{"Maltese", "Malti", "mt"},
{"Māori", "te reo Māori", "mi"},
{"Marathi (Marāṭhī)", "मराठी", "mr"},
{"Marshallese", "Kajin M̧ajeļ", "mh"},
{"Mongolian", "Монгол хэл", "mn"},
{"Nauruan", "Dorerin Naoero", "na"},
{"Navajo, Navaho", "Diné bizaad", "nv"},
{"Northern Ndebele", "isiNdebele", "nd"},
{"Nepali", "नेपाली", "ne"},
{"Ndonga", "Owambo", "ng"},
{"Norwegian Bokmål", "Norsk bokmål", "nb"},
{"Norwegian Nynorsk", "Norsk nynorsk", "nn"},
{"Norwegian", "Norsk", "no"},
{"Nuosu", "ꆈꌠ꒿ Nuosuhxop", "ii"},
{"Southern Ndebele", "isiNdebele", "nr"},
{"Occitan", "occitan, lenga d'òc", "oc"},
{"Ojibwe, Ojibwa", "ᐊᓂᔑᓈᐯᒧᐎᓐ", "oj"},
{"Old Church Slavonic, Church Slavonic, Old Bulgarian", "ѩзыкъ словѣньскъ", "cu"},
{"Oromo", "Afaan Oromoo", "om"},
{"Oriya", "ଓଡ଼ିଆ", "or"},
{"Ossetian, Ossetic", "ирон æвзаг", "os"},
{"(Eastern) Punjabi", "ਪੰਜਾਬੀ", "pa"},
{"Pāli", "पाऴि", "pi"},
{"Persian (Farsi)", "فارسی", "fa"},
{"Polish", "język polski, polszczyzna", "pl"},
{"Pashto, Pushto", "پښتو", "ps"},
{"Portuguese", "Português", "pt"},
{"Quechua", "Runa Simi, Kichwa", "qu"},
{"Romansh", "rumantsch grischun", "rm"},
{"Kirundi", "Ikirundi", "rn"},
{"Romanian", "Română", "ro"},
{"Russian", "Русский", "ru"},
{"Sanskrit (Saṁskṛta)", "संस्कृतम्", "sa"},
{"Sardinian", "sardu", "sc"},
{"Sindhi", "सिन्धी, سنڌي، سندھی", "sd"},
{"Northern Sami", "Davvisámegiella", "se"},
{"Samoan", "gagana fa'a Samoa", "sm"},
{"Sango", "yângâ tî sängö", "sg"},
{"Serbian", "српски језик", "sr"},
{"Scottish Gaelic, Gaelic", "Gàidhlig", "gd"},
{"Shona", "chiShona", "sn"},
{"Sinhalese, Sinhala", "සිංහල", "si"},
{"Slovak", "slovenčina, slovenský jazyk", "sk"},
{"Slovene", "slovenski jezik, slovenščina", "sl"},
{"Somali", "Soomaaliga, af Soomaali", "so"},
{"Southern Sotho", "Sesotho", "st"},
{"Spanish", "Español", "es"},
{"Sundanese", "Basa Sunda", "su"},
{"Swahili", "Kiswahili", "sw"},
{"Swati", "SiSwati", "ss"},
{"Swedish", "svenska", "sv"},
{"Tamil", "தமிழ்", "ta"},
{"Telugu", "తెలుగు", "te"},
{"Tajik", "тоҷикӣ, toçikī, تاجیکی", "tg"},
{"Thai", "ไทย", "th"},
{"Tigrinya", "ትግርኛ", "ti"},
{"Tibetan Standard, Tibetan, Central", "བོད་ཡིག", "bo"},
{"Turkmen", "Türkmen, Түркмен", "tk"},
{"Tagalog", "Wikang Tagalog", "tl"},
{"Tswana", "Setswana", "tn"},
{"Tonga (Tonga Islands)", "faka Tonga", "to"},
{"Turkish", "Türkçe", "tr"},
{"Tsonga", "Xitsonga", "ts"},
{"Tatar", "татар теле, tatar tele", "tt"},
{"Twi", "Twi", "tw"},
{"Tahitian", "Reo Tahiti", "ty"},
{"Uyghur", "ئۇيغۇرچە, Uyghurche", "ug"},
{"Ukrainian", "Українська", "uk"},
{"Urdu", "اردو", "ur"},
{"Uzbek", "Oʻzbek, Ўзбек, أۇزبېك", "uz"},
{"Venda", "Tshivenḓa", "ve"},
{"Vietnamese", "Tiếng Việt", "vi"},
{"Volapük", "Volapük", "vo"},
{"Walloon", "walon", "wa"},
{"Welsh", "Cymraeg", "cy"},
{"Wolof", "Wollof", "wo"},
{"Western Frisian", "Frysk", "fy"},
{"Xhosa", "isiXhosa", "xh"},
{"Yiddish", "ייִדיש", "yi"},
{"Yoruba", "Yorùbá", "yo"},
{"Zhuang, Chuang", "Saɯ cueŋƅ, Saw cuengh", "za"},
{"Zulu", "isiZulu", "zu"},
}
activeLangs = []Language{}
tx := db.Begin()
for i, lang := range langs {
l := Language{
EnglishName: lang[0],
Name: lang[1],
Code: lang[2],
Active: false,
}
if l.Code == "en" {
l.AvailableInGui = true
l.Active = true
l.Default = true
}
tx.Create(&l)
if l.Active {
activeLangs = append(activeLangs, l)
}
if l.Default {
defaultLang = l
}
Trail(WORKING, "Initializing Languages: [%s%d/%d%s]", colors.FGGreenB, i+1, len(langs), colors.FGNormal)
}
tx.Commit()
Trail(OK, "Initializing Languages: [%s%d/%d%s]", colors.FGGreenB, len(langs), len(langs), colors.FGNormal)
}
// Translate is used to get a translation from a multilingual fields
func Translate(raw string, lang string, args ...bool) string {
var langParser map[string]json.RawMessage
err := json.Unmarshal([]byte(raw), &langParser)
if err != nil {
return raw
}
transtedStr := string(langParser[lang])
if len(transtedStr) > 2 {
return transtedStr[1 : len(transtedStr)-1]
}
if len(args) > 0 && !args[0] {
return ""
}
Get(&defaultLang, "`default` = ?", true)
transtedStr = string(langParser[defaultLang.Code])
if len(transtedStr) > 2 {
return transtedStr[1 : len(transtedStr)-1]
}
return ""
}
// Tf is a function for translating strings into any given language
// Parameters:
// ===========
// path (string): This is where to get the translation from. It is in the
// format of "GROUPNAME/FILENAME" for example: "uadmin/system"
// lang (string): Is the language code. If empty string is passed we will use
// the default language.
// term (string): The term to translate.
// args (...interface{}): Is a list of args to fill the term with place holders
func Tf(path string, lang string, term string, args ...interface{}) string {
var err error
var buf []byte
if lang == "" {
lang = defaultLang.Code
}
// Check if the path if for an existing model schema
pathParts := strings.Split(path, "/")
isSchemaFile := false
if len(pathParts) > 2 {
path = strings.Join(pathParts[0:2], "/")
isSchemaFile = true
}
fileName := "./static/i18n/" + strings.ToLower(path) + "." + lang + ".json"
if _, err = os.Stat(fileName); os.IsNotExist(err) {
Trail(WARNING, "Unrecognized path (%s) - fileName:%s", path, fileName)
return term
}
buf, err = ioutil.ReadFile(fileName)
if err != nil {
Trail(ERROR, "Unable to read language file (%s)", fileName)
return term
}
// Check if it is a schema file or custom files
if !isSchemaFile {
langMap := map[string]string{}
err = json.Unmarshal(buf, &langMap)
if err != nil {
Trail(ERROR, "Unknown translation file format (%s)", path)
return term
}
// If the term exists, then return it
if val, ok := langMap[term]; ok {
return strings.TrimPrefix(val, translateMe)
}
// If it doesn't exist then add it to the file
if lang != "en" {
Tf(path, "en", term, args...)
langMap[term] = translateMe + term
} else {
langMap[term] = term
}
// Save the file with the new term
saveLangFile(langMap, fileName)
} else {
langMap := structLanguage{}
err = json.Unmarshal(buf, &langMap)
if err != nil {
Trail(ERROR, "Unknown translation file format (%s)", path)
return term
}
// If the term exists, then return it
// First: ErrMsg
if strings.ToLower(pathParts[3]) == "errmsg" {
if val, ok := langMap.Fields[pathParts[2]].ErrMsg[term]; ok {
return strings.TrimPrefix(val, translateMe)
}
// If it doesn't exist then add it to the file
if lang != "en" {
Tf(strings.Join(pathParts, "/"), "en", term, args...)
langMap.Fields[pathParts[2]].ErrMsg[term] = translateMe + term
} else {
langMap.Fields[pathParts[2]].ErrMsg[term] = term
}
// Save the file with the new term
saveLangFile(langMap, fileName)
}
// TODO: add other parts of the structLang in here
}
return term
}
// Translate Model
func translateSchema(s *ModelSchema, lang string) {
if lang == "" {
lang = "en"
}
pkgName := fmt.Sprint(reflect.TypeOf(models[s.ModelName]))
pkgName = strings.Split(pkgName, ".")[0]
fileName := "./static/i18n/" + pkgName + "/" + s.ModelName + "." + lang + ".json"
// If the model language file doessn't exist, then return
if _, err := os.Stat(fileName); os.IsNotExist(err) {
return
}
buf, err := ioutil.ReadFile(fileName)
if err != nil {
Trail(ERROR, "Unable to read language file (%s)", fileName)
return
}
// Parse the file and traslate the schema
structLang := structLanguage{}
err = json.Unmarshal(buf, &structLang)
if err != nil {
Trail(ERROR, "Invalid format for language file (%s)", fileName)
return
}
s.DisplayName = strings.TrimPrefix(structLang.DisplayName, translateMe)
for i, f := range s.Fields {
f.DisplayName = strings.TrimPrefix(structLang.Fields[f.Name].DisplayName, translateMe)
f.Help = strings.TrimPrefix(structLang.Fields[f.Name].Help, translateMe)
f.PatternMsg = strings.TrimPrefix(structLang.Fields[f.Name].PatternMsg, translateMe)
if _, ok := structLang.Fields[f.Name].ErrMsg[f.ErrMsg]; ok {
f.ErrMsg = strings.TrimPrefix(structLang.Fields[f.Name].ErrMsg[f.ErrMsg], translateMe)
} else {
}
s.Fields[i] = f
}
}
func getLanguage(r *http.Request) Language {
langCookie, err := r.Cookie("language")
if err != nil || langCookie == nil {
return Language{}
}
lang := langCookie.Value
language := Language{}
Get(&language, "code=?", lang)
return language
}