105 lines
2.1 KiB
Go
105 lines
2.1 KiB
Go
package pretix
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"maunium.net/go/mautrix/event"
|
|
)
|
|
|
|
const (
|
|
eventOrderPlaced = "pretix.event.order.placed"
|
|
|
|
urlIndividualOrder = "%s/api/v1/organizers/%s/events/%s/orders/%s/"
|
|
)
|
|
|
|
func (s Server) orderPlaced(w http.ResponseWriter, r *http.Request) {
|
|
if r.Header.Get("Content-Type") != "application/json" {
|
|
writeStatus(w, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
data := struct{
|
|
Action string
|
|
Code string
|
|
Event string
|
|
Organizer string
|
|
}{}
|
|
decoder := json.NewDecoder(r.Body)
|
|
|
|
err := decoder.Decode(&data)
|
|
if err != nil {
|
|
writeStatus(w, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if data.Action != eventOrderPlaced {
|
|
writeStatus(w, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodGet, s.buildURL(urlIndividualOrder, data.Organizer, data.Event, data.Code), nil)
|
|
if err != nil {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("Authorization", fmt.Sprint("Token ", s.config.APIToken))
|
|
|
|
resp, err := s.client.Do(req)
|
|
if err != nil {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != 200 {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if resp.Header.Get("Content-Type") != "application/json" {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
decoder = json.NewDecoder(resp.Body)
|
|
order := struct{
|
|
Code string
|
|
Datetime time.Time
|
|
Positions []struct{
|
|
Price string
|
|
}
|
|
}{}
|
|
|
|
err = decoder.Decode(&order)
|
|
if err != nil {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
result, err := s.db.Exec("INSERT INTO orders VALUES(?);", order.Code)
|
|
if err != nil {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
rowsAffected, err := result.RowsAffected()
|
|
if err != nil {
|
|
writeStatus(w, http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if rowsAffected > 0 && order.Datetime.Add(72 * time.Hour).After(time.Now()) { // pretix retries failed webhooks for up to three days
|
|
message := event.MessageEventContent{
|
|
MsgType: event.MsgText,
|
|
Body: fmt.Sprintf("%+v", order),
|
|
}
|
|
|
|
s.matrix.Broadcast(&message)
|
|
}
|
|
}
|