forked from arlolra/check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
286 lines (260 loc) · 7.46 KB
/
utils.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
package main
import (
"encoding/json"
"fmt"
"github.com/samuel/go-gettext/gettext"
"html/template"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
)
func IsParamSet(r *http.Request, param string) bool {
return len(r.URL.Query().Get(param)) > 0
}
func Lang(r *http.Request) string {
lang := r.URL.Query().Get("lang")
if len(lang) == 0 {
lang = "en_US"
}
return lang
}
func GetQS(q url.Values, param string, deflt int) (num int, str string) {
str = q.Get(param)
num, err := strconv.Atoi(str)
if err != nil {
num = deflt
str = ""
} else {
str = fmt.Sprintf("&%s=%s", param, str)
}
return
}
func GetHost(r *http.Request) (host string, err error) {
// get remote ip
host = r.Header.Get("X-Forwarded-For")
if len(host) > 0 {
parts := strings.Split(host, ",")
// apache will append the remote address
host = strings.TrimSpace(parts[len(parts)-1])
} else {
host, _, err = net.SplitHostPort(r.RemoteAddr)
}
return
}
var TBBUserAgents = regexp.MustCompile(`^Mozilla/5\.0 \(Windows NT 6\.1; rv:[\d]+\.0\) Gecko/20100101 Firefox/[\d]+\.0$`)
var OrfoxUserAgents = regexp.MustCompile(`^Mozilla/5\.0 \(Android; Mobile; rv:38.0\) Gecko/38.0 Firefox/38.0$`)
func LikelyTBB(ua string) bool {
return TBBUserAgents.MatchString(ua) || OrfoxUserAgents.MatchString(ua)
}
var HaveManual = map[string]bool{
"ar": true,
"cs": true,
"de": true,
"el": true,
"en": true,
"es": true,
"fa": true,
"fr": true,
"hu": true,
"it": true,
"ja": true,
"lv": true,
"nb": true,
"nl": true,
"pl": true,
"pt_BR": true,
"ru": true,
"sv": true,
"tr": true,
"zh_CN": true,
}
func FuncMap(domain *gettext.Domain) template.FuncMap {
return template.FuncMap{
"UnEscaped": func(x string) interface{} {
return template.HTML(x)
},
"UnEscapedURL": func(x string) interface{} {
return template.URL(x)
},
"GetText": func(lang string, text string) string {
return domain.GetText(lang, text)
},
"Equal": func(one string, two string) bool {
return one == two
},
"Not": func(b bool) bool {
return !b
},
"And": func(a bool, b bool) bool {
return a && b
},
"UserManual": func(lang string) string {
if _, ok := HaveManual[lang]; !ok {
lang = "en"
}
return lang
},
}
}
var Layout *template.Template
func CompileTemplate(base string, domain *gettext.Domain, templateName string) *template.Template {
if Layout == nil {
Layout = template.New("")
Layout = Layout.Funcs(FuncMap(domain))
Layout = template.Must(Layout.ParseFiles(
path.Join(base, "public/base.html"),
path.Join(base, "public/torbutton.html"),
))
}
l, err := Layout.Clone()
if err != nil {
log.Fatal(err)
}
return template.Must(l.ParseFiles(path.Join(base, "public/", templateName)))
}
type locale struct {
Code string
Name string
}
func GetLocaleList(base string) map[string]string {
// populated from https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
// and https://en.wikipedia.org/w/api.php?action=sitematrix&format=json
haveTranslatedNames := map[string]string{
"af": "Afrikaans",
"ar": "العربية",
"az": "Azərbaycanca",
"bg": "български",
"bs": "Bosanski jezik",
"ca": "Català",
"cs": "Čeština",
"cy": "Cymraeg",
"da": "Dansk",
"de": "Deutsch",
"el": "ελληνικά",
"en_GB": "English (United Kingdom)",
"eo": "Esperanto",
"es": "Español",
"es_AR": "Español (Argentina)",
"es_CO": "Español (Colombia)",
"es_MX": "Español (Mexico)",
"et": "Eesti",
"eu": "Euskara",
"fa": "فارسی",
"fi": "Suomi",
"fr": "Français",
"fr_CA": "Français (Canadien)",
"gl": "Galego",
"he": "עברית",
"hi": "हिन्दी",
"hr": "Hrvatski jezik",
"hr_HR": "Hrvatski jezik (Croatia)",
"hu": "Magyar",
"id": "Bahasa Indonesia",
"it": "Italiano",
"ja": "日本語",
"km": "មែរ",
"kn": "ಕನ್ನಡ",
"ko": "한국어",
"ko_KR": "한국어 (South Korea)",
"lo": "ລາວ",
"lv": "Latviešu valoda",
"mk": "македонски јазик",
"ms_MY": "Bahasa Melayu",
"my": "ဗမာစာ",
"nb": "Norsk bokmål",
"nl": "Nederlands",
"nl_BE": "Vlaams",
"nn": "Norsk nynorsk",
"pa": "ਪੰਜਾਬੀ",
"pl": "Język polski",
"pl_PL": "Język polski (Poland)",
"pt": "Português",
"pt_BR": "Português do Brasil",
"ro": "română",
"ru": "русский язык",
"ru@petr1708": "Russian Petrine orthography",
"si_LK": "සිංහල",
"sk": "Slovenčina",
"sk_SK": "Slovenčina (Slovakia)",
"sl": "Slovenski jezik",
"sl_SI": "Slovenski jezik (Slovenia)",
"sq": "shqip",
"sr": "српски језик",
"sv": "Svenska",
"ta": "தமிழ்",
"te_IN": "తెలుగు",
"th": "ไทย",
"tr": "Türkçe",
"uk": "українська мова",
"zh_CN": "中文简体",
"zh_TW": "中文繁體",
}
// for all folders in locale which match a locale from https://www.transifex.com/api/2/languages/
// use the language name unless we have an override
webLocales, err := FetchTranslationLocales(base)
if err != nil {
log.Printf("Failed to get up to date language list, using fallback.")
return haveTranslatedNames
}
return GetInstalledLocales(base, webLocales, haveTranslatedNames)
}
func FetchTranslationLocales(base string) (map[string]locale, error) {
file, err := os.Open(path.Join(base, "data/langs"))
if err != nil {
return nil, err
}
defer file.Close()
webLocales := make(map[string]locale)
// Parse the api response into a list of possible locales
dec := json.NewDecoder(file)
for {
var webList []locale
if err = dec.Decode(&webList); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
// The api returns an array, so we need to map it
for _, l := range webList {
webLocales[l.Code] = l
}
}
return webLocales, nil
}
// Get a list of all languages installed in our locale folder with translations if available
func GetInstalledLocales(base string, webLocales map[string]locale, nameTranslations map[string]string) map[string]string {
localFiles, err := ioutil.ReadDir(path.Join(base, "locale"))
if err != nil {
log.Print("No locales found in 'locale'. Try running 'make i18n'.")
log.Fatal(err)
}
locales := make(map[string]string, len(localFiles))
locales["en_US"] = "English"
for _, f := range localFiles {
// TODO: Ensure a language has 100% of the template file
// Currently this is what should be on the torcheck_completed
// branch on the translations git should be, so we don't really
// have to check it in theory...
code := f.Name()
// Only accept folders which have corresponding locale
if !f.IsDir() || webLocales[code] == (locale{}) {
continue
}
// If we have a translated name for a given locale, use it
if transName := nameTranslations[code]; transName != "" {
locales[code] = transName
} else {
log.Print("No translated name for code: " + code)
locales[code] = webLocales[code].Name
}
}
return locales
}