blob: acfb811a07ebb7cee198622f4ea5459dc28f297d [file] [log] [blame]
avm99963b5ab76c2020-12-27 02:18:49 +01001package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "log"
8 "net/http"
9 "os"
avm999630f961162020-12-27 13:12:27 +010010 "strings"
avm99963b5ab76c2020-12-27 02:18:49 +010011)
12
13const isoLangsFileName = "isoLangs.json"
14
15type Language struct {
16 CodeName string `json:"-"`
17 Name string `json:"name"`
18 NativeName string `json:"nativeName"`
19}
20
21func getLanguage(isoLangs map[string]Language, lang string) (Language, error) {
22 for currLangCode, currLang := range isoLangs {
23 if currLangCode == lang {
24 currLang.CodeName = lang
avm999630f961162020-12-27 13:12:27 +010025
26 // Only consider the first entry of the list (e.g. "a, b, c" --> "a")
27 if index := strings.Index(currLang.NativeName, ","); index > 0 {
28 currLang.NativeName = currLang.NativeName[:index]
29 }
30
avm99963b5ab76c2020-12-27 02:18:49 +010031 return currLang, nil
32 }
33 }
34
35 return Language{}, fmt.Errorf("Didn't find language '%v' in isoLangs", lang)
36}
37
38func main() {
39 log.SetPrefix("[langs] ")
40 log.SetFlags(0)
41
42 isoLangsFile, err := os.Open(isoLangsFileName)
43 if err != nil {
44 log.Fatalf("Couldn't open file %v, error: %v", isoLangsFileName, err)
45 }
46 defer isoLangsFile.Close()
47
48 isoLangsRawData, err := ioutil.ReadAll(isoLangsFile)
49 if err != nil {
50 log.Fatalf("Couldn't read file %v, error: %v", isoLangsFileName, err)
51 }
52
53 var isoLangs map[string]Language
54 if err := json.Unmarshal(isoLangsRawData, &isoLangs); err != nil {
55 log.Fatalf("Couldn't unmarshal JSON file %v, error: %v", isoLangsFileName, err)
56 }
57
58 resp, err := http.Get("http://translate.google.com/translate_a/l?client=chrome")
59 if err != nil {
60 log.Fatalf("Couldn't get current Google Translate languages from server, error: %v", err)
61 }
62 defer resp.Body.Close()
63
64 gTranslateRawData, err := ioutil.ReadAll(resp.Body)
65 if err != nil {
66 log.Fatalf("Couldn't read body data from Google Translate languages request, error: %v", err)
67 }
68
69 var gTranslateJson map[string]interface{}
70 if err := json.Unmarshal(gTranslateRawData, &gTranslateJson); err != nil {
71 log.Fatalf("Couldn't unmarshal JSON data from the Google Translate languages request, error: %v", err)
72 }
73
74 gTranslateLangs := gTranslateJson["tl"].(map[string]interface{})
75 langs := make(map[string]Language, len(gTranslateLangs))
76
77 for langCode, name := range gTranslateLangs {
78 isoLang, err := getLanguage(isoLangs, langCode)
79 if err != nil {
80 log.Fatalf("Didn't find language '%v' in isoLangs, error: %v", langCode, err)
81 }
82 isoLang.Name = name.(string)
83 langs[langCode] = isoLang
84 }
85
86 result, err := json.MarshalIndent(langs, "", " ")
87 if err != nil {
88 log.Fatal("Couldn't marshal the final JSON, error: %v", err)
89 }
90
91 fmt.Printf("%v", string(result))
92}