webuiServer.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. config "github.com/OliveTin/OliveTin/internal/config"
  9. updatecheck "github.com/OliveTin/OliveTin/internal/updatecheck"
  10. )
  11. type webUISettings struct {
  12. Rest string
  13. ThemeName string
  14. ShowFooter bool
  15. ShowNavigation bool
  16. ShowNewVersions bool
  17. AvailableVersion string
  18. CurrentVersion string
  19. PageTitle string
  20. SectionNavigationStyle string
  21. }
  22. func findWebuiDir() string {
  23. directoriesToSearch := []string{
  24. cfg.WebUIDir,
  25. "../webui/",
  26. "/usr/share/OliveTin/webui/",
  27. "/var/www/OliveTin/",
  28. "/var/www/olivetin/",
  29. "/etc/OliveTin/webui/",
  30. }
  31. // Use a classic i := 0 style for loop here instead of range, as the
  32. // search order must be deterministic - the order that the slice was defined in.
  33. for i := 0; i < len(directoriesToSearch); i++ {
  34. dir := directoriesToSearch[i]
  35. if _, err := os.Stat(dir); !os.IsNotExist(err) {
  36. log.WithFields(log.Fields{
  37. "dir": dir,
  38. }).Infof("Found the webui directory")
  39. return dir
  40. }
  41. }
  42. log.Warnf("Did not find the webui directory, you will probably get 404 errors.")
  43. return "./webui" // Should not exist
  44. }
  45. func generateWebUISettings(w http.ResponseWriter, r *http.Request) {
  46. jsonRet, _ := json.Marshal(webUISettings{
  47. Rest: cfg.ExternalRestAddress + "/api/",
  48. ThemeName: cfg.ThemeName,
  49. ShowFooter: cfg.ShowFooter,
  50. ShowNavigation: cfg.ShowNavigation,
  51. ShowNewVersions: cfg.ShowNewVersions,
  52. AvailableVersion: updatecheck.AvailableVersion,
  53. CurrentVersion: updatecheck.CurrentVersion,
  54. PageTitle: cfg.PageTitle,
  55. SectionNavigationStyle: cfg.SectionNavigationStyle,
  56. })
  57. _, err := w.Write([]byte(jsonRet))
  58. if err != nil {
  59. log.Warnf("Could not write webui settings: %v", err)
  60. }
  61. }
  62. func startWebUIServer(cfg *config.Config) {
  63. log.WithFields(log.Fields{
  64. "address": cfg.ListenAddressWebUI,
  65. }).Info("Starting WebUI server")
  66. mux := http.NewServeMux()
  67. mux.Handle("/", http.FileServer(http.Dir(findWebuiDir())))
  68. mux.HandleFunc("/webUiSettings.json", generateWebUISettings)
  69. srv := &http.Server{
  70. Addr: cfg.ListenAddressWebUI,
  71. Handler: mux,
  72. }
  73. log.Fatal(srv.ListenAndServe())
  74. }