You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

languages.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (c) 2018 Daniel Oaks <daniel@danieloaks.net>
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "strings"
  6. "sync"
  7. )
  8. // LanguageManager manages our languages and provides translation abilities.
  9. type LanguageManager struct {
  10. sync.RWMutex
  11. Info map[string]LangData
  12. translations map[string]map[string]string
  13. }
  14. // NewLanguageManager returns a new LanguageManager.
  15. func NewLanguageManager(languageData map[string]LangData) *LanguageManager {
  16. lm := LanguageManager{
  17. Info: make(map[string]LangData),
  18. translations: make(map[string]map[string]string),
  19. }
  20. // make fake "en" info
  21. lm.Info["en"] = LangData{
  22. Code: "en",
  23. Name: "English",
  24. Maintainers: "Oragono contributors and the IRC community",
  25. }
  26. // load language data
  27. for name, data := range languageData {
  28. lm.Info[name] = data
  29. lm.translations[name] = data.Translations
  30. }
  31. return &lm
  32. }
  33. // Count returns how many languages we have.
  34. func (lm *LanguageManager) Count() int {
  35. lm.RLock()
  36. defer lm.RUnlock()
  37. return len(lm.Info)
  38. }
  39. // Codes returns the proper language codes for the given casefolded language codes.
  40. func (lm *LanguageManager) Codes(codes []string) []string {
  41. lm.RLock()
  42. defer lm.RUnlock()
  43. var newCodes []string
  44. for _, code := range codes {
  45. info, exists := lm.Info[code]
  46. if exists {
  47. newCodes = append(newCodes, info.Code)
  48. }
  49. }
  50. if len(newCodes) == 0 {
  51. newCodes = []string{"en"}
  52. }
  53. return newCodes
  54. }
  55. // Translate returns the given string, translated into the given language.
  56. func (lm *LanguageManager) Translate(languages []string, originalString string) string {
  57. // not using any special languages
  58. if len(languages) == 0 || languages[0] == "en" || len(lm.translations) == 0 {
  59. return originalString
  60. }
  61. lm.RLock()
  62. defer lm.RUnlock()
  63. for _, lang := range languages {
  64. lang = strings.ToLower(lang)
  65. if lang == "en" {
  66. return originalString
  67. }
  68. translations, exists := lm.translations[lang]
  69. if !exists {
  70. continue
  71. }
  72. newString, exists := translations[originalString]
  73. if !exists {
  74. continue
  75. }
  76. // found a valid translation!
  77. return newString
  78. }
  79. // didn't find any translation
  80. return originalString
  81. }