webuiServer.go 5.0 KB

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