feat: add account health and ghcr publishing
This commit is contained in:
1 parent
3b92608108
commit
7359171a7f
60 files changed
+2140
-203
No files matched your search
@@ -7,18 +7,19 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"ds2api/internal/account"
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
)
|
||||
|
||||
func (c *Client) Login(ctx context.Context, acc config.Account) (string, error) {
|
||||
clients := c.requestClientsForAccount(acc)
|
||||
accountID := strings.TrimSpace(acc.Identifier())
|
||||
payload := map[string]any{
|
||||
"password": strings.TrimSpace(acc.Password),
|
||||
"device_id": "deepseek_to_api",
|
||||
"os": "android",
|
||||
"device_id": DeviceID(accountID),
|
||||
"os": "Android",
|
||||
}
|
||||
if email := strings.TrimSpace(acc.Email); email != "" {
|
||||
payload["email"] = email
|
||||
@@ -62,10 +63,25 @@ func (c *Client) CreateSession(ctx context.Context, a *auth.RequestAuth, maxAtte
|
||||
resp, status, err := c.postJSONWithStatus(ctx, clients.regular, clients.fallback, dsprotocol.DeepSeekCreateSessionURL, headers, map[string]any{"agent": "chat"})
|
||||
if err != nil {
|
||||
config.Logger.Warn("[create_session] request error", "error", err, "account", a.AccountID)
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
code, bizCode, msg, bizMsg := extractResponseStatus(resp)
|
||||
if muted, muteErr := c.handleMutedResponse(ctx, a, "create session", resp); muted {
|
||||
if muteErr != nil {
|
||||
return "", muteErr
|
||||
}
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
if status == http.StatusOK && code == 0 && bizCode == 0 {
|
||||
sessionID := extractCreateSessionID(resp)
|
||||
if sessionID != "" {
|
||||
@@ -80,9 +96,10 @@ func (c *Client) CreateSession(ctx context.Context, a *auth.RequestAuth, maxAtte
|
||||
continue
|
||||
}
|
||||
}
|
||||
if c.Auth.SwitchAccount(ctx, a) {
|
||||
if c.Auth.SwitchAccountWithPenalty(ctx, a, penaltyForFailedStatus(status, code, bizCode, msg, bizMsg)) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -115,10 +132,25 @@ func (c *Client) GetPowForTarget(ctx context.Context, a *auth.RequestAuth, targe
|
||||
config.Logger.Warn("[get_pow] request error", "error", err, "account", a.AccountID, "target_path", targetPath)
|
||||
lastFailureKind = FailureUnknown
|
||||
lastFailureMessage = err.Error()
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
code, bizCode, msg, bizMsg := extractResponseStatus(resp)
|
||||
if muted, muteErr := c.handleMutedResponse(ctx, a, "get pow", resp); muted {
|
||||
if muteErr != nil {
|
||||
return "", muteErr
|
||||
}
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
if status == http.StatusOK && code == 0 && bizCode == 0 {
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizData, _ := data["biz_data"].(map[string]any)
|
||||
@@ -144,9 +176,10 @@ func (c *Client) GetPowForTarget(ctx context.Context, a *auth.RequestAuth, targe
|
||||
continue
|
||||
}
|
||||
}
|
||||
if c.Auth.SwitchAccount(ctx, a) {
|
||||
if c.Auth.SwitchAccountWithPenalty(ctx, a, penaltyForFailedStatus(status, code, bizCode, msg, bizMsg)) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -157,139 +190,3 @@ func (c *Client) GetPowForTarget(ctx context.Context, a *auth.RequestAuth, targe
|
||||
}
|
||||
return "", errors.New("get pow failed")
|
||||
}
|
||||
|
||||
func (c *Client) authHeaders(token string) map[string]string {
|
||||
headers := make(map[string]string, len(dsprotocol.BaseHeaders)+1)
|
||||
for k, v := range dsprotocol.BaseHeaders {
|
||||
headers[k] = v
|
||||
}
|
||||
headers["authorization"] = "Bearer " + token
|
||||
return headers
|
||||
}
|
||||
|
||||
func isTokenInvalid(status int, code int, bizCode int, msg string, bizMsg string) bool {
|
||||
msg = strings.ToLower(strings.TrimSpace(msg) + " " + strings.TrimSpace(bizMsg))
|
||||
if status == http.StatusUnauthorized || status == http.StatusForbidden {
|
||||
return true
|
||||
}
|
||||
if code == 40001 || code == 40002 || code == 40003 || bizCode == 40001 || bizCode == 40002 || bizCode == 40003 {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(msg, "token") ||
|
||||
strings.Contains(msg, "unauthorized") ||
|
||||
strings.Contains(msg, "expired") ||
|
||||
strings.Contains(msg, "not login") ||
|
||||
strings.Contains(msg, "login required") ||
|
||||
strings.Contains(msg, "invalid jwt")
|
||||
}
|
||||
|
||||
func shouldAttemptRefresh(status int, code int, bizCode int, msg string, bizMsg string) bool {
|
||||
if isTokenInvalid(status, code, bizCode, msg, bizMsg) {
|
||||
return true
|
||||
}
|
||||
// Some DeepSeek failures come back as HTTP 200/code=0 but with non-zero biz_code.
|
||||
// Only attempt refresh when these biz failures still look auth-related.
|
||||
return status == http.StatusOK &&
|
||||
code == 0 &&
|
||||
bizCode != 0 &&
|
||||
isAuthIndicativeBizFailure(msg, bizMsg)
|
||||
}
|
||||
|
||||
func isAuthIndicativeBizFailure(msg string, bizMsg string) bool {
|
||||
combined := strings.ToLower(strings.TrimSpace(msg) + " " + strings.TrimSpace(bizMsg))
|
||||
authKeywords := []string{
|
||||
"auth",
|
||||
"authorization",
|
||||
"credential",
|
||||
"expired",
|
||||
"invalid jwt",
|
||||
"jwt",
|
||||
"login",
|
||||
"not login",
|
||||
"session expired",
|
||||
"token",
|
||||
"unauthorized",
|
||||
"登录",
|
||||
"未登录",
|
||||
"认证",
|
||||
"凭证",
|
||||
"会话过期",
|
||||
"令牌",
|
||||
}
|
||||
for _, keyword := range authKeywords {
|
||||
if strings.Contains(combined, keyword) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func authFailureKind(useConfigToken bool) FailureKind {
|
||||
if useConfigToken {
|
||||
return FailureManagedUnauthorized
|
||||
}
|
||||
return FailureDirectUnauthorized
|
||||
}
|
||||
|
||||
func failureMessage(msg string, bizMsg string, fallback string) string {
|
||||
if trimmed := strings.TrimSpace(bizMsg); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
if trimmed := strings.TrimSpace(msg); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
return strings.TrimSpace(fallback)
|
||||
}
|
||||
|
||||
// DeepSeek has returned create-session ids in both biz_data.id and
|
||||
// biz_data.chat_session.id across observed response variants; accept either.
|
||||
func extractCreateSessionID(resp map[string]any) string {
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizData, _ := data["biz_data"].(map[string]any)
|
||||
if sessionID, _ := bizData["id"].(string); strings.TrimSpace(sessionID) != "" {
|
||||
return strings.TrimSpace(sessionID)
|
||||
}
|
||||
if chatSession, ok := bizData["chat_session"].(map[string]any); ok {
|
||||
if sessionID, _ := chatSession["id"].(string); strings.TrimSpace(sessionID) != "" {
|
||||
return strings.TrimSpace(sessionID)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractResponseStatus(resp map[string]any) (code int, bizCode int, msg string, bizMsg string) {
|
||||
code = intFrom(resp["code"])
|
||||
msg, _ = resp["msg"].(string)
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizCode = intFrom(data["biz_code"])
|
||||
bizMsg, _ = data["biz_msg"].(string)
|
||||
if strings.TrimSpace(bizMsg) == "" {
|
||||
if bizData, ok := data["biz_data"].(map[string]any); ok {
|
||||
bizMsg, _ = bizData["msg"].(string)
|
||||
}
|
||||
}
|
||||
return code, bizCode, msg, bizMsg
|
||||
}
|
||||
|
||||
func normalizeMobileForLogin(raw string) (mobile string, areaCode any) {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" {
|
||||
return "", nil
|
||||
}
|
||||
hasPlus := strings.HasPrefix(s, "+")
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for _, r := range s {
|
||||
if unicode.IsDigit(r) {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
digits := b.String()
|
||||
if digits == "" {
|
||||
return "", nil
|
||||
}
|
||||
if (hasPlus || strings.HasPrefix(digits, "86")) && strings.HasPrefix(digits, "86") && len(digits) == 13 {
|
||||
return digits[2:], nil
|
||||
}
|
||||
return digits, nil
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"ds2api/internal/config"
|
||||
)
|
||||
|
||||
type captureLoginDoer struct {
|
||||
method string
|
||||
url string
|
||||
headers http.Header
|
||||
body []byte
|
||||
}
|
||||
|
||||
func (d *captureLoginDoer) Do(req *http.Request) (*http.Response, error) {
|
||||
d.method = req.Method
|
||||
d.url = req.URL.String()
|
||||
d.headers = req.Header.Clone()
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d.body = body
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"code":0,"msg":"","data":{"biz_code":0,"biz_msg":"","biz_data":{"user":{"token":"token-from-email-login"}}}}`,
|
||||
)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestLoginPrefersEmailPayloadWhenEmailPresent(t *testing.T) {
|
||||
doer := &captureLoginDoer{}
|
||||
c := &Client{
|
||||
regular: doer,
|
||||
stream: doer,
|
||||
fallback: &http.Client{},
|
||||
fallbackS: &http.Client{},
|
||||
}
|
||||
|
||||
token, err := c.Login(context.Background(), config.Account{
|
||||
Email: "global@example.com",
|
||||
Mobile: "+8613800138000",
|
||||
Password: "secret",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("login returned error: %v", err)
|
||||
}
|
||||
if token != "token-from-email-login" {
|
||||
t.Fatalf("unexpected token: %q", token)
|
||||
}
|
||||
if doer.method != http.MethodPost {
|
||||
t.Fatalf("unexpected method: %q", doer.method)
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(doer.body, &payload); err != nil {
|
||||
t.Fatalf("decode payload: %v", err)
|
||||
}
|
||||
if payload["email"] != "global@example.com" {
|
||||
t.Fatalf("expected email payload, got %#v", payload)
|
||||
}
|
||||
if _, ok := payload["mobile"]; ok {
|
||||
t.Fatalf("did not expect mobile in email login payload, got %#v", payload)
|
||||
}
|
||||
if _, ok := payload["area_code"]; ok {
|
||||
t.Fatalf("did not expect area_code in email login payload, got %#v", payload)
|
||||
}
|
||||
if payload["password"] != "secret" {
|
||||
t.Fatalf("expected password preserved, got %#v", payload)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
dsprotocol "ds2api/internal/deepseek/protocol"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"ds2api/internal/account"
|
||||
)
|
||||
|
||||
func penaltyForFailedStatus(status int, code int, bizCode int, msg string, bizMsg string) account.PenaltyKind {
|
||||
if isTokenInvalid(status, code, bizCode, msg, bizMsg) || isAuthIndicativeBizFailure(msg, bizMsg) {
|
||||
return account.PenaltyAuthFailed
|
||||
}
|
||||
switch {
|
||||
case status == http.StatusTooManyRequests:
|
||||
return account.PenaltyHTTP429
|
||||
case status == http.StatusForbidden:
|
||||
return account.PenaltyHTTP403
|
||||
case status >= 500 && status <= 599:
|
||||
return account.PenaltyHTTP5xx
|
||||
default:
|
||||
return account.PenaltyUnknown
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) authHeaders(token string) map[string]string {
|
||||
headers := make(map[string]string, len(dsprotocol.BaseHeaders)+1)
|
||||
for k, v := range dsprotocol.BaseHeaders {
|
||||
headers[k] = v
|
||||
}
|
||||
headers["authorization"] = "Bearer " + token
|
||||
return headers
|
||||
}
|
||||
|
||||
func isTokenInvalid(status int, code int, bizCode int, msg string, bizMsg string) bool {
|
||||
msg = strings.ToLower(strings.TrimSpace(msg) + " " + strings.TrimSpace(bizMsg))
|
||||
if status == http.StatusUnauthorized || status == http.StatusForbidden {
|
||||
return true
|
||||
}
|
||||
if code == 40001 || code == 40002 || code == 40003 || bizCode == 40001 || bizCode == 40002 || bizCode == 40003 {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(msg, "token") ||
|
||||
strings.Contains(msg, "unauthorized") ||
|
||||
strings.Contains(msg, "expired") ||
|
||||
strings.Contains(msg, "not login") ||
|
||||
strings.Contains(msg, "login required") ||
|
||||
strings.Contains(msg, "invalid jwt")
|
||||
}
|
||||
|
||||
func shouldAttemptRefresh(status int, code int, bizCode int, msg string, bizMsg string) bool {
|
||||
if isTokenInvalid(status, code, bizCode, msg, bizMsg) {
|
||||
return true
|
||||
}
|
||||
// Some DeepSeek failures come back as HTTP 200/code=0 but with non-zero biz_code.
|
||||
// Only attempt refresh when these biz failures still look auth-related.
|
||||
return status == http.StatusOK &&
|
||||
code == 0 &&
|
||||
bizCode != 0 &&
|
||||
isAuthIndicativeBizFailure(msg, bizMsg)
|
||||
}
|
||||
|
||||
func isAuthIndicativeBizFailure(msg string, bizMsg string) bool {
|
||||
combined := strings.ToLower(strings.TrimSpace(msg) + " " + strings.TrimSpace(bizMsg))
|
||||
authKeywords := []string{
|
||||
"auth",
|
||||
"authorization",
|
||||
"credential",
|
||||
"expired",
|
||||
"invalid jwt",
|
||||
"jwt",
|
||||
"login",
|
||||
"not login",
|
||||
"session expired",
|
||||
"token",
|
||||
"unauthorized",
|
||||
"登录",
|
||||
"未登录",
|
||||
"认证",
|
||||
"凭证",
|
||||
"会话过期",
|
||||
"令牌",
|
||||
}
|
||||
for _, keyword := range authKeywords {
|
||||
if strings.Contains(combined, keyword) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func authFailureKind(useConfigToken bool) FailureKind {
|
||||
if useConfigToken {
|
||||
return FailureManagedUnauthorized
|
||||
}
|
||||
return FailureDirectUnauthorized
|
||||
}
|
||||
|
||||
func failureMessage(msg string, bizMsg string, fallback string) string {
|
||||
if trimmed := strings.TrimSpace(bizMsg); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
if trimmed := strings.TrimSpace(msg); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
return strings.TrimSpace(fallback)
|
||||
}
|
||||
|
||||
// DeepSeek has returned create-session ids in both biz_data.id and
|
||||
// biz_data.chat_session.id across observed response variants; accept either.
|
||||
func extractCreateSessionID(resp map[string]any) string {
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizData, _ := data["biz_data"].(map[string]any)
|
||||
if sessionID, _ := bizData["id"].(string); strings.TrimSpace(sessionID) != "" {
|
||||
return strings.TrimSpace(sessionID)
|
||||
}
|
||||
if chatSession, ok := bizData["chat_session"].(map[string]any); ok {
|
||||
if sessionID, _ := chatSession["id"].(string); strings.TrimSpace(sessionID) != "" {
|
||||
return strings.TrimSpace(sessionID)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractResponseStatus(resp map[string]any) (code int, bizCode int, msg string, bizMsg string) {
|
||||
code = intFrom(resp["code"])
|
||||
msg, _ = resp["msg"].(string)
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizCode = intFrom(data["biz_code"])
|
||||
bizMsg, _ = data["biz_msg"].(string)
|
||||
if strings.TrimSpace(bizMsg) == "" {
|
||||
if bizData, ok := data["biz_data"].(map[string]any); ok {
|
||||
bizMsg, _ = bizData["msg"].(string)
|
||||
}
|
||||
}
|
||||
return code, bizCode, msg, bizMsg
|
||||
}
|
||||
|
||||
func normalizeMobileForLogin(raw string) (mobile string, areaCode any) {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" {
|
||||
return "", nil
|
||||
}
|
||||
hasPlus := strings.HasPrefix(s, "+")
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for _, r := range s {
|
||||
if unicode.IsDigit(r) {
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
digits := b.String()
|
||||
if digits == "" {
|
||||
return "", nil
|
||||
}
|
||||
if (hasPlus || strings.HasPrefix(digits, "86")) && strings.HasPrefix(digits, "86") && len(digits) == 13 {
|
||||
return digits[2:], nil
|
||||
}
|
||||
return digits, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"ds2api/internal/account"
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
trans "ds2api/internal/deepseek/transport"
|
||||
@@ -26,11 +27,39 @@ func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payloa
|
||||
for attempts < maxAttempts {
|
||||
resp, err := c.streamPost(ctx, clients.stream, dsprotocol.DeepSeekCompletionURL, headers, payload)
|
||||
if err != nil {
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
nextPow, powErr := c.GetPow(ctx, a, maxAttempts)
|
||||
if powErr != nil {
|
||||
return nil, powErr
|
||||
}
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
headers = c.authHeaders(a.DeepSeekToken)
|
||||
headers["x-ds-pow-response"] = nextPow
|
||||
powResp = nextPow
|
||||
}
|
||||
attempts++
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
muted, muteErr := c.detectCompletionMute(ctx, a, resp)
|
||||
if muteErr != nil {
|
||||
_ = resp.Body.Close()
|
||||
return nil, muteErr
|
||||
}
|
||||
if muted {
|
||||
_ = resp.Body.Close()
|
||||
nextPow, powErr := c.GetPow(ctx, a, maxAttempts)
|
||||
if powErr != nil {
|
||||
return nil, powErr
|
||||
}
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
headers = c.authHeaders(a.DeepSeekToken)
|
||||
headers["x-ds-pow-response"] = nextPow
|
||||
powResp = nextPow
|
||||
continue
|
||||
}
|
||||
if captureSession != nil {
|
||||
resp.Body = captureSession.WrapBody(resp.Body, resp.StatusCode)
|
||||
}
|
||||
@@ -40,13 +69,37 @@ func (c *Client) CallCompletion(ctx context.Context, a *auth.RequestAuth, payloa
|
||||
if captureSession != nil {
|
||||
resp.Body = captureSession.WrapBody(resp.Body, resp.StatusCode)
|
||||
}
|
||||
penalty := completionPenaltyForStatus(resp.StatusCode)
|
||||
_ = resp.Body.Close()
|
||||
if a.UseConfigToken && penalty != account.PenaltyUnknown && c.Auth.SwitchAccountWithPenalty(ctx, a, penalty) {
|
||||
nextPow, powErr := c.GetPow(ctx, a, maxAttempts)
|
||||
if powErr != nil {
|
||||
return nil, powErr
|
||||
}
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
headers = c.authHeaders(a.DeepSeekToken)
|
||||
headers["x-ds-pow-response"] = nextPow
|
||||
powResp = nextPow
|
||||
}
|
||||
attempts++
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
return nil, errors.New("completion failed")
|
||||
}
|
||||
|
||||
func completionPenaltyForStatus(status int) account.PenaltyKind {
|
||||
switch {
|
||||
case status == http.StatusTooManyRequests:
|
||||
return account.PenaltyHTTP429
|
||||
case status == http.StatusForbidden:
|
||||
return account.PenaltyHTTP403
|
||||
case status >= 500 && status <= 599:
|
||||
return account.PenaltyHTTP5xx
|
||||
default:
|
||||
return account.PenaltyUnknown
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) streamPost(ctx context.Context, doer trans.Doer, url string, headers map[string]string, payload any) (*http.Response, error) {
|
||||
b, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
|
||||
@@ -37,8 +37,8 @@ func NewClient(store *config.Store, resolver *auth.Resolver) *Client {
|
||||
capture: devcapture.Global(),
|
||||
regular: trans.New(60 * time.Second),
|
||||
stream: trans.New(0),
|
||||
fallback: &http.Client{Timeout: 60 * time.Second},
|
||||
fallbackS: &http.Client{Timeout: 0},
|
||||
fallback: trans.NewFallbackClient(60*time.Second, nil),
|
||||
fallbackS: trans.NewFallbackClient(0, nil),
|
||||
maxRetries: 3,
|
||||
proxyClients: map[string]requestClients{},
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"ds2api/internal/account"
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
)
|
||||
@@ -55,6 +56,12 @@ func (c *Client) GetSessionCount(ctx context.Context, a *auth.RequestAuth, maxAt
|
||||
resp, status, err := c.getJSONWithStatus(ctx, clients.regular, reqURL, headers)
|
||||
if err != nil {
|
||||
config.Logger.Warn("[get_session_count] request error", "error", err, "account", a.AccountID)
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
@@ -92,9 +99,10 @@ func (c *Client) GetSessionCount(ctx context.Context, a *auth.RequestAuth, maxAt
|
||||
continue
|
||||
}
|
||||
}
|
||||
if c.Auth.SwitchAccount(ctx, a) {
|
||||
if c.Auth.SwitchAccountWithPenalty(ctx, a, penaltyForFailedStatus(status, code, bizCode, msg, bizMsg)) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"ds2api/internal/account"
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
)
|
||||
@@ -47,6 +48,12 @@ func (c *Client) DeleteSession(ctx context.Context, a *auth.RequestAuth, session
|
||||
resp, status, err := c.postJSONWithStatus(ctx, clients.regular, clients.fallback, dsprotocol.DeepSeekDeleteSessionURL, headers, payload)
|
||||
if err != nil {
|
||||
config.Logger.Warn("[delete_session] request error", "error", err, "session_id", sessionID)
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
@@ -67,9 +74,10 @@ func (c *Client) DeleteSession(ctx context.Context, a *auth.RequestAuth, session
|
||||
continue
|
||||
}
|
||||
}
|
||||
if c.Auth.SwitchAccount(ctx, a) {
|
||||
if c.Auth.SwitchAccountWithPenalty(ctx, a, penaltyForFailedStatus(status, code, bizCode, msg, bizMsg)) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
clients = c.requestClientsForAuth(ctx, a)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ds2api/internal/account"
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
trans "ds2api/internal/deepseek/transport"
|
||||
@@ -90,6 +91,9 @@ func (c *Client) UploadFile(ctx context.Context, a *auth.RequestAuth, req Upload
|
||||
powHeader = ""
|
||||
lastFailureKind = FailureUnknown
|
||||
lastFailureMessage = err.Error()
|
||||
if a.UseConfigToken && c.Auth.SwitchAccountWithPenalty(ctx, a, account.PenaltyNetwork) {
|
||||
refreshed = false
|
||||
}
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
@@ -110,6 +114,15 @@ func (c *Client) UploadFile(ctx context.Context, a *auth.RequestAuth, req Upload
|
||||
}
|
||||
}
|
||||
code, bizCode, msg, bizMsg := extractResponseStatus(parsed)
|
||||
if muted, muteErr := c.handleMutedResponse(ctx, a, "upload file", parsed); muted {
|
||||
if muteErr != nil {
|
||||
return nil, muteErr
|
||||
}
|
||||
refreshed = false
|
||||
powHeader = ""
|
||||
attempts++
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode == http.StatusOK && code == 0 && bizCode == 0 {
|
||||
result := extractUploadFileResult(parsed)
|
||||
result.Raw = parsed
|
||||
@@ -150,7 +163,7 @@ func (c *Client) UploadFile(ctx context.Context, a *auth.RequestAuth, req Upload
|
||||
continue
|
||||
}
|
||||
}
|
||||
if c.Auth.SwitchAccount(ctx, a) {
|
||||
if c.Auth.SwitchAccountWithPenalty(ctx, a, penaltyForFailedStatus(resp.StatusCode, code, bizCode, msg, bizMsg)) {
|
||||
refreshed = false
|
||||
attempts++
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func DeviceID(accountIdentifier string) string {
|
||||
trimmed := strings.TrimSpace(accountIdentifier)
|
||||
if trimmed == "" {
|
||||
trimmed = "ds2api"
|
||||
}
|
||||
hash := sha512.Sum512([]byte(trimmed))
|
||||
return base64.StdEncoding.EncodeToString(hash[:])
|
||||
}
|
||||
@@ -11,6 +11,7 @@ const (
|
||||
FailureUnknown FailureKind = ""
|
||||
FailureDirectUnauthorized FailureKind = "direct_unauthorized"
|
||||
FailureManagedUnauthorized FailureKind = "managed_unauthorized"
|
||||
FailureAccountMuted FailureKind = "account_muted"
|
||||
)
|
||||
|
||||
type RequestFailure struct {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ds2api/internal/auth"
|
||||
"ds2api/internal/config"
|
||||
)
|
||||
|
||||
type muteInfo struct {
|
||||
Muted bool
|
||||
Until float64
|
||||
}
|
||||
|
||||
func extractMuteInfo(resp map[string]any) muteInfo {
|
||||
if resp == nil {
|
||||
return muteInfo{}
|
||||
}
|
||||
_, bizCode, msg, bizMsg := extractResponseStatus(resp)
|
||||
data, _ := resp["data"].(map[string]any)
|
||||
bizData, _ := data["biz_data"].(map[string]any)
|
||||
isMuted := intFrom(bizData["is_muted"]) == 1
|
||||
combined := strings.ToLower(strings.TrimSpace(msg) + " " + strings.TrimSpace(bizMsg))
|
||||
if bizCode == 5 || isMuted || strings.Contains(combined, "muted") {
|
||||
return muteInfo{Muted: true, Until: floatFrom(bizData["mute_until"])}
|
||||
}
|
||||
return muteInfo{}
|
||||
}
|
||||
|
||||
func floatFrom(v any) float64 {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
return x
|
||||
case float32:
|
||||
return float64(x)
|
||||
case int:
|
||||
return float64(x)
|
||||
case int64:
|
||||
return float64(x)
|
||||
case json.Number:
|
||||
f, _ := x.Float64()
|
||||
return f
|
||||
case string:
|
||||
f, _ := strconv.ParseFloat(strings.TrimSpace(x), 64)
|
||||
return f
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) handleMutedResponse(ctx context.Context, a *auth.RequestAuth, op string, resp map[string]any) (bool, error) {
|
||||
info := extractMuteInfo(resp)
|
||||
if !info.Muted {
|
||||
return false, nil
|
||||
}
|
||||
if a != nil && a.UseConfigToken {
|
||||
a.MarkAccountMuted(info.Until)
|
||||
config.Logger.Warn("[account_mute] upstream muted account", "op", op, "account", a.AccountID, "mute_until", info.Until)
|
||||
if a.SwitchAccount(ctx) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
msg := "account is muted"
|
||||
if info.Until > 0 {
|
||||
msg = fmt.Sprintf("%s until %.3f", msg, info.Until)
|
||||
}
|
||||
return true, &RequestFailure{Op: op, Kind: FailureAccountMuted, Message: msg}
|
||||
}
|
||||
|
||||
func (c *Client) detectCompletionMute(ctx context.Context, a *auth.RequestAuth, resp *http.Response) (bool, error) {
|
||||
if resp == nil || resp.Body == nil {
|
||||
return false, nil
|
||||
}
|
||||
contentType := strings.ToLower(resp.Header.Get("Content-Type"))
|
||||
looksLikeJSON := strings.Contains(contentType, "json")
|
||||
if !looksLikeJSON && (resp.ContentLength <= 0 || resp.ContentLength > 1<<20 || strings.Contains(contentType, "event-stream")) {
|
||||
return false, nil
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
resp.Body = io.NopCloser(bytes.NewReader(body))
|
||||
parsed := map[string]any{}
|
||||
if len(body) == 0 || json.Unmarshal(body, &parsed) != nil {
|
||||
return false, nil
|
||||
}
|
||||
return c.handleMutedResponse(ctx, a, "completion", parsed)
|
||||
}
|
||||
Reference in new issue
Block a user