webuiServer.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package httpservers
  2. import (
  3. "encoding/json"
  4. // cors "github.com/OliveTin/OliveTin/internal/cors"
  5. log "github.com/sirupsen/logrus"
  6. "net/http"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. config "github.com/OliveTin/OliveTin/internal/config"
  11. installationinfo "github.com/OliveTin/OliveTin/internal/installationinfo"
  12. sv "github.com/OliveTin/OliveTin/internal/stringvariables"
  13. )
  14. var (
  15. customThemeCss []byte
  16. customThemeCssRead = false
  17. )
  18. type webUISettings struct {
  19. Rest string
  20. ShowFooter bool
  21. ShowNavigation bool
  22. ShowNewVersions bool
  23. AvailableVersion string
  24. CurrentVersion string
  25. PageTitle string
  26. SectionNavigationStyle string
  27. DefaultIconForBack string
  28. EnableCustomJs bool
  29. AuthLoginUrl string
  30. AuthLocalLogin bool
  31. StyleMods []string
  32. AuthOAuth2Providers []publicOAuth2Provider
  33. AdditionalLinks []*config.NavigationLink
  34. }
  35. func findWebuiDir() string {
  36. directoriesToSearch := []string{
  37. cfg.WebUIDir,
  38. "../webui/",
  39. "/usr/share/OliveTin/webui/",
  40. "/var/www/OliveTin/",
  41. "/var/www/olivetin/",
  42. "/etc/OliveTin/webui/",
  43. }
  44. // Use a classic i := 0 style for loop here instead of range, as the
  45. // search order must be deterministic - the order that the slice was defined in.
  46. for i := 0; i < len(directoriesToSearch); i++ {
  47. dir := directoriesToSearch[i]
  48. absdir, _ := filepath.Abs(dir)
  49. if _, err := os.Stat(absdir); !os.IsNotExist(err) {
  50. log.WithFields(log.Fields{
  51. "dir": absdir,
  52. }).Infof("Found the webui directory")
  53. sv.Set("internal.webuidir", absdir+" ("+dir+")")
  54. return dir
  55. }
  56. }
  57. log.Warnf("Did not find the webui directory, you will probably get 404 errors.")
  58. return "./webui" // Should not exist
  59. }
  60. func findCustomWebuiDir() string {
  61. dir := path.Join(cfg.GetDir(), "custom-webui")
  62. return dir
  63. }
  64. func setupCustomWebuiDir() {
  65. dir := findCustomWebuiDir()
  66. err := os.MkdirAll(path.Join(dir, "themes/"), 0775)
  67. if err != nil {
  68. log.Warnf("Could not create themes directory: %v", err)
  69. sv.Set("internal.themesdir", err.Error())
  70. } else {
  71. sv.Set("internal.themesdir", dir)
  72. }
  73. }
  74. func generateThemeCss(w http.ResponseWriter, r *http.Request) {
  75. themeCssFilename := path.Join(findCustomWebuiDir(), "themes", cfg.ThemeName, "theme.css")
  76. if !customThemeCssRead || cfg.ThemeCacheDisabled {
  77. customThemeCssRead = true
  78. if _, err := os.Stat(themeCssFilename); err == nil {
  79. customThemeCss, _ = os.ReadFile(themeCssFilename)
  80. } else {
  81. log.Debugf("Theme CSS not read: %v", err)
  82. customThemeCss = []byte("/* not found */")
  83. }
  84. }
  85. w.Header().Add("Content-Type", "text/css")
  86. w.Write(customThemeCss)
  87. }
  88. type publicOAuth2Provider struct {
  89. Name string
  90. Title string
  91. Icon string
  92. }
  93. func buildPublicOAuth2ProvidersList(cfg *config.Config) []publicOAuth2Provider {
  94. var publicProviders []publicOAuth2Provider
  95. for _, provider := range cfg.AuthOAuth2Providers {
  96. publicProviders = append(publicProviders, publicOAuth2Provider{
  97. Name: provider.Name,
  98. Title: provider.Title,
  99. Icon: provider.Icon,
  100. })
  101. }
  102. return publicProviders
  103. }
  104. func generateWebUISettings(w http.ResponseWriter, r *http.Request) {
  105. jsonRet, _ := json.Marshal(webUISettings{
  106. Rest: cfg.ExternalRestAddress + "/api/",
  107. ShowFooter: cfg.ShowFooter,
  108. ShowNavigation: cfg.ShowNavigation,
  109. ShowNewVersions: cfg.ShowNewVersions,
  110. AvailableVersion: installationinfo.Runtime.AvailableVersion,
  111. CurrentVersion: installationinfo.Build.Version,
  112. PageTitle: cfg.PageTitle,
  113. SectionNavigationStyle: cfg.SectionNavigationStyle,
  114. DefaultIconForBack: cfg.DefaultIconForBack,
  115. EnableCustomJs: cfg.EnableCustomJs,
  116. AuthLoginUrl: cfg.AuthLoginUrl,
  117. AuthLocalLogin: cfg.AuthLocalUsers.Enabled,
  118. AuthOAuth2Providers: buildPublicOAuth2ProvidersList(cfg),
  119. AdditionalLinks: cfg.AdditionalNavigationLinks,
  120. StyleMods: cfg.StyleMods,
  121. })
  122. w.Header().Add("Content-Type", "application/json")
  123. _, err := w.Write([]byte(jsonRet))
  124. if err != nil {
  125. log.Warnf("Could not write webui settings: %v", err)
  126. }
  127. }
  128. func startWebUIServer(cfg *config.Config) {
  129. log.WithFields(log.Fields{
  130. "address": cfg.ListenAddressWebUI,
  131. }).Info("Starting WebUI server")
  132. setupCustomWebuiDir()
  133. mux := http.NewServeMux()
  134. mux.Handle("/custom-webui/", http.StripPrefix("/custom-webui/", http.FileServer(http.Dir(findCustomWebuiDir()))))
  135. mux.HandleFunc("/theme.css", generateThemeCss)
  136. mux.HandleFunc("/webUiSettings.json", generateWebUISettings)
  137. webuiDir := findWebuiDir()
  138. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  139. dirName := path.Dir(r.URL.Path)
  140. // Mangle requests for any path like /logs or /config to load the webui index.html
  141. if path.Ext(r.URL.Path) == "" && r.URL.Path != "/" {
  142. log.Debugf("Mangling request for %s to /index.html", r.URL.Path)
  143. http.ServeFile(w, r, path.Join(webuiDir, "index.html"))
  144. } else {
  145. http.StripPrefix(dirName, http.FileServer(http.Dir(webuiDir))).ServeHTTP(w, r)
  146. }
  147. })
  148. srv := &http.Server{
  149. Addr: cfg.ListenAddressWebUI,
  150. Handler: mux,
  151. }
  152. log.Fatal(srv.ListenAndServe())
  153. }