webuiServer.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "/var/www/olivetin/",
  23. "/etc/OliveTin/webui/",
  24. }
  25. for _, dir := range directoriesToSearch {
  26. if _, err := os.Stat(dir); !os.IsNotExist(err) {
  27. log.WithFields(log.Fields{
  28. "dir": dir,
  29. }).Infof("Found the webui directory")
  30. return dir
  31. }
  32. }
  33. log.Warnf("Did not find the webui directory, you will probably get 404 errors.")
  34. return "./webui" // Should not exist
  35. }
  36. func generateWebUISettings(w http.ResponseWriter, r *http.Request) {
  37. restAddress := ""
  38. if !cfg.UseSingleHTTPFrontend {
  39. restAddress = cfg.ExternalRestAddress
  40. }
  41. jsonRet, _ := json.Marshal(webUISettings{
  42. Rest: restAddress + "/api/",
  43. ThemeName: cfg.ThemeName,
  44. HideNavigation: cfg.HideNavigation,
  45. AvailableVersion: updatecheck.AvailableVersion,
  46. CurrentVersion: updatecheck.CurrentVersion,
  47. ShowNewVersions: cfg.ShowNewVersions,
  48. })
  49. _, err := w.Write([]byte(jsonRet))
  50. if err != nil {
  51. log.Warnf("Could not write webui settings: %v", err)
  52. }
  53. }
  54. func startWebUIServer(cfg *config.Config) {
  55. log.WithFields(log.Fields{
  56. "address": cfg.ListenAddressWebUI,
  57. }).Info("Starting WebUI server")
  58. mux := http.NewServeMux()
  59. mux.Handle("/", http.FileServer(http.Dir(findWebuiDir())))
  60. mux.HandleFunc("/webUiSettings.json", generateWebUISettings)
  61. srv := &http.Server{
  62. Addr: cfg.ListenAddressWebUI,
  63. Handler: mux,
  64. }
  65. log.Fatal(srv.ListenAndServe())
  66. }