2021-07-22 23:26:21 +03:00
|
|
|
package report
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/lus/pasty/internal/config"
|
|
|
|
"github.com/valyala/fasthttp"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ReportRequest represents a report request sent to the report webhook
|
|
|
|
type ReportRequest struct {
|
2021-07-24 18:03:40 +03:00
|
|
|
Paste string `json:"paste"`
|
|
|
|
Reason string `json:"reason"`
|
2021-07-22 23:26:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReportResponse represents a report response received from the report webhook
|
|
|
|
type ReportResponse struct {
|
2021-07-24 00:39:37 +03:00
|
|
|
Success bool `json:"success"`
|
2021-07-22 23:26:21 +03:00
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// SendReport sends a report request to the report webhook
|
|
|
|
func SendReport(reportRequest *ReportRequest) (*ReportResponse, error) {
|
|
|
|
request := fasthttp.AcquireRequest()
|
|
|
|
defer fasthttp.ReleaseRequest(request)
|
|
|
|
|
|
|
|
response := fasthttp.AcquireResponse()
|
|
|
|
defer fasthttp.ReleaseResponse(response)
|
|
|
|
|
|
|
|
request.Header.SetMethod(fasthttp.MethodPost)
|
|
|
|
request.SetRequestURI(config.Current.Reports.ReportWebhook)
|
|
|
|
if config.Current.Reports.ReportWebhookToken != "" {
|
|
|
|
request.Header.Set("Authorization", "Bearer "+config.Current.Reports.ReportWebhookToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := json.Marshal(reportRequest)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
request.SetBody(data)
|
|
|
|
|
|
|
|
if err := fasthttp.Do(request, response); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
status := response.StatusCode()
|
|
|
|
if status < 200 || status > 299 {
|
|
|
|
return nil, fmt.Errorf("the report webhook responded with an unexpected error: %d (%s)", status, string(response.Body()))
|
|
|
|
}
|
|
|
|
|
|
|
|
reportResponse := new(ReportResponse)
|
|
|
|
if err := json.Unmarshal(response.Body(), reportResponse); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return reportResponse, nil
|
|
|
|
}
|