Sync production source including routing, billing, Astra detection and public uptime. Update custom build instructions and license packaging.
65 lines
2.2 KiB
Go
65 lines
2.2 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/model"
|
|
"github.com/tidwall/gjson"
|
|
)
|
|
|
|
// Visitor sessions belong to a single detection. Keep them in its private task
|
|
// metadata until completion so polling can resume after a process restart.
|
|
type manxueVisitorSession struct {
|
|
Cookies []*http.Cookie `json:"manxue_cookies,omitempty"`
|
|
}
|
|
|
|
func manxueRunRequest(ctx context.Context, run *model.DetectionRun, method, path string, payload any, key string) (gjson.Result, error) {
|
|
var session manxueVisitorSession
|
|
_ = common.UnmarshalJsonStr(run.Result, &session)
|
|
if len(session.Cookies) == 0 && !(method == http.MethodPost && run.RemoteID == "") {
|
|
return manxueRequest(ctx, method, path, payload, key)
|
|
}
|
|
jar, _ := cookiejar.New(nil)
|
|
origin, _ := url.Parse("https://manxue.ai/api/visitor/")
|
|
client := &http.Client{Timeout: 35 * time.Second, Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
|
if len(session.Cookies) == 0 {
|
|
if _, err := manxueRequestWithClient(ctx, client, http.MethodGet, "/api/visitor/config", nil, ""); err != nil {
|
|
return gjson.Result{}, errDetectionServiceUnavailable
|
|
}
|
|
session.Cookies = jar.Cookies(origin)
|
|
if len(session.Cookies) == 0 {
|
|
return gjson.Result{}, errDetectionServiceUnavailable
|
|
}
|
|
encoded, err := common.Marshal(session)
|
|
if err != nil {
|
|
return gjson.Result{}, err
|
|
}
|
|
if err = model.DB.Model(&model.DetectionRun{}).Where("id = ?", run.ID).Update("result", string(encoded)).Error; err != nil {
|
|
return gjson.Result{}, err
|
|
}
|
|
run.Result = string(encoded)
|
|
} else {
|
|
jar.SetCookies(origin, session.Cookies)
|
|
}
|
|
if method == http.MethodPost {
|
|
fields, ok := payload.(map[string]any)
|
|
if !ok {
|
|
return gjson.Result{}, errors.New("invalid pelican payload")
|
|
}
|
|
public := make(map[string]any, len(fields)+1)
|
|
for k, v := range fields {
|
|
public[k] = v
|
|
}
|
|
public["public"] = true
|
|
payload = public
|
|
}
|
|
return manxueRequestWithClient(ctx, client, method, strings.Replace(path, "/api/v1/tests", "/api/visitor/tests", 1), payload, key)
|
|
}
|