locale.fonts.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package main
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. "path/filepath"
  7. "strings"
  8. "imuslab.com/arozos/mod/info/logger"
  9. "imuslab.com/arozos/mod/locale"
  10. "imuslab.com/arozos/mod/locale/fonts"
  11. "imuslab.com/arozos/mod/network/gzipmiddleware"
  12. prout "imuslab.com/arozos/mod/prouter"
  13. "imuslab.com/arozos/mod/utils"
  14. )
  15. /*
  16. System locale files and font library
  17. The locale files live in ./system/locale and are served at their old
  18. address, /SystemAO/locale/*, by localeServer (mod/locale): each user gets
  19. them with the fonts they picked in System Settings > System Fonts filled
  20. in. The fonts themselves are in ./system/locale/fonts (mod/locale/fonts),
  21. their generated slices in ./system/cache/fonts.
  22. User endpoints (login required):
  23. GET /system/fonts/list families, languages and the caller's choices
  24. POST /system/fonts/preference the caller's font for a language
  25. GET /system/fonts/faces every family's faces and their files, for
  26. pages that set text in them (the Office
  27. apps): any user may use the fonts, only
  28. an administrator installs them
  29. Admin endpoints:
  30. POST /system/fonts/default the system default font for a language
  31. POST /system/fonts/upload install font files (multipart "file")
  32. POST /system/fonts/delete remove a family
  33. */
  34. var (
  35. localeServer *locale.Server
  36. fontLibrary *fonts.Library
  37. )
  38. func LocaleInit() {
  39. lib, err := fonts.NewLibrary(fonts.Options{
  40. Root: filepath.Join(localeRoot, "fonts"),
  41. CacheDir: filepath.Join("system", "cache", "fonts"),
  42. DB: sysdb,
  43. })
  44. if err != nil {
  45. logger.PrintAndLog("Locale", "Font library unavailable, locale files are served without library fonts", err)
  46. lib = nil
  47. }
  48. srv, err := locale.NewServer(locale.Options{
  49. Root: localeRoot,
  50. LegacyRoot: filepath.Join("web", "SystemAO", "locale"),
  51. Fonts: lib,
  52. })
  53. if err != nil {
  54. logger.PrintAndLog("Locale", "Unable to serve the system locale files", err)
  55. return
  56. }
  57. localeServer = srv
  58. if lib == nil {
  59. return
  60. }
  61. fontLibrary = lib
  62. go lib.Warm(srv.LanguageCodes())
  63. userRouter := prout.NewModuleRouter(prout.RouterOption{
  64. ModuleName: "",
  65. AdminOnly: false,
  66. UserHandler: userHandler,
  67. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  68. utils.SendErrorResponse(w, "Permission Denied")
  69. },
  70. })
  71. userRouter.HandleFunc("/system/fonts/list", handleFontList)
  72. userRouter.HandleFunc("/system/fonts/preference", handleFontPreference)
  73. userRouter.HandleFunc("/system/fonts/faces", handleFontFaces)
  74. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  75. ModuleName: "System Setting",
  76. AdminOnly: true,
  77. UserHandler: userHandler,
  78. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  79. utils.SendErrorResponse(w, "Permission Denied")
  80. },
  81. })
  82. adminRouter.HandleFunc("/system/fonts/default", handleFontDefault)
  83. adminRouter.HandleFunc("/system/fonts/upload", handleFontUpload)
  84. adminRouter.HandleFunc("/system/fonts/delete", handleFontDelete)
  85. }
  86. // serveLocaleRequest answers /SystemAO/locale/* for a logged in user
  87. func serveLocaleRequest(w http.ResponseWriter, r *http.Request) {
  88. username := ""
  89. if userinfo, err := userHandler.GetUserInfoFromRequest(w, r); err == nil {
  90. username = userinfo.Username
  91. }
  92. serve := func(w http.ResponseWriter, r *http.Request) {
  93. localeServer.Serve(w, r, username)
  94. }
  95. if *enable_gzip && !strings.Contains(r.URL.Path, "/fonts/slice/") && !strings.Contains(r.URL.Path, "/fonts/file/") {
  96. //Font slices are WOFF2, compressed already; a whole font can be tens
  97. //of megabytes and is fetched in ranges
  98. gzipmiddleware.CompressFunc(serve)(w, r)
  99. return
  100. }
  101. serve(w, r)
  102. }
  103. // handleFontFaces lists the installed families with the files of their
  104. // faces; the paths are relative to base
  105. func handleFontFaces(w http.ResponseWriter, r *http.Request) {
  106. js, err := json.Marshal(map[string]interface{}{
  107. "base": locale.URLPrefix + "fonts/",
  108. "families": fontLibrary.Sources(),
  109. })
  110. if err != nil {
  111. utils.SendErrorResponse(w, "Unable to list the fonts")
  112. return
  113. }
  114. utils.SendJSONResponse(w, string(js))
  115. }
  116. func handleFontList(w http.ResponseWriter, r *http.Request) {
  117. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  118. if err != nil {
  119. utils.SendErrorResponse(w, "User not logged in")
  120. return
  121. }
  122. type languageView struct {
  123. Code string `json:"code"`
  124. Name string `json:"name"`
  125. Choice string `json:"choice"` //the user's own choice, "" follows the default
  126. Default string `json:"default"` //the system default, "" or "@system" for device fonts
  127. AdminDefault string `json:"adminDefault"` //what an admin stored, "" when the factory default applies
  128. Factory string `json:"factory"` //the default shipped in defaults.json
  129. Effective string `json:"effective"` //the family in use, "" for device fonts
  130. }
  131. codes := localeServer.LanguageCodes()
  132. languages := []languageView{}
  133. for _, l := range localeServer.Languages() {
  134. languages = append(languages, languageView{
  135. Code: l.Code,
  136. Name: l.Name,
  137. Choice: fontLibrary.Choice(userinfo.Username, l.Code),
  138. Default: fontLibrary.Default(l.Code),
  139. AdminDefault: fontLibrary.AdminDefault(l.Code),
  140. Factory: fontLibrary.Factory(l.Code),
  141. Effective: fontLibrary.Effective(userinfo.Username, l.Code),
  142. })
  143. }
  144. js, _ := json.Marshal(map[string]interface{}{
  145. "isAdmin": userinfo.IsAdmin(),
  146. "maxFontSize": fonts.MaxFontSize,
  147. "languages": languages,
  148. "families": fontLibrary.Families(codes),
  149. })
  150. utils.SendJSONResponse(w, string(js))
  151. }
  152. func handleFontPreference(w http.ResponseWriter, r *http.Request) {
  153. if r.Method != http.MethodPost {
  154. utils.SendErrorResponse(w, "POST required")
  155. return
  156. }
  157. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  158. if err != nil {
  159. utils.SendErrorResponse(w, "User not logged in")
  160. return
  161. }
  162. lang, err := utils.PostPara(r, "lang")
  163. if err != nil {
  164. utils.SendErrorResponse(w, "Invalid language")
  165. return
  166. }
  167. family, _ := utils.PostPara(r, "family")
  168. if err := fontLibrary.SetChoice(userinfo.Username, lang, family); err != nil {
  169. utils.SendErrorResponse(w, err.Error())
  170. return
  171. }
  172. utils.SendOK(w)
  173. }
  174. func handleFontDefault(w http.ResponseWriter, r *http.Request) {
  175. if r.Method != http.MethodPost {
  176. utils.SendErrorResponse(w, "POST required")
  177. return
  178. }
  179. lang, err := utils.PostPara(r, "lang")
  180. if err != nil {
  181. utils.SendErrorResponse(w, "Invalid language")
  182. return
  183. }
  184. family, _ := utils.PostPara(r, "family")
  185. if err := fontLibrary.SetDefault(lang, family); err != nil {
  186. utils.SendErrorResponse(w, err.Error())
  187. return
  188. }
  189. utils.SendOK(w)
  190. }
  191. func handleFontUpload(w http.ResponseWriter, r *http.Request) {
  192. if r.Method != http.MethodPost {
  193. utils.SendErrorResponse(w, "POST required")
  194. return
  195. }
  196. r.Body = http.MaxBytesReader(w, r.Body, 4*fonts.MaxFontSize)
  197. if err := r.ParseMultipartForm(32 << 20); err != nil {
  198. utils.SendErrorResponse(w, "The upload is too large or incomplete")
  199. return
  200. }
  201. defer r.MultipartForm.RemoveAll()
  202. type result struct {
  203. File string `json:"file"`
  204. Error string `json:"error,omitempty"`
  205. Face *fonts.FaceView `json:"face,omitempty"`
  206. }
  207. results := []result{}
  208. for _, header := range r.MultipartForm.File["file"] {
  209. res := result{File: header.Filename}
  210. if header.Size > fonts.MaxFontSize {
  211. res.Error = "The font is too large"
  212. results = append(results, res)
  213. continue
  214. }
  215. f, err := header.Open()
  216. if err != nil {
  217. res.Error = "Unable to read the upload"
  218. results = append(results, res)
  219. continue
  220. }
  221. data, err := io.ReadAll(io.LimitReader(f, fonts.MaxFontSize+1))
  222. f.Close()
  223. if err != nil || len(data) > fonts.MaxFontSize {
  224. res.Error = "The font is too large"
  225. results = append(results, res)
  226. continue
  227. }
  228. face, err := fontLibrary.Install(header.Filename, data)
  229. if err != nil {
  230. res.Error = err.Error()
  231. } else {
  232. res.Face = &face
  233. }
  234. results = append(results, res)
  235. }
  236. if len(results) == 0 {
  237. utils.SendErrorResponse(w, "No font file received")
  238. return
  239. }
  240. js, _ := json.Marshal(results)
  241. utils.SendJSONResponse(w, string(js))
  242. }
  243. func handleFontDelete(w http.ResponseWriter, r *http.Request) {
  244. if r.Method != http.MethodPost {
  245. utils.SendErrorResponse(w, "POST required")
  246. return
  247. }
  248. family, err := utils.PostPara(r, "family")
  249. if err != nil {
  250. utils.SendErrorResponse(w, "Invalid family")
  251. return
  252. }
  253. if err := fontLibrary.Delete(family); err != nil {
  254. utils.SendErrorResponse(w, err.Error())
  255. return
  256. }
  257. utils.SendOK(w)
  258. }