handler.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package main
  2. import (
  3. "context"
  4. "log/slog"
  5. "net/http"
  6. "time"
  7. "github.com/jackc/pgx/v5/pgtype"
  8. )
  9. func (cfg Config) AddUpstream(w http.ResponseWriter, r *http.Request) {}
  10. func (cfg Config) DelUpstream(w http.ResponseWriter, r *http.Request) {}
  11. func (cfg Config) GetTickets(w http.ResponseWriter, r *http.Request) {
  12. // this will look for application/x-www-form-urlencoded
  13. // content type
  14. err := r.ParseForm()
  15. if err != nil {
  16. // if there was an error here, we return the error
  17. // as response along with a 400 http response code
  18. http.Error(w, err.Error(), http.StatusBadRequest)
  19. return
  20. }
  21. whmcs := r.FormValue("whmcs")
  22. if whmcs == "" {
  23. http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest)
  24. return
  25. }
  26. cache := r.FormValue("disallowcache") == ""
  27. srv, err := cfg.ReadServerFromDB(whmcs)
  28. if err != nil {
  29. http.Error(
  30. w,
  31. "Server %v not in my database",
  32. http.StatusBadRequest,
  33. )
  34. }
  35. slog.Debug("GetTickets handler",
  36. "whmcs", srv.name,
  37. "nocache", !cache,
  38. )
  39. slog.Info("Running callback GetTickets", "whmcs", whmcs)
  40. // Get last ticket update from db
  41. row := cfg.dbpool.QueryRow(
  42. context.Background(),
  43. "SELECT response,lastupdated FROM requestlog WHERE server = $1 ORDER BY lastupdated LIMIT 1",
  44. whmcs,
  45. )
  46. var lastupdated pgtype.Timestamp
  47. var response []any
  48. if cache {
  49. err = row.Scan(&response, &lastupdated)
  50. now := time.Now()
  51. diff := now.Sub(lastupdated.Time)
  52. // check if we have rows and if they are there, are they recent enough
  53. if err == nil && diff.Abs().Minutes() >= 5.0 {
  54. slog.Info("DB has cached response.", "lastupdated", lastupdated.Time)
  55. SendRSSResponse(w, response, lastupdated, whmcs)
  56. return
  57. }
  58. }
  59. slog.Debug("DB does not have cached response. Requesting server.")
  60. ticketarray, err := srv.GetUpstreamTickets()
  61. if err != nil {
  62. http.Error(w,
  63. err.Error(),
  64. http.StatusInternalServerError,
  65. )
  66. return
  67. }
  68. err = cfg.StoreTicketResponse(ticketarray, whmcs)
  69. if err != nil {
  70. slog.Error("Error while updating API response in database", "error", err.Error())
  71. }
  72. _, err = SendRSSResponse(w, ticketarray, lastupdated, whmcs)
  73. if err != nil {
  74. http.Error(w, err.Error(), http.StatusInternalServerError)
  75. return
  76. }
  77. }