package main import ( "context" "encoding/json" "fmt" "log/slog" "net/http" "strconv" "time" "github.com/jackc/pgx/v5/pgtype" ) func (cfg Config) AddUpstream(w http.ResponseWriter, r *http.Request) { 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 } name := r.FormValue("whmcs") endpoint := r.FormValue("endpoint") backend := r.FormValue("backend") identifier := r.FormValue("identifier") secret := r.FormValue("secret") srv := Server{Name: name, Backend: backend, Endpoint: endpoint, Identifier: identifier, Secret: secret} if srv.Name == "" { http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest) return } if srv.Endpoint == "" { http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest) return } if srv.Identifier == "" { http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest) return } if srv.Secret == "" { http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest) return } if srv.Backend == "" { http.Error(w, "No WHMCS upstream name provided. Please provide one as a urlencoded form", http.StatusBadRequest) return } // Check if these details actually work _, err = srv.GetTickets() if err != nil { slog.Error("Unable to add server, credentials invalid") http.Error(w, fmt.Sprintf("Unable to add server. Got error: %v", err.Error()), http.StatusBadRequest) return } if err = srv.StoreServerInDB(cfg.dbpool); err != nil { slog.Error("Unable to add server", "error", err.Error()) http.Error( w, fmt.Sprintf("Unable to add server. Got error: %v", err.Error()), http.StatusInternalServerError, ) return } w.WriteHeader(http.StatusCreated) } 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, fmt.Sprintf("Server %v not in my database", whmcs), http.StatusBadRequest, ) return } slog.Debug("GetTickets handler", "whmcs", srv.Name, "nocache", !cache, ) slog.Info("Running callback GetTickets", "whmcs", whmcs) if cache { // Get last ticket update from db row := cfg.dbpool.QueryRow( context.Background(), "SELECT response,lastupdated FROM requestlog WHERE server = $1 ORDER BY lastupdated DESC LIMIT 1", whmcs, ) var lastupdated pgtype.Timestamp var dbresponse json.RawMessage var gettickets GetTicketsResponse err = row.Scan(&dbresponse, &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) if err = json.Unmarshal(dbresponse, &gettickets); err != nil { slog.Error("unable to unmarshal db response", "error", err.Error()) } else { SendRSSResponse(w, srv, cfg, gettickets.Tickets.Ticket, lastupdated.Time, whmcs) return } } else { if err == nil { n, err := ClearServerResponses(cfg, whmcs, "requestlog") if err != nil { slog.Error("Failed to clear cache db responses", "error", err.Error()) } else { slog.Info("Cleared cached responses", "rowsAffected", n) } } } } slog.Debug("DB does not have cached response. Requesting server.") tickets, err := srv.GetTickets() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError, ) return } err = StoreServerResponse(cfg, tickets, whmcs, "requestlog") if err != nil { slog.Error("Error while updating API response in database", "error", err.Error()) } else { slog.Info("Cached response in db") } _, err = SendRSSResponse(w, srv, cfg, tickets.Tickets.Ticket, time.Now(), whmcs) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } // Helpers func SendRSSResponse( w http.ResponseWriter, srv Server, cfg Config, ticketarray []GetTicketsTicket, lastupdated time.Time, whmcs string, ) (int, error) { rss, err := TicketsToRSS(ticketarray, srv, cfg, lastupdated) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return 0, err } w.Header().Set("Content-Type", "application/rss+xml") w.WriteHeader(http.StatusOK) w.Header().Set("Content-Length", strconv.Itoa(len(rss))) n, err := w.Write([]byte(rss)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return 0, err } return n, nil } func RaiseParseError(w http.ResponseWriter, key string, value any) { slog.Error("Failed to parse JSON response", "key", key, "value", value, ) http.Error(w, "Failed to parse JSON response from upstream", http.StatusInternalServerError) } func StoreServerResponse[T APIResponser](cfg Config, response T, servername string, tablename string) error { ticketsBytes, err := json.Marshal(response) // slog.Debug("marshalled data", "tickets", string(ticketsBytes)) if err != nil { return err } cmdtag, err := cfg.dbpool.Exec( context.Background(), fmt.Sprintf("INSERT INTO %v (server,response) VALUES ($1, $2)", tablename), servername, string(ticketsBytes), ) if err != nil { return err } if cmdtag.RowsAffected() != 1 { return fmt.Errorf("Invalid number of rows affected (%v)", cmdtag.RowsAffected()) } return nil } func ClearServerResponses(cfg Config, servername string, tablename string) (n int64, err error) { slog.Info("Clearing cache responses", "table", tablename, "server", servername) cmdTag, err := cfg.dbpool.Exec(context.Background(), fmt.Sprintf(`DELETE FROM %v WHERE server = $1`, tablename), servername, ) n = cmdTag.RowsAffected() if err != nil { return n, err } return n, nil }