webuiServer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. SshFoundKey string
  29. SshFoundConfig string
  30. EnableCustomJs bool
  31. AuthLoginUrl string
  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, err = 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. func generateWebUISettings(w http.ResponseWriter, r *http.Request) {
  88. jsonRet, _ := json.Marshal(webUISettings{
  89. Rest: cfg.ExternalRestAddress + "/api/",
  90. ShowFooter: cfg.ShowFooter,
  91. ShowNavigation: cfg.ShowNavigation,
  92. ShowNewVersions: cfg.ShowNewVersions,
  93. AvailableVersion: installationinfo.Runtime.AvailableVersion,
  94. CurrentVersion: installationinfo.Build.Version,
  95. PageTitle: cfg.PageTitle,
  96. SectionNavigationStyle: cfg.SectionNavigationStyle,
  97. DefaultIconForBack: cfg.DefaultIconForBack,
  98. SshFoundKey: installationinfo.Runtime.SshFoundKey,
  99. SshFoundConfig: installationinfo.Runtime.SshFoundConfig,
  100. EnableCustomJs: cfg.EnableCustomJs,
  101. AuthLoginUrl: cfg.AuthLoginUrl,
  102. AdditionalLinks: cfg.AdditionalNavigationLinks,
  103. })
  104. w.Header().Add("Content-Type", "application/json")
  105. _, err := w.Write([]byte(jsonRet))
  106. if err != nil {
  107. log.Warnf("Could not write webui settings: %v", err)
  108. }
  109. }
  110. func startWebUIServer(cfg *config.Config) {
  111. log.WithFields(log.Fields{
  112. "address": cfg.ListenAddressWebUI,
  113. }).Info("Starting WebUI server")
  114. setupCustomWebuiDir()
  115. mux := http.NewServeMux()
  116. mux.Handle("/custom-webui/", http.StripPrefix("/custom-webui/", http.FileServer(http.Dir(findCustomWebuiDir()))))
  117. mux.HandleFunc("/theme.css", generateThemeCss)
  118. mux.HandleFunc("/webUiSettings.json", generateWebUISettings)
  119. webuiDir := findWebuiDir()
  120. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  121. dirName := path.Dir(r.URL.Path)
  122. // Mangle requests for any path like /logs or /config to load the webui index.html
  123. if path.Ext(r.URL.Path) == "" && r.URL.Path != "/" {
  124. log.Debugf("Mangling request for %s to /index.html", r.URL.Path)
  125. http.ServeFile(w, r, path.Join(webuiDir, "index.html"))
  126. } else {
  127. http.StripPrefix(dirName, http.FileServer(http.Dir(webuiDir))).ServeHTTP(w, r)
  128. }
  129. })
  130. srv := &http.Server{
  131. Addr: cfg.ListenAddressWebUI,
  132. Handler: mux,
  133. }
  134. log.Fatal(srv.ListenAndServe())
  135. }