| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package main
- import (
- "context"
- "log/slog"
- "net/http"
- "time"
- "github.com/jackc/pgx/v5/pgtype"
- )
- func (cfg Config) AddUpstream(w http.ResponseWriter, r *http.Request) {}
- func (cfg Config) DelUpstream(w http.ResponseWriter, r *http.Request) {}
- func (cfg Config) GetTickets(w http.ResponseWriter, r *http.Request) {
- // this will look for application/x-www-form-urlencoded
- // content type
- err := r.ParseForm()
- if err != nil {
- // if there was an error here, we return the error
- // as response along with a 400 http response code
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- whmcs := r.FormValue("whmcs")
- if whmcs == "" {
- http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest)
- return
- }
- cache := r.FormValue("disallowcache") == ""
- srv, err := cfg.ReadServerFromDB(whmcs)
- if err != nil {
- http.Error(
- w,
- "Server %v not in my database",
- http.StatusBadRequest,
- )
- }
- slog.Debug("GetTickets handler",
- "whmcs", srv.name,
- "nocache", !cache,
- )
- slog.Info("Running callback GetTickets", "whmcs", whmcs)
- // Get last ticket update from db
- row := cfg.dbpool.QueryRow(
- context.Background(),
- "SELECT response,lastupdated FROM requestlog WHERE server = $1 ORDER BY lastupdated LIMIT 1",
- whmcs,
- )
- var lastupdated pgtype.Timestamp
- var response []any
- if cache {
- err = row.Scan(&response, &lastupdated)
- now := time.Now()
- diff := now.Sub(lastupdated.Time)
- // check if we have rows and if they are there, are they recent enough
- if err == nil && diff.Abs().Minutes() >= 5.0 {
- slog.Info("DB has cached response.", "lastupdated", lastupdated.Time)
- SendRSSResponse(w, response, lastupdated, whmcs)
- return
- }
- }
- slog.Debug("DB does not have cached response. Requesting server.")
- ticketarray, err := srv.GetUpstreamTickets()
- if err != nil {
- http.Error(w,
- err.Error(),
- http.StatusInternalServerError,
- )
- return
- }
- err = cfg.StoreTicketResponse(ticketarray, whmcs)
- if err != nil {
- slog.Error("Error while updating API response in database", "error", err.Error())
- }
- _, err = SendRSSResponse(w, ticketarray, lastupdated, whmcs)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- }
|