webuiServer.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package httpservers
  2. import (
  3. "encoding/json"
  4. // cors "github.com/jamesread/OliveTin/internal/cors"
  5. log "github.com/sirupsen/logrus"
  6. "net/http"
  7. "os"
  8. config "github.com/jamesread/OliveTin/internal/config"
  9. updatecheck "github.com/jamesread/OliveTin/internal/updatecheck"
  10. )
  11. type webUISettings struct {
  12. Rest string
  13. ThemeName string
  14. HideNavigation bool
  15. AvailableVersion string
  16. CurrentVersion string
  17. ShowNewVersions bool
  18. }
  19. func findWebuiDir() string {
  20. directoriesToSearch := []string{
  21. "./webui",
  22. "/usr/share/OliveTin/webui/",
  23. "/var/www/olivetin/",
  24. "/etc/OliveTin/webui/",
  25. }
  26. for _, dir := range directoriesToSearch {
  27. if _, err := os.Stat(dir); !os.IsNotExist(err) {
  28. log.WithFields(log.Fields{
  29. "dir": dir,
  30. }).Infof("Found the webui directory")
  31. return dir
  32. }
  33. }
  34. log.Warnf("Did not find the webui directory, you will probably get 404 errors.")
  35. return "./webui" // Should not exist
  36. }
  37. func generateWebUISettings(w http.ResponseWriter, r *http.Request) {
  38. restAddress := ""
  39. if !cfg.UseSingleHTTPFrontend {
  40. restAddress = cfg.ExternalRestAddress
  41. }
  42. jsonRet, _ := json.Marshal(webUISettings{
  43. Rest: restAddress + "/api/",
  44. ThemeName: cfg.ThemeName,
  45. HideNavigation: cfg.HideNavigation,
  46. AvailableVersion: updatecheck.AvailableVersion,
  47. CurrentVersion: updatecheck.CurrentVersion,
  48. ShowNewVersions: cfg.ShowNewVersions,
  49. })
  50. _, err := w.Write([]byte(jsonRet))
  51. if err != nil {
  52. log.Warnf("Could not write webui settings: %v", err)
  53. }
  54. }
  55. func startWebUIServer(cfg *config.Config) {
  56. log.WithFields(log.Fields{
  57. "address": cfg.ListenAddressWebUI,
  58. }).Info("Starting WebUI server")
  59. mux := http.NewServeMux()
  60. mux.Handle("/", http.FileServer(http.Dir(findWebuiDir())))
  61. mux.HandleFunc("/webUiSettings.json", generateWebUISettings)
  62. srv := &http.Server{
  63. Addr: cfg.ListenAddressWebUI,
  64. Handler: mux,
  65. }
  66. log.Fatal(srv.ListenAndServe())
  67. }