Beispiel #1
0
func Init(config core_config.ReadWriter) go_i18n.TranslateFunc {
	var T go_i18n.TranslateFunc
	var err error

	locale := config.Locale()
	if locale != "" {
		pieces := strings.Split(locale, "_")
		err = loadFromAsset(locale, pieces[1])
		if err == nil {
			T, err = go_i18n.Tfunc(config.Locale(), DEFAULT_LOCALE)
		}
	} else {
		var userLocale string
		userLocale, err = initWithUserLocale()
		if err != nil {
			userLocale = mustLoadDefaultLocale()
		}

		T, err = go_i18n.Tfunc(userLocale, DEFAULT_LOCALE)
	}

	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #2
0
func Init(config core_config.ReadWriter, detector detection.Detector) go_i18n.TranslateFunc {
	var T go_i18n.TranslateFunc
	var err error

	locale := config.Locale()
	if locale != "" {
		err = loadFromAsset(locale)
		if err == nil {
			T, err = go_i18n.Tfunc(config.Locale(), DEFAULT_LOCALE)
		}
	} else {
		var userLocale string
		userLocale, err = initWithUserLocale(detector)
		if err != nil {
			userLocale = mustLoadDefaultLocale()
		}

		T, err = go_i18n.Tfunc(userLocale, DEFAULT_LOCALE)
	}

	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #3
0
func LoadLocale(locale string) i18n.TranslateFunc {
	if locale != "" {
		T, _ = i18n.Tfunc(locale)
	} else {
		T, _ = i18n.Tfunc("en-US")
	}

	return T
}
Beispiel #4
0
func GetTranslationsAndLocale(w http.ResponseWriter, r *http.Request) (i18n.TranslateFunc, string) {
	headerLocale := strings.Split(strings.Split(r.Header.Get("Accept-Language"), ",")[0], "-")[0]
	if locales[headerLocale] != "" {
		translations, _ := i18n.Tfunc(headerLocale)
		return translations, headerLocale
	}

	translations, _ := i18n.Tfunc(model.DEFAULT_LOCALE)
	return translations, model.DEFAULT_LOCALE
}
Beispiel #5
0
func TfuncWithFallback(pref string) i18n.TranslateFunc {
	t, _ := i18n.Tfunc(pref)
	return func(translationID string, args ...interface{}) string {
		if translated := t(translationID, args...); translated != translationID {
			return translated
		}

		t, _ := i18n.Tfunc(model.DEFAULT_LOCALE)
		return t(translationID, args...)
	}
}
Beispiel #6
0
/**
 * Request that the LCS start a lookup process for a particular URL.
 * @param {string} lookupURL - The URL to try to find in the distributed cache
 */
func lookup(lookupURL string) Result {
	response, err := http.Get(BundleLookupURL(Configuration, lookupURL))
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err != nil {
		fmt.Println(T("error_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		return Result{ERR_NO_CONNECT_LCS, err.Error(), false, false, ""}
	} else if response == nil || response.StatusCode != 200 {
		errMsg := T("lcs_not_ready_cli")
		fmt.Println(errMsg)
		return Result{ERR_LCS_NOT_READY, errMsg, false, false, ""}
	}
	decoder := json.NewDecoder(response.Body)
	var result Result
	err = decoder.Decode(&result)
	if err != nil {
		decodeErrorMessage := T("decode_error_cli", map[string]interface{}{
			"Message": err.Error(),
		})
		fmt.Println(decodeErrorMessage)
		reachedLCS := HandleCCError(ERR_MALFORMED_LCS_RESPONSE, err.Error(), ErrorState{
			"requestURL": DecodeErrReportURL(Configuration),
		})
		if reachedLCS {
			return Result{ERR_MALFORMED_LCS_RESPONSE, decodeErrorMessage, false, false, ""}
		} else {
			errMsg := T("no_reach_lcs_cli")
			return Result{ERR_NO_CONNECT_LCS, errMsg, false, false, ""}
		}
	}
	return result
}
Beispiel #7
0
func init() {

	cmd, err := notify.NewCmd("telegram-cli", "-C")

	if err != nil {
		log.Fatal("NewCmd error", err)
	}

	botConf = Conf{
		Limit: 10,
		Url:   "localhost",
		Rpms:  500,
		Cmd:   cmd,
	}

	//Init Data Mapper
	c, err := beeconf.NewConfig("ini", "../../conf/app.conf")

	if err != nil {
		log.Fatal(err)
	}

	TestConfig, err := conf.Initialize("test", c)
	if err != nil {
		log.Fatal(err)
	}

	if err := M.DbOpen(TestConfig.Db); err != nil {
		log.Fatal(err)
	}

	M.PrepareTables(&M.Cand{})
	Tfn, _ := i18n.Tfunc("en-us", "en-us", "en-us")
	M.T = Tfn
}
Beispiel #8
0
func main() {
	// Configure the i18n library to use the preferred language set in the CENOLANG environement variable
	setLanguage := os.Getenv("CENOLANG")
	if setLanguage == "" {
		os.Setenv("CENOLANG", "en-us")
		setLanguage = "en-us"
	}
	i18n.MustLoadTranslationFile("./translations/" + setLanguage + ".all.json")
	T, _ := i18n.Tfunc(setLanguage, "en-us")
	// Read an existing configuration file or have the user supply settings
	if conf, err := ReadConfigFile(CONFIG_FILE); err != nil {
		fmt.Println(T("no_config_cli", map[string]interface{}{"Location": CONFIG_FILE}))
		Configuration = GetConfigFromUser()
	} else {
		Configuration = conf
	}
	// Create an HTTP proxy server
	http.HandleFunc("/lookup", directHandler)
	http.HandleFunc("/", proxyHandler)
	fmt.Println(T("listening_msg_cli", map[string]interface{}{"Port": Configuration.PortNumber}))
	err := http.ListenAndServe(Configuration.PortNumber, nil)
	if err != nil {
		panic(err)
	}
}
Beispiel #9
0
// SendEmailPasswordResetToken sends a password reset token via email.
func SendEmailPasswordResetToken(to string, token string, locale string) error {
	T, _ := i18n.Tfunc(locale)
	err := email.SendEmailFromAdmin(to,
		T("reset_password_title"),
		T("link")+" : "+config.HostURL+"/reset/password/"+token,
		T("reset_password_content")+"<br/><a href=\""+config.HostURL+"/reset/password/"+token+"\" target=\"_blank\">"+config.HostURL+"/reset/password/"+token+"</a>")
	return err
}
Beispiel #10
0
// SendEmailVerfication sends an email verification token via email.
func SendEmailVerfication(to string, token string, locale string) error {
	T, _ := i18n.Tfunc(locale)
	err := email.SendEmailFromAdmin(to,
		T("verify_email_title"),
		T("link")+" : "+config.HostURL+"/verify/email/"+token,
		T("verify_email_content")+"<br/><a href=\""+config.HostURL+"/verify/email/"+token+"\" target=\"_blank\">"+config.HostURL+"/verify/email/"+token+"</a>")
	return err
}
Beispiel #11
0
func GetUserTranslations(locale string) i18n.TranslateFunc {
	if _, ok := locales[locale]; !ok {
		locale = model.DEFAULT_LOCALE
	}

	translations, _ := i18n.Tfunc(locale)
	return translations
}
Beispiel #12
0
// NewTranslation obtains a translation function object for the
// specified locales
func NewTranslation(userLocale string, defaultLocale string) (t i18n.TranslateFunc, err error) {
	t, err = i18n.Tfunc(userLocale, userLocale)
	if err != nil {
		return t, err
	}

	return t, err
}
func init() {
	// TO DO : find another way maybe with assets, go bind-data
	out1, _ := Asset("en-us.all.yaml")
	out2, _ := Asset("fr-be.all.yaml")
	i18n.ParseTranslationFileBytes("en-us.all.yaml", out1)
	i18n.ParseTranslationFileBytes("fr-be.all.yaml", out2)
	Tr, _ = i18n.Tfunc("fr-be")
}
Beispiel #14
0
func Example() {
	i18n.MustLoadTranslationFile("../goi18n/testdata/expected/en-us.all.json")

	T, _ := i18n.Tfunc("en-US")

	bobMap := map[string]interface{}{"Person": "Bob"}
	bobStruct := struct{ Person string }{Person: "Bob"}

	fmt.Println(T("program_greeting"))
	fmt.Println(T("person_greeting", bobMap))
	fmt.Println(T("person_greeting", bobStruct))

	fmt.Println(T("your_unread_email_count", 0))
	fmt.Println(T("your_unread_email_count", 1))
	fmt.Println(T("your_unread_email_count", 2))
	fmt.Println(T("my_height_in_meters", "1.7"))

	fmt.Println(T("person_unread_email_count", 0, bobMap))
	fmt.Println(T("person_unread_email_count", 1, bobMap))
	fmt.Println(T("person_unread_email_count", 2, bobMap))
	fmt.Println(T("person_unread_email_count", 0, bobStruct))
	fmt.Println(T("person_unread_email_count", 1, bobStruct))
	fmt.Println(T("person_unread_email_count", 2, bobStruct))

	fmt.Println(T("person_unread_email_count_timeframe", 3, map[string]interface{}{
		"Person":    "Bob",
		"Timeframe": T("d_days", 0),
	}))
	fmt.Println(T("person_unread_email_count_timeframe", 3, map[string]interface{}{
		"Person":    "Bob",
		"Timeframe": T("d_days", 1),
	}))
	fmt.Println(T("person_unread_email_count_timeframe", 3, map[string]interface{}{
		"Person":    "Bob",
		"Timeframe": T("d_days", 2),
	}))

	// Output:
	// Hello world
	// Hello Bob
	// Hello Bob
	// You have 0 unread emails.
	// You have 1 unread email.
	// You have 2 unread emails.
	// I am 1.7 meters tall.
	// Bob has 0 unread emails.
	// Bob has 1 unread email.
	// Bob has 2 unread emails.
	// Bob has 0 unread emails.
	// Bob has 1 unread email.
	// Bob has 2 unread emails.
	// Bob has 3 unread emails in the past 0 days.
	// Bob has 3 unread emails in the past 1 day.
	// Bob has 3 unread emails in the past 2 days.
}
Beispiel #15
0
/**
 * Check if a provided URL is well-formed.  If not, serve an error page.
 * This call terminates requests when the return value is false (i.e. invalid URL).
 * @param {string} URL - The URL being requested
 * @param {ResponseWriter} w - The object handling writing responses to the client
 * @param {*Request} r - Information about the request
 */
func validateURL(URL string, w http.ResponseWriter, r *http.Request) bool {
	isValid, err := regexp.MatchString(URL_REGEX, URL)
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if !isValid || err != nil {
		HandleCCError(ERR_MALFORMED_URL, T("malformed_url_cli", map[string]interface{}{
			"URL": URL,
		}), ErrorState{"responseWriter": w, "request": r})
		return false
	}
	return true
}
Beispiel #16
0
func t(message, lang, fallback string, data ...interface{}) (template.HTML, error) {
	var count interface{}
	hasCount := false

	if len(data)%2 == 1 {
		if !isNumber(data[0]) {
			return "", errors.New("The count argument must be a number")
		}
		count = data[0]
		hasCount = true

		data = data[1:]
	}

	dataMap := map[string]interface{}{}
	for i := 0; i < len(data); i += 2 {
		dataMap[data[i].(string)] = data[i+1]
	}

	T, err := i18n.Tfunc(lang, fallback)

	if err != nil {
		return "", err
	}

	var translated string
	if hasCount {
		translated = T(message, count, dataMap)
	} else {
		translated = T(message, dataMap)
	}

	if translated == message {
		// Doesn't have a translation mapping, we have to do the template evaluation by hand
		t, err := ttemplate.New("i18n").Parse(message)

		if err != nil {
			return "", err
		}

		buf := util.BufferPool.GetBuffer()
		defer util.BufferPool.Put(buf)

		if err := t.Execute(buf, dataMap); err != nil {
			return "", err
		}

		return template.HTML(buf.String()), nil
	} else {
		return template.HTML(translated), nil
	}
}
Beispiel #17
0
func Init(packageName string, i18nDirname string) go_i18n.TranslateFunc {
	userLocale, err := initWithUserLocale(packageName, i18nDirname)
	if err != nil {
		userLocale = mustLoadDefaultLocale(packageName, i18nDirname)
	}

	T, err := go_i18n.Tfunc(userLocale, DEFAULT_LOCALE)
	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #18
0
func getText(locale, ident, channel string, pending_item *db.PendingItem) string {
	T, _ := i18n.Tfunc(
		locale+"_"+pending_item.Organization+"_"+channel,
		locale+"_"+channel,
	)

	text := T(ident, pending_item.Context)
	if text == ident {
		text = ""
	}

	return text
}
Beispiel #19
0
func Init() go_i18n.TranslateFunc {
	userLocale, err := initWithUserLocale()
	if err != nil {
		userLocale = mustLoadDefaultLocale()
	}

	T, err := go_i18n.Tfunc(userLocale, DEFAULT_LOCALE)
	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #20
0
func GetTranslationsAndLocale(w http.ResponseWriter, r *http.Request) (i18n.TranslateFunc, string) {
	var translations i18n.TranslateFunc
	var _ error
	localeCookie := ""
	if cookie, err := r.Cookie(SESSION_LOCALE); err == nil {
		localeCookie = cookie.Value
		if locales[localeCookie] != "" {
			translations, _ = i18n.Tfunc(localeCookie)
			return translations, localeCookie
		}
	}

	localeCookie = strings.Split(strings.Split(r.Header.Get("Accept-Language"), ",")[0], "-")[0]
	if locales[localeCookie] != "" {
		translations, _ = i18n.Tfunc(localeCookie)
		SetLocaleCookie(w, localeCookie, 10)
		return translations, localeCookie
	}

	translations, _ = i18n.Tfunc(model.DEFAULT_LOCALE)
	SetLocaleCookie(w, model.DEFAULT_LOCALE, 10)
	return translations, model.DEFAULT_LOCALE
}
Beispiel #21
0
/**
 * Try to request a new bundle be created and serve the please wait page.
 * This function should terminate requests.
 * @param {string} URL - The URL to POST to to request a new bundle
 * @param {bool} rewritten - True if the request was downgraded from HTTPS to HTTP else false
 * @param {ResponseWriter} w - the object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func tryRequestBundle(URL string, rewritten bool, w http.ResponseWriter, r *http.Request) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	if err := requestNewBundle(URL, rewritten); err != nil {
		fmt.Println(T("bundle_err_cli", map[string]interface{}{
			"Message": err.Error(),
		}))
		HandleLCSError(ERR_NO_CONNECT_RS, err.Error(), ErrorState{
			"responseWriter": w,
			"request":        r,
		})
	} else {
		pleaseWait(URL, w)
	}
}
Beispiel #22
0
func main() {
	// T needs to point to a translate func, otherwise cf internals blow up
	i18n.T, _ = go_i18n.Tfunc("")
	p := CfPlugin{
		Deployer: &BlueGreenDeploy{
			ErrorFunc: func(message string, err error) {
				fmt.Printf("%v - %v\n", message, err)
				os.Exit(1)
			},
			Out: os.Stdout,
		},
	}

	plugin.Start(&p)
}
Beispiel #23
0
func Init(packageName string, i18nDirname string) (go_i18n.TranslateFunc, error) {
	userLocale := getUserLocale()
	err := loadTranslationAssets(packageName, i18nDirname, userLocale, DEFAULT_LOCAL)
	if err != nil {
		return nil, err
	}

	T, err := go_i18n.Tfunc(userLocale, DEFAULT_LOCAL)
	if err != nil {
		fmt.Printf("Could not initialize i18n strings") //TODO: Better Error Handling
		return nil, err
	}

	return T, nil
}
Beispiel #24
0
/**
 * Serve a page to inform the user that the bundle for the site they requested is being prepared.
 * This function terminates requests.
 * @param {string} URL - The URL that was originally requested
 * @param {ResponseWriter} w - The object handling writing to the client
 */
func pleaseWait(URL string, w http.ResponseWriter) {
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	t, err := template.ParseFiles(path.Join(".", "views", "wait.html"))
	if err != nil {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte(T("please_wait_txt")))
	} else {
		w.Header().Set("Content-Type", "text/html")
		t.Execute(w, map[string]string{
			"PrepareMessage": T("please_wait_header_html"),
			"Paragraph1":     T("please_wait_p1_html"),
			"Paragraph2":     T("please_wait_p2_html"),
			"Retry":          T("retry_html"),
			"Contact":        T("contact_html"),
			"Redirect":       URL,
		})
	}
}
Beispiel #25
0
func Init(detector Detector) goi18n.TranslateFunc {
	var T goi18n.TranslateFunc
	var err error

	var userLocale string
	userLocale, err = initWithUserLocale(detector)
	if err != nil {
		userLocale = mustLoadDefaultLocale()
	}

	T, err = goi18n.Tfunc(userLocale, DEFAULT_LOCALE)

	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #26
0
func Init(config core_config.Reader) go_i18n.TranslateFunc {
	sources := []string{
		config.Locale(),
		os.Getenv(lcAll),
		os.Getenv(lang),
		defaultLocale,
	}

	assetNames := resources.AssetNames()

	for _, source := range sources {
		if source == "" {
			continue
		}

		for _, l := range language.Parse(source) {
			if l.Tag == zhTW || l.Tag == zhHK {
				l.Tag = zhHant
			}

			for _, assetName := range assetNames {
				assetLocale := strings.ToLower(strings.Replace(path.Base(assetName), underscore, hyphen, -1))
				if strings.HasPrefix(assetLocale, l.Tag) {
					assetBytes, err := resources.Asset(assetName)
					if err != nil {
						panic(fmt.Sprintf("Could not load asset '%s': %s", assetName, err.Error()))
					}

					err = go_i18n.ParseTranslationFileBytes(assetName, assetBytes)
					if err != nil {
						panic(fmt.Sprintf("Could not load translations '%s': %s", assetName, err.Error()))
					}

					T, err := go_i18n.Tfunc(source)
					if err == nil {
						return T
					}
				}
			}
		}
	}

	panic("Unable to find suitable translation")
}
Beispiel #27
0
/**
 * Handle incoming requests for bundles.
 * 1. Initiate bundle lookup process
 * 2. Initiate bundle creation process when no bundle exists anywhere
 * @param {ResponseWriter} w - The object handling responding to the client
 * @param {*Request} r - Information about the request
 */
func proxyHandler(w http.ResponseWriter, r *http.Request) {
	w = WriteProxyHeader(w)
	URL := r.URL.String()
	T, _ := i18n.Tfunc(os.Getenv("CENOLANG"), "en-us")
	wasRewritten := r.Header.Get(REWRITTEN_HEADER) == "true"
	fmt.Println(T("got_request_msg_cli", map[string]interface{}{
		"URL":       URL,
		"Rewritten": wasRewritten,
	}))
	if isValidURL := validateURL(URL, w, r); !isValidURL {
		return
	}
	result := lookup(URL)
	if result.ErrCode > 0 {
		fmt.Println(T("err_from_lcs_cli", map[string]interface{}{
			"Code":    result.ErrCode,
			"Message": result.ErrMsg,
		}))
		// Assuming the reason the response is malformed is because of the formation of the bundle,
		// so we will request that a new bundle be created.
		if result.ErrCode == ERR_MALFORMED_LCS_RESPONSE {
			tryRequestBundle(URL, wasRewritten, w, r)
		} else if IsCacheServerError(result.ErrCode) {
			HandleLCSError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		} else {
			HandleCCError(result.ErrCode, result.ErrMsg, ErrorState{
				"responseWriter": w,
				"request":        r,
			})
		}
	} else if result.Complete {
		if result.Found {
			w.Write([]byte(result.Bundle))
		} else {
			tryRequestBundle(URL, wasRewritten, w, r)
		}
	} else {
		pleaseWait(URL, w)
	}
}
Beispiel #28
0
func StartHttpServer() {
	T, _ := i18n.Tfunc("en-US")
	rdr = render.New(render.Options{
		Directory:     "templates",
		Layout:        "layout",
		Funcs:         []template.FuncMap{{"T": T}},
		Extensions:    []string{".html"},
		IsDevelopment: true,
	})

	routes := mux.NewRouter().StrictSlash(false)
	SetRoutes(routes)

	log.Println("Listening on " + *bindingAddress)
	if err := http.ListenAndServe(*bindingAddress, routes); err != nil {
		log.Fatalf("Couldn't bind HTTP server [%s]", err)
	}

	log.Println("Persona has left the building.")
}
Beispiel #29
0
func Init(packageName string, i18nDirname string) go_i18n.TranslateFunc {
	userLocale, err := jibber_jabber.DetectIETF()
	if err != nil {
		userLocale = DEFAULT_LOCAL
	}

	// convert IETF format to XCU format
	userLocale = strings.Replace(userLocale, "-", "_", 1)
	loadFromAsset(packageName, i18nDirname, userLocale)
	// if err != nil {
	// 	panic(err)
	// }

	T, err := go_i18n.Tfunc(userLocale, DEFAULT_LOCAL)
	if err != nil {
		panic(err)
	}

	return T
}
Beispiel #30
0
// TranslateFunc determines what translation to load. For the common case, calling i18n.Error() should suffice
func TranslateFunc(req *rest.Request) i18n.TranslateFunc {
	const (
		acceptLanguage = "Accept-Language"
		requestID      = "SD-Request-ID" // copied to avoid cyclic dependency between middleware and i18n
	)

	// Using golang.org/x/text/language may be a better option for matching languages (e.g, support for language
	// weights, see https://godoc.org/golang.org/x/text/language#example-ParseAcceptLanguage), but we rely on the
	// internal implementation in github.com/nicksnyder/go-i18n/i18n to handle all that for us...
	reqID := req.Header.Get(requestID)
	locale := req.Header.Get(acceptLanguage)
	T, err := i18n.Tfunc(locale, "en-US")
	if err != nil {
		log.WithFields(log.Fields{
			"error":                  err,
			"request_id":             reqID,
			"accept_language_header": locale,
		}).Error("Could not get translation function")
	}
	return T
}