client: Windows 客户端(WinUI3 壳 + agent-core;调试用 Electron 壳存档);localserver token 改为常数时间比较
This commit is contained in:
@@ -0,0 +1,458 @@
|
||||
// bilibili B站执行器(无浏览器投稿 + API 扫码登录)。
|
||||
// 协议依据:ForgQi/biliup(MIT)bili_webup.py 的 upos/bda2 上传链路。
|
||||
package bilibili
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Executor B站投稿执行器
|
||||
type Executor struct {
|
||||
Vault *vault.Vault
|
||||
HTTP *http.Client
|
||||
MemberBase string // 投稿 API 基址(测试可替换)
|
||||
PassportBase string // 登录 API 基址(测试可替换)
|
||||
UpOSScheme string // upos 上传协议(默认 https,测试 http)
|
||||
PollTimeout time.Duration // 扫码轮询总时长(默认 3 分钟)
|
||||
}
|
||||
|
||||
// New 构造执行器
|
||||
func New(v *vault.Vault) *Executor {
|
||||
return &Executor{
|
||||
Vault: v,
|
||||
HTTP: &http.Client{Timeout: 30 * time.Second},
|
||||
MemberBase: "https://member.bilibili.com",
|
||||
PassportBase: "https://passport.bilibili.com",
|
||||
UpOSScheme: "https",
|
||||
PollTimeout: 3 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
// Platform 平台标识
|
||||
func (e *Executor) Platform() string { return "bilibili" }
|
||||
|
||||
// credentials 凭据(保险库 JSON)
|
||||
type credentials struct {
|
||||
Cookies string `json:"cookies"`
|
||||
}
|
||||
|
||||
// Execute 发布:下载素材 → upos 上传 → 投稿 → 返回作品链接
|
||||
func (e *Executor) Execute(ctx context.Context, task exec.Task) exec.Result {
|
||||
fail := func(err string) exec.Result {
|
||||
return exec.Result{TaskID: task.TaskID, Status: "failed", Error: err}
|
||||
}
|
||||
creds, err := e.creds(task.AccountID)
|
||||
if err != nil {
|
||||
return fail("B站账号未登录(本地无凭据),请先在客户端完成扫码绑定")
|
||||
}
|
||||
if len(task.MaterialURLs) == 0 {
|
||||
return fail("任务缺少素材")
|
||||
}
|
||||
videoPath, cleanup, err := downloadFile(ctx, e.HTTP, task.MaterialURLs[0])
|
||||
if err != nil {
|
||||
return fail("素材下载失败: " + err.Error())
|
||||
}
|
||||
defer cleanup()
|
||||
part, err := e.uploadVideo(ctx, creds.Cookies, videoPath)
|
||||
if err != nil {
|
||||
return fail("视频上传失败: " + err.Error())
|
||||
}
|
||||
bvid, err := e.submit(ctx, creds.Cookies, task, part)
|
||||
if err != nil {
|
||||
return fail("投稿提交失败: " + err.Error())
|
||||
}
|
||||
return exec.Result{
|
||||
TaskID: task.TaskID,
|
||||
Status: "success",
|
||||
PublishedURL: "https://www.bilibili.com/video/" + bvid,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Executor) creds(accountID string) (*credentials, error) {
|
||||
raw, err := e.Vault.Load(accountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c credentials
|
||||
if err = json.Unmarshal(raw, &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.Cookies == "" {
|
||||
return nil, fmt.Errorf("empty cookies")
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// uploadVideo 上传视频(upos/bda2 分片),返回投稿所需的 part 信息
|
||||
func (e *Executor) uploadVideo(ctx context.Context, cookies, filePath string) (map[string]interface{}, error) {
|
||||
stat, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name := filepath.Base(filePath)
|
||||
total := stat.Size()
|
||||
|
||||
// 1) preupload 获取上传地址
|
||||
q := url.Values{}
|
||||
q.Set("r", "upos")
|
||||
q.Set("profile", "ugcupos/bup")
|
||||
q.Set("ssl", "0")
|
||||
q.Set("version", "2.8.12")
|
||||
q.Set("build", "2081200")
|
||||
q.Set("name", name)
|
||||
q.Set("size", strconv.FormatInt(total, 10))
|
||||
preURL := e.MemberBase + "/preupload?upcdn=bda2&probe_version=20221109&" + q.Encode()
|
||||
var pre struct {
|
||||
OK int `json:"OK"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Auth string `json:"auth"`
|
||||
BizID int `json:"biz_id"`
|
||||
UposURI string `json:"upos_uri"`
|
||||
ChunkSize int `json:"chunk_size"`
|
||||
}
|
||||
if err = e.getJSON(ctx, preURL, cookies, &pre); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pre.OK != 1 || pre.UposURI == "" {
|
||||
return nil, fmt.Errorf("preupload 返回异常")
|
||||
}
|
||||
upURL := e.UpOSScheme + ":" + pre.Endpoint + "/" + strings.TrimPrefix(pre.UposURI, "upos://")
|
||||
authH := map[string]string{"X-Upos-Auth": pre.Auth}
|
||||
|
||||
// 2) 申请 upload_id
|
||||
var up struct {
|
||||
UploadID string `json:"upload_id"`
|
||||
}
|
||||
if err = e.postJSON(ctx, upURL+"?uploads&output=json", cookies, authH, nil, &up); err != nil {
|
||||
return nil, fmt.Errorf("申请 upload_id 失败: %w", err)
|
||||
}
|
||||
|
||||
// 3) 分片上传
|
||||
chunkSize := pre.ChunkSize
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = 7 * 1024 * 1024
|
||||
}
|
||||
chunks := int((total + int64(chunkSize) - 1) / int64(chunkSize))
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
parts := make([]map[string]interface{}, 0, chunks)
|
||||
buf := make([]byte, chunkSize)
|
||||
for i := 0; i < chunks; i++ {
|
||||
n, rerr := io.ReadFull(f, buf)
|
||||
if rerr != nil && rerr != io.ErrUnexpectedEOF && rerr != io.EOF {
|
||||
return nil, rerr
|
||||
}
|
||||
start := i * chunkSize
|
||||
end := start + n
|
||||
pq := url.Values{}
|
||||
pq.Set("uploadId", up.UploadID)
|
||||
pq.Set("partNumber", strconv.Itoa(i+1))
|
||||
pq.Set("chunk", strconv.Itoa(i))
|
||||
pq.Set("chunks", strconv.Itoa(chunks))
|
||||
pq.Set("size", strconv.Itoa(n))
|
||||
pq.Set("start", strconv.Itoa(start))
|
||||
pq.Set("end", strconv.Itoa(end))
|
||||
pq.Set("total", strconv.FormatInt(total, 10))
|
||||
if err = e.putBody(ctx, upURL+"?"+pq.Encode(), cookies, authH, buf[:n]); err != nil {
|
||||
return nil, fmt.Errorf("分片 %d 上传失败: %w", i+1, err)
|
||||
}
|
||||
parts = append(parts, map[string]interface{}{"partNumber": i + 1, "eTag": "etag"})
|
||||
}
|
||||
|
||||
// 4) 合并分片
|
||||
mq := url.Values{}
|
||||
mq.Set("name", name)
|
||||
mq.Set("uploadId", up.UploadID)
|
||||
mq.Set("biz_id", strconv.Itoa(pre.BizID))
|
||||
mq.Set("output", "json")
|
||||
mq.Set("profile", "ugcupos/bup")
|
||||
var merged struct {
|
||||
OK int `json:"OK"`
|
||||
}
|
||||
if err = e.postJSON(ctx, upURL+"?"+mq.Encode(), cookies, authH, map[string]interface{}{"parts": parts}, &merged); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if merged.OK != 1 {
|
||||
return nil, fmt.Errorf("分片合并返回异常")
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"title": strings.TrimSuffix(name, filepath.Ext(name)),
|
||||
"filename": strings.TrimSuffix(filepath.Base(pre.UposURI), filepath.Ext(filepath.Base(pre.UposURI))),
|
||||
"desc": "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// submit 投稿(x/vu/web/add)
|
||||
func (e *Executor) submit(ctx context.Context, cookies string, task exec.Task, part map[string]interface{}) (string, error) {
|
||||
csrf := cookieValue(cookies, "bili_jct")
|
||||
// 风控预热(失败不影响)
|
||||
_, _ = e.get(ctx, e.MemberBase+"/x/geetest/pre/add", cookies)
|
||||
tag := strings.Join(task.Tags, ",")
|
||||
if tag == "" {
|
||||
tag = "日常"
|
||||
}
|
||||
body := map[string]interface{}{
|
||||
"title": truncateRunes(task.Title, 80),
|
||||
"desc": task.Content,
|
||||
"desc_v2": []map[string]interface{}{{"raw_text": task.Content, "type": 1, "biz_id": ""}},
|
||||
"copyright": 1,
|
||||
"source": "",
|
||||
"tid": 174,
|
||||
"tag": tag,
|
||||
"dynamic": "",
|
||||
"videos": []map[string]interface{}{part},
|
||||
}
|
||||
var ret struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data struct {
|
||||
Bvid string `json:"bvid"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := e.postJSON(ctx, e.MemberBase+"/x/vu/web/add?csrf="+csrf, cookies, nil, body, &ret); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ret.Code != 0 {
|
||||
return "", fmt.Errorf("code=%d %s", ret.Code, ret.Message)
|
||||
}
|
||||
return ret.Data.Bvid, nil
|
||||
}
|
||||
|
||||
// SolveChallenge B站扫码登录:生成二维码 → onQR 展示 → 轮询 → 保存 cookie
|
||||
func (e *Executor) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
key, qrURL, err := e.generateQR(ctx)
|
||||
if err != nil {
|
||||
return false, ""
|
||||
}
|
||||
if onQR != nil {
|
||||
onQR(key, qrURL)
|
||||
}
|
||||
deadline := time.Now().Add(e.PollTimeout)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false, ""
|
||||
default:
|
||||
}
|
||||
code, cookieURL, perr := e.pollQR(ctx, key)
|
||||
if perr != nil {
|
||||
return false, ""
|
||||
}
|
||||
switch code {
|
||||
case 0:
|
||||
cookies := cookiesFromCrossDomainURL(cookieURL)
|
||||
if cookies == "" {
|
||||
return false, ""
|
||||
}
|
||||
_ = e.Vault.Save(ch.AccountID, []byte(`{"cookies":"`+jsonEscape(cookies)+`"}`))
|
||||
return true, "confirmed"
|
||||
case 86090:
|
||||
case 86101:
|
||||
default:
|
||||
return false, ""
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// generateQR 生成登录二维码
|
||||
func (e *Executor) generateQR(ctx context.Context) (key, qrURL string, err error) {
|
||||
var ret struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
URL string `json:"url"`
|
||||
QrcodeKey string `json:"qrcode_key"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err = e.getJSON(ctx, e.PassportBase+"/x/passport-login/web/qrcode/generate", "", &ret); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if ret.Code != 0 || ret.Data.QrcodeKey == "" {
|
||||
return "", "", fmt.Errorf("生成二维码失败 code=%d", ret.Code)
|
||||
}
|
||||
return ret.Data.QrcodeKey, ret.Data.URL, nil
|
||||
}
|
||||
|
||||
// pollQR 轮询扫码状态:86101 未扫 / 86090 已扫待确认 / 0 成功(返回跨域 cookie URL)
|
||||
func (e *Executor) pollQR(ctx context.Context, key string) (int, string, error) {
|
||||
var ret struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := e.getJSON(ctx, e.PassportBase+"/x/passport-login/web/qrcode/poll?qrcode_key="+key, "", &ret); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
return ret.Code, ret.Data.URL, nil
|
||||
}
|
||||
|
||||
// ---- HTTP 辅助 ----
|
||||
|
||||
func (e *Executor) get(ctx context.Context, rawURL, cookies string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cookies != "" {
|
||||
req.Header.Set("Cookie", cookies)
|
||||
}
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36")
|
||||
req.Header.Set("Referer", "https://member.bilibili.com")
|
||||
resp, err := e.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func (e *Executor) getJSON(ctx context.Context, rawURL, cookies string, out interface{}) error {
|
||||
raw, err := e.get(ctx, rawURL, cookies)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, out)
|
||||
}
|
||||
|
||||
func (e *Executor) postJSON(ctx context.Context, rawURL, cookies string, extraH map[string]string, body interface{}, out interface{}) error {
|
||||
var buf bytes.Buffer
|
||||
if body != nil {
|
||||
raw, _ := json.Marshal(body)
|
||||
buf.Write(raw)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, &buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cookies != "" {
|
||||
req.Header.Set("Cookie", cookies)
|
||||
}
|
||||
for k, v := range extraH {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120 Safari/537.36")
|
||||
req.Header.Set("Referer", "https://member.bilibili.com")
|
||||
resp, err := e.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("http %d", resp.StatusCode)
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(raw, out)
|
||||
}
|
||||
|
||||
func (e *Executor) putBody(ctx context.Context, rawURL, cookies string, extraH map[string]string, data []byte) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, rawURL, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cookies != "" {
|
||||
req.Header.Set("Cookie", cookies)
|
||||
}
|
||||
for k, v := range extraH {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := e.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("http %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// downloadFile 下载素材到临时文件
|
||||
func downloadFile(ctx context.Context, client *http.Client, rawURL string) (string, func(), error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", nil, fmt.Errorf("下载 http %d", resp.StatusCode)
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "ep-material-*")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
_, err = io.Copy(tmp, resp.Body)
|
||||
tmp.Close()
|
||||
if err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp.Name(), func() { _ = os.Remove(tmp.Name()) }, nil
|
||||
}
|
||||
|
||||
// cookieValue 从 cookie 串取值
|
||||
func cookieValue(cookies, key string) string {
|
||||
for _, part := range strings.Split(cookies, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if i := strings.Index(part, "="); i > 0 && part[:i] == key {
|
||||
return part[i+1:]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// cookiesFromCrossDomainURL 从跨域跳转 URL 提取登录 cookie
|
||||
func cookiesFromCrossDomainURL(rawURL string) string {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
q := u.Query()
|
||||
sess := q.Get("SESSDATA")
|
||||
jct := q.Get("bili_jct")
|
||||
dede := q.Get("DedeUserID")
|
||||
if sess == "" {
|
||||
return ""
|
||||
}
|
||||
return "SESSDATA=" + sess + "; bili_jct=" + jct + "; DedeUserID=" + dede
|
||||
}
|
||||
|
||||
func truncateRunes(s string, max int) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= max {
|
||||
return s
|
||||
}
|
||||
return string(r[:max])
|
||||
}
|
||||
|
||||
func jsonEscape(s string) string {
|
||||
raw, _ := json.Marshal(s)
|
||||
return string(raw[1 : len(raw)-1])
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package bilibili
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// stubBili 桩:preupload + upos(uploads/分片/合并)+ 投稿 add,记录关键请求
|
||||
func stubBili(t *testing.T) (*httptest.Server, *struct {
|
||||
PartQuery string
|
||||
PartsLen int
|
||||
AddBody map[string]interface{}
|
||||
AddURL string
|
||||
XUposAuth string
|
||||
}) {
|
||||
rec := &struct {
|
||||
PartQuery string
|
||||
PartsLen int
|
||||
AddBody map[string]interface{}
|
||||
AddURL string
|
||||
XUposAuth string
|
||||
}{}
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.URL.Path == "/preupload":
|
||||
// endpoint 指向桩服务器自身
|
||||
endpoint := "//" + strings.TrimPrefix(srv.URL, "http://")
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"OK": 1, "endpoint": endpoint, "auth": "auth-x", "biz_id": 1000,
|
||||
"upos_uri": "upos://video/av123", "chunk_size": 5,
|
||||
})
|
||||
case strings.Contains(r.URL.RawQuery, "uploads"):
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"upload_id": "upload-1"})
|
||||
case r.Method == http.MethodPut:
|
||||
rec.PartQuery = r.URL.RawQuery
|
||||
rec.XUposAuth = r.Header.Get("X-Upos-Auth")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == http.MethodPost && strings.Contains(r.URL.RawQuery, "output=json"):
|
||||
var body map[string]interface{}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if parts, ok := body["parts"].([]interface{}); ok {
|
||||
rec.PartsLen = len(parts)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]int{"OK": 1})
|
||||
case r.URL.Path == "/x/vu/web/add":
|
||||
rec.AddURL = r.URL.RawQuery
|
||||
_ = json.NewDecoder(r.Body).Decode(&rec.AddBody)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": 0, "data": map[string]string{"bvid": "BV1TEST123"},
|
||||
})
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
return srv, rec
|
||||
}
|
||||
|
||||
func TestExecuteUploadFlow(t *testing.T) {
|
||||
// 素材服务器
|
||||
matSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("0123456789abcdef"))
|
||||
}))
|
||||
defer matSrv.Close()
|
||||
|
||||
srv, rec := stubBili(t)
|
||||
defer srv.Close()
|
||||
|
||||
v, _ := vault.Open(t.TempDir())
|
||||
_ = v.Save("77", []byte(`{"cookies":"SESSDATA=sess; bili_jct=csrf-x; DedeUserID=1"}`))
|
||||
|
||||
e := New(v)
|
||||
e.MemberBase = srv.URL
|
||||
e.PassportBase = srv.URL
|
||||
e.UpOSScheme = "http"
|
||||
|
||||
res := e.Execute(context.Background(), exec.Task{
|
||||
TaskID: "9", AccountID: "77", Title: "测试标题", Content: "简介",
|
||||
Tags: []string{"测试", "日常"}, MaterialURLs: []string{matSrv.URL + "/v.mp4"},
|
||||
})
|
||||
if res.Status != "success" {
|
||||
t.Fatalf("expect success, got %+v", res)
|
||||
}
|
||||
if res.PublishedURL != "https://www.bilibili.com/video/BV1TEST123" {
|
||||
t.Fatalf("published url wrong: %s", res.PublishedURL)
|
||||
}
|
||||
// rec.PartQuery 记录最后一片(partNumber=4 size=1 start=15 end=16)
|
||||
if !strings.Contains(rec.PartQuery, "partNumber=4") || !strings.Contains(rec.PartQuery, "chunks=4") ||
|
||||
!strings.Contains(rec.PartQuery, "total=16") || !strings.Contains(rec.PartQuery, "size=1") {
|
||||
t.Fatalf("chunk query wrong: %s", rec.PartQuery)
|
||||
}
|
||||
if rec.PartsLen != 4 {
|
||||
t.Fatalf("expect 4 merged parts, got %d", rec.PartsLen)
|
||||
}
|
||||
if rec.AddURL != "csrf=csrf-x" {
|
||||
t.Fatalf("add csrf wrong: %s", rec.AddURL)
|
||||
}
|
||||
if rec.AddBody["title"] != "测试标题" || rec.AddBody["copyright"] != float64(1) {
|
||||
t.Fatalf("add body wrong: %+v", rec.AddBody)
|
||||
}
|
||||
if videos, ok := rec.AddBody["videos"].([]interface{}); !ok || len(videos) != 1 {
|
||||
t.Fatal("videos missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSolveChallengeQRLogin(t *testing.T) {
|
||||
pollAttempts := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case strings.Contains(r.URL.Path, "generate"):
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": 0, "data": map[string]string{"url": "https://qr.example/x", "qrcode_key": "key-1"},
|
||||
})
|
||||
case strings.Contains(r.URL.Path, "poll"):
|
||||
pollAttempts++
|
||||
if pollAttempts == 1 {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": 86101, "data": map[string]string{}})
|
||||
} else {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]string{
|
||||
"url": "https://passport.biligame.com/x/passport-login/web/crossDomain?SESSDATA=sess123&bili_jct=jct456&DedeUserID=789",
|
||||
},
|
||||
})
|
||||
}
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
v, _ := vault.Open(t.TempDir())
|
||||
e := New(v)
|
||||
e.MemberBase = srv.URL
|
||||
e.PassportBase = srv.URL
|
||||
e.PollTimeout = 10 * time.Second
|
||||
|
||||
var gotQR string
|
||||
solved, value := e.SolveChallenge(context.Background(), proto.Challenge{ChallengeID: "1", AccountID: "77"}, func(token, qrURL string) {
|
||||
gotQR = qrURL
|
||||
})
|
||||
if !solved || value != "confirmed" {
|
||||
t.Fatalf("expect solved, got %v %s", solved, value)
|
||||
}
|
||||
if gotQR == "" {
|
||||
t.Fatal("onQR should be called")
|
||||
}
|
||||
raw, err := v.Load("77")
|
||||
if err != nil {
|
||||
t.Fatalf("vault should have cookies: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(raw), "SESSDATA=sess123") {
|
||||
t.Fatalf("cookies not saved: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollTimeoutUnscanned(t *testing.T) {
|
||||
// 一直未扫码:应超时返回未解决
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.Contains(r.URL.Path, "generate") {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": 0, "data": map[string]string{"url": "u", "qrcode_key": "k"}})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"code": 86101, "data": map[string]string{}})
|
||||
}))
|
||||
defer srv.Close()
|
||||
v, _ := vault.Open(t.TempDir())
|
||||
e := New(v)
|
||||
e.MemberBase = srv.URL
|
||||
e.PassportBase = srv.URL
|
||||
e.PollTimeout = 3 * time.Second
|
||||
if solved, _ := e.SolveChallenge(context.Background(), proto.Challenge{AccountID: "1"}, nil); solved {
|
||||
t.Fatal("unscanned should timeout unsolved")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// cdnbase 三平台执行器公共底座:保险库 + 浏览器档案目录 + 代理 + 执行入口。
|
||||
package cdnbase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/exec/cdp"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Platform 三平台执行器公共底座
|
||||
type Platform struct {
|
||||
Vault *vault.Vault
|
||||
RootDir string // 浏览器档案根目录(每账号子目录)
|
||||
Proxy string // 账号固定 IP 代理
|
||||
ChromePath string
|
||||
Headless bool
|
||||
ReceiptDir string // 截图回执目录
|
||||
Name string // 平台名(日志)
|
||||
PublishCfg cdp.PublishConfig
|
||||
LoginCfg cdp.QRLoginConfig
|
||||
LoginDomain string // 登录 cookie 域名
|
||||
}
|
||||
|
||||
// credentials 保险库凭据
|
||||
type credentials struct {
|
||||
Cookies string `json:"cookies"`
|
||||
}
|
||||
|
||||
// loadCookies 读账号 cookie(无则空,触发扫码)
|
||||
func (p *Platform) loadCookies(accountID string) string {
|
||||
raw, err := p.Vault.Load(accountID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var c credentials
|
||||
if json.Unmarshal(raw, &c) != nil {
|
||||
return ""
|
||||
}
|
||||
return c.Cookies
|
||||
}
|
||||
|
||||
// profileDir 账号独立档案目录
|
||||
func (p *Platform) profileDir(accountID string) string {
|
||||
return filepath.Join(p.RootDir, p.Name, accountID)
|
||||
}
|
||||
|
||||
// Publish 通用发布入口(下载素材 → 启动浏览器 → 发布 → 回传)
|
||||
func (p *Platform) Publish(ctx context.Context, task exec.Task) exec.Result {
|
||||
fail := func(err string) exec.Result {
|
||||
return exec.Result{TaskID: task.TaskID, Status: "failed", Error: err}
|
||||
}
|
||||
cookies := p.loadCookies(task.AccountID)
|
||||
if len(task.MaterialURLs) == 0 {
|
||||
return fail("任务缺少素材")
|
||||
}
|
||||
videoPath, cleanup, err := cdp.DownloadFile(ctx, task.MaterialURLs[0])
|
||||
if err != nil {
|
||||
return fail("素材下载失败: " + err.Error())
|
||||
}
|
||||
defer cleanup()
|
||||
|
||||
br, err := cdp.Launch(ctx, cdp.Options{
|
||||
UserDataDir: p.profileDir(task.AccountID),
|
||||
Proxy: p.Proxy,
|
||||
Headless: p.Headless,
|
||||
ChromePath: p.ChromePath,
|
||||
})
|
||||
if err != nil {
|
||||
return fail("浏览器启动失败: " + err.Error())
|
||||
}
|
||||
defer br.Close()
|
||||
|
||||
cfg := p.PublishCfg
|
||||
cfg.Platform = p.Name
|
||||
cfg.ReceiptDir = p.ReceiptDir
|
||||
res, err := br.Publish(ctx, cfg, videoPath, task.Title, task.Content, task.Tags, cookies, p.LoginDomain)
|
||||
if err != nil {
|
||||
return fail("发布失败: " + err.Error())
|
||||
}
|
||||
return exec.Result{
|
||||
TaskID: task.TaskID,
|
||||
Status: "success",
|
||||
PublishedURL: res.URL,
|
||||
Receipts: res.Receipts,
|
||||
}
|
||||
}
|
||||
|
||||
// SolveChallenge CDP 扫码登录:二维码截图经 onQR 展示 → 轮询登录 → 保存 cookie
|
||||
func (p *Platform) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
br, err := cdp.Launch(ctx, cdp.Options{
|
||||
UserDataDir: p.profileDir(ch.AccountID),
|
||||
Proxy: p.Proxy,
|
||||
Headless: p.Headless,
|
||||
ChromePath: p.ChromePath,
|
||||
})
|
||||
if err != nil {
|
||||
cdp.Log("%s: 扫码浏览器启动失败: %v", p.Name, err)
|
||||
return false, ""
|
||||
}
|
||||
defer br.Close()
|
||||
cookies, err := br.QRLogin(ctx, p.LoginCfg, onQR)
|
||||
if err != nil {
|
||||
cdp.Log("%s: 扫码登录失败: %v", p.Name, err)
|
||||
return false, ""
|
||||
}
|
||||
if cookies == "" {
|
||||
return false, ""
|
||||
}
|
||||
_ = p.Vault.Save(ch.AccountID, []byte(`{"cookies":"`+cdp.EscapeJSON(cookies)+`"}`))
|
||||
return true, "confirmed"
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// cdp 共享浏览器基础设施:独立档案启动(每账号一档案)、代理、指纹、扫码登录。
|
||||
// 一期驱动 rod-launcher 管理的 Chromium;ChromePath 给定则驱动系统 Chrome/Edge。
|
||||
package cdp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-rod/rod"
|
||||
"github.com/go-rod/rod/lib/launcher"
|
||||
"github.com/go-rod/rod/lib/proto"
|
||||
rodstealth "github.com/go-rod/stealth"
|
||||
)
|
||||
|
||||
// Options 浏览器启动选项
|
||||
type Options struct {
|
||||
UserDataDir string // 每账号独立档案目录
|
||||
Proxy string // 账号固定 IP 代理(http://ip:port)
|
||||
Headless bool
|
||||
ChromePath string // 系统 Chrome/Edge 可执行文件(空=自动探测/下载)
|
||||
}
|
||||
|
||||
// Browser 浏览器封装
|
||||
type Browser struct {
|
||||
rod *rod.Browser
|
||||
Page *rod.Page
|
||||
}
|
||||
|
||||
// defaultChromePath 常见系统浏览器路径(Windows 优先,macOS 兜底)
|
||||
func defaultChromePath() string {
|
||||
candidates := []string{
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
candidates = append(candidates, "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
|
||||
}
|
||||
for _, p := range candidates {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Launch 启动浏览器(独立档案 + 指纹 + 反自动化)
|
||||
func Launch(ctx context.Context, opts Options) (*Browser, error) {
|
||||
l := launcher.New()
|
||||
if opts.UserDataDir != "" {
|
||||
if err := os.MkdirAll(opts.UserDataDir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l = l.UserDataDir(opts.UserDataDir)
|
||||
}
|
||||
if opts.Proxy != "" {
|
||||
l = l.Set("proxy-server", opts.Proxy)
|
||||
}
|
||||
bin := opts.ChromePath
|
||||
if bin == "" {
|
||||
bin = defaultChromePath()
|
||||
}
|
||||
if bin != "" {
|
||||
l = l.Bin(bin)
|
||||
}
|
||||
l = l.Headless(opts.Headless).
|
||||
Set("no-first-run").
|
||||
Set("no-default-browser-check").
|
||||
Set("disable-blink-features", "AutomationControlled").
|
||||
Set("window-size", "1440,900")
|
||||
url, err := l.Launch()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
browser := rod.New().ControlURL(url)
|
||||
if err = browser.Connect(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 指纹/反自动化(stealth 注入)
|
||||
page, err := rodstealth.Page(browser)
|
||||
if err != nil {
|
||||
browser.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Browser{rod: browser, Page: page}, nil
|
||||
}
|
||||
|
||||
// Close 关闭浏览器
|
||||
func (b *Browser) Close() {
|
||||
_ = b.rod.Close()
|
||||
}
|
||||
|
||||
// Screenshot 截图回执(PNG 本地保存,返回路径;二期上传服务器)
|
||||
func (b *Browser) Screenshot(receiptDir, name string) string {
|
||||
if err := os.MkdirAll(receiptDir, 0o755); err != nil {
|
||||
return ""
|
||||
}
|
||||
path := filepath.Join(receiptDir, name)
|
||||
_ = b.Page.MustWaitLoad().MustScreenshot(path)
|
||||
return path
|
||||
}
|
||||
|
||||
// InjectCookies 注入登录 cookie(免重复扫码)
|
||||
func (b *Browser) InjectCookies(cookieStr, domain string) error {
|
||||
for _, part := range strings.Split(cookieStr, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
i := strings.Index(part, "=")
|
||||
if i <= 0 {
|
||||
continue
|
||||
}
|
||||
name, value := part[:i], part[i+1:]
|
||||
cookie := &proto.NetworkCookieParam{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Domain: domain,
|
||||
Path: "/",
|
||||
}
|
||||
_ = b.rod.SetCookies([]*proto.NetworkCookieParam{cookie})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cookies 导出当前浏览器 cookie(域名过滤)
|
||||
func (b *Browser) Cookies(domain string) string {
|
||||
cookies, err := b.rod.GetCookies()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
parts := make([]string, 0, len(cookies))
|
||||
for _, c := range cookies {
|
||||
if domain != "" && !strings.Contains(c.Domain, domain) {
|
||||
continue
|
||||
}
|
||||
parts = append(parts, c.Name+"="+c.Value)
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// QRLoginConfig 扫码登录配置
|
||||
type QRLoginConfig struct {
|
||||
LoginURL string
|
||||
LoginPathMarker string // 登录页 URL 特征(登录成功=URL 离开该特征)
|
||||
QRSelector string // 二维码元素选择器
|
||||
SuccessWait time.Duration
|
||||
}
|
||||
|
||||
// QRLogin 通用扫码登录:打开登录页 → 截图二维码经 onQR 展示 → 轮询 URL 直到登录成功
|
||||
func (b *Browser) QRLogin(ctx context.Context, cfg QRLoginConfig, onQR func(qrToken, qrURL string)) (string, error) {
|
||||
if err := b.Page.Navigate(cfg.LoginURL); err != nil {
|
||||
return "", err
|
||||
}
|
||||
_ = b.Page.WaitLoad()
|
||||
// 截图二维码 → 临时 PNG → file:// URI → onQR(壳端 BitmapImage 展示)
|
||||
qrEl, err := b.Page.Element(cfg.QRSelector)
|
||||
if err == nil {
|
||||
raw, serr := qrEl.Screenshot(proto.PageCaptureScreenshotFormatPng, 100)
|
||||
if serr == nil && len(raw) > 0 {
|
||||
qrPath := filepath.Join(os.TempDir(), "ep-qr-"+time.Now().Format("150405")+".png")
|
||||
if werr := os.WriteFile(qrPath, raw, 0o600); werr == nil && onQR != nil {
|
||||
onQR("", "file://"+qrPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 轮询登录状态
|
||||
deadline := time.Now().Add(cfg.SuccessWait)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", fmt.Errorf("cancelled")
|
||||
default:
|
||||
}
|
||||
info, ierr := b.Page.Info()
|
||||
if ierr == nil && !strings.Contains(info.URL, cfg.LoginPathMarker) {
|
||||
return b.Cookies(""), nil
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
return "", fmt.Errorf("扫码登录超时")
|
||||
}
|
||||
|
||||
// DownloadFile 下载素材到临时文件(返回路径与清理函数)
|
||||
func DownloadFile(ctx context.Context, rawURL string) (string, func(), error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
client := &http.Client{Timeout: 10 * time.Minute}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", nil, fmt.Errorf("下载 http %d", resp.StatusCode)
|
||||
}
|
||||
tmp, err := os.CreateTemp("", "ep-material-*")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
_, err = io.Copy(tmp, resp.Body)
|
||||
tmp.Close()
|
||||
if err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp.Name(), func() { _ = os.Remove(tmp.Name()) }, nil
|
||||
}
|
||||
|
||||
// EscapeJSON 转义字符串供嵌入 JSON
|
||||
func EscapeJSON(s string) string {
|
||||
raw, _ := json.Marshal(s)
|
||||
return string(raw[1 : len(raw)-1])
|
||||
}
|
||||
|
||||
// Log 调试输出
|
||||
func Log(format string, args ...interface{}) {
|
||||
log.Printf("[cdp] "+format, args...)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package cdp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEscapeJSON(t *testing.T) {
|
||||
s := EscapeJSON("SESSDATA=ab\"c; bili_jct=d")
|
||||
// 转义后应可嵌入 JSON 且还原一致
|
||||
var decoded string
|
||||
if err := json.Unmarshal([]byte(`"`+s+`"`), &decoded); err != nil {
|
||||
t.Fatalf("escaped string not valid json: %v", err)
|
||||
}
|
||||
if decoded != "SESSDATA=ab\"c; bili_jct=d" {
|
||||
t.Fatalf("roundtrip mismatch: %q", decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFile(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("video-bytes-123"))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
path, cleanup, err := DownloadFile(context.Background(), srv.URL+"/v.mp4")
|
||||
if err != nil {
|
||||
t.Fatalf("download: %v", err)
|
||||
}
|
||||
defer cleanup()
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil || string(raw) != "video-bytes-123" {
|
||||
t.Fatalf("content mismatch: %s %v", raw, err)
|
||||
}
|
||||
cleanup()
|
||||
if _, err = os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("cleanup should remove temp file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFileHTTPError(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusGone)
|
||||
_, _ = io.WriteString(w, "gone")
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, _, err := DownloadFile(context.Background(), srv.URL); err == nil {
|
||||
t.Fatal("410 should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultChromePath(t *testing.T) {
|
||||
// 至少不 panic、返回字符串
|
||||
p := defaultChromePath()
|
||||
if strings.TrimSpace(p) == "" && p != "" {
|
||||
t.Fatal("unexpected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
// Publish 通用发布流程:进上传页 → 注入 cookie → 传视频 → 填表单 → 点发布 → 等成功跳转 → 截图回执。
|
||||
// 各平台选择器差异经 PublishConfig 配置;平台改版时只需调整配置。
|
||||
package cdp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-rod/rod"
|
||||
"github.com/go-rod/rod/lib/proto"
|
||||
)
|
||||
|
||||
// PublishConfig 发布流程配置(选择器按平台填写)
|
||||
type PublishConfig struct {
|
||||
Platform string
|
||||
UploadURL string
|
||||
SuccessMarker string // 发布成功后的 URL 特征
|
||||
FileInputSel string
|
||||
TitleSel string
|
||||
DescSel string
|
||||
PublishBtnSel string
|
||||
FormWait time.Duration // 等视频处理出表单的最长时间
|
||||
SuccessWait time.Duration
|
||||
ReceiptDir string
|
||||
}
|
||||
|
||||
// PublishResult 发布结果
|
||||
type PublishResult struct {
|
||||
URL string
|
||||
Receipts []string
|
||||
}
|
||||
|
||||
// Publish 执行通用发布流程
|
||||
func (b *Browser) Publish(ctx context.Context, cfg PublishConfig, videoPath, title, content string, tags []string, cookieStr, cookieDomain string) (*PublishResult, error) {
|
||||
if err := b.Page.Navigate(cfg.UploadURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = b.Page.WaitLoad()
|
||||
// 注入登录 cookie(有则免扫码)
|
||||
if cookieStr != "" {
|
||||
_ = b.InjectCookies(cookieStr, cookieDomain)
|
||||
if err := b.Page.Navigate(cfg.UploadURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = b.Page.WaitLoad()
|
||||
}
|
||||
|
||||
// 1) 传视频
|
||||
fileInput, err := b.Page.Element(cfg.FileInputSel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("找不到上传入口(%s): %w", cfg.FileInputSel, err)
|
||||
}
|
||||
if err = fileInput.SetFiles([]string{videoPath}); err != nil {
|
||||
return nil, fmt.Errorf("选择文件失败: %w", err)
|
||||
}
|
||||
Log("%s: 视频已选择,等待平台处理...", cfg.Platform)
|
||||
|
||||
// 2) 等表单渲染(视频转码后出现标题输入框)
|
||||
titleEl, err := b.Page.ElementR(cfg.TitleSel, "")
|
||||
if err != nil {
|
||||
titleEl, err = b.waitElement(ctx, cfg.TitleSel, cfg.FormWait)
|
||||
}
|
||||
if err != nil {
|
||||
b.Screenshot(cfg.ReceiptDir, cfg.Platform+"-form-fail.png")
|
||||
return nil, fmt.Errorf("等表单渲染超时(%s): %w", cfg.TitleSel, err)
|
||||
}
|
||||
|
||||
// 3) 填标题/描述(话题并入描述)
|
||||
if err = titleEl.Input(title); err != nil {
|
||||
return nil, fmt.Errorf("填标题失败: %w", err)
|
||||
}
|
||||
desc := content
|
||||
if len(tags) > 0 {
|
||||
for _, t := range tags {
|
||||
t = strings.TrimSpace(t)
|
||||
if t != "" && !strings.HasPrefix(t, "#") {
|
||||
t = "#" + t
|
||||
}
|
||||
desc += " " + t
|
||||
}
|
||||
}
|
||||
if descEl, derr := b.Page.Element(cfg.DescSel); derr == nil {
|
||||
_ = descEl.Input(desc)
|
||||
}
|
||||
|
||||
// 4) 点发布
|
||||
btn, err := b.waitElement(ctx, cfg.PublishBtnSel, 15*time.Second)
|
||||
if err != nil {
|
||||
b.Screenshot(cfg.ReceiptDir, cfg.Platform+"-btn-fail.png")
|
||||
return nil, fmt.Errorf("找不到发布按钮(%s): %w", cfg.PublishBtnSel, err)
|
||||
}
|
||||
if err = btn.Click(proto.InputMouseButtonLeft, 1); err != nil {
|
||||
return nil, fmt.Errorf("点发布失败: %w", err)
|
||||
}
|
||||
Log("%s: 已点发布,等待结果...", cfg.Platform)
|
||||
|
||||
// 5) 等成功跳转
|
||||
if err = b.waitURL(ctx, cfg.SuccessMarker, cfg.SuccessWait); err != nil {
|
||||
b.Screenshot(cfg.ReceiptDir, cfg.Platform+"-publish-fail.png")
|
||||
return nil, err
|
||||
}
|
||||
info, _ := b.Page.Info()
|
||||
receipt := b.Screenshot(cfg.ReceiptDir, cfg.Platform+"-success.png")
|
||||
Log("%s: 发布成功 %s", cfg.Platform, info.URL)
|
||||
return &PublishResult{URL: info.URL, Receipts: []string{receipt}}, nil
|
||||
}
|
||||
|
||||
// waitElement 轮询等待元素出现
|
||||
func (b *Browser) waitElement(ctx context.Context, selector string, timeout time.Duration) (*rod.Element, error) {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("cancelled")
|
||||
default:
|
||||
}
|
||||
el, err := b.Page.Element(selector)
|
||||
if err == nil {
|
||||
return el, nil
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
return nil, fmt.Errorf("timeout waiting %s", selector)
|
||||
}
|
||||
|
||||
// waitURL 轮询等待 URL 命中特征
|
||||
func (b *Browser) waitURL(ctx context.Context, marker string, timeout time.Duration) error {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("cancelled")
|
||||
default:
|
||||
}
|
||||
info, err := b.Page.Info()
|
||||
if err == nil && strings.Contains(info.URL, marker) {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
return fmt.Errorf("timeout waiting url %s", marker)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// douyin 抖音执行器(CDP:creator.douyin.com)。选择器参考 dreammis/social-auto-upload(2026-06 版)。
|
||||
package douyin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/exec/cdnbase"
|
||||
"everypublish/agentcore/internal/exec/cdp"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Executor 抖音发布执行器
|
||||
type Executor struct {
|
||||
base *cdnbase.Platform
|
||||
}
|
||||
|
||||
// New 构造执行器(rootDir=浏览器档案根目录,proxy=账号固定IP代理)
|
||||
func New(v *vault.Vault, rootDir, proxy, chromePath string, headless bool) *Executor {
|
||||
p := &cdnbase.Platform{
|
||||
Vault: v,
|
||||
RootDir: rootDir,
|
||||
Proxy: proxy,
|
||||
ChromePath: chromePath,
|
||||
Headless: headless,
|
||||
ReceiptDir: rootDir + "/receipts",
|
||||
Name: "douyin",
|
||||
LoginDomain: ".douyin.com",
|
||||
PublishCfg: cdp.PublishConfig{
|
||||
UploadURL: "https://creator.douyin.com/creator-micro/content/upload",
|
||||
SuccessMarker: "creator-micro/content/manage",
|
||||
FileInputSel: "input[type=\"file\"]",
|
||||
TitleSel: "input[placeholder*=\"填写作品标题\"]",
|
||||
DescSel: "div.zone-container[contenteditable=\"true\"]",
|
||||
PublishBtnSel: "button:has-text(\"发布\")",
|
||||
FormWait: 180 * time.Second, // 视频转码渲染表单较慢
|
||||
SuccessWait: 120 * time.Second,
|
||||
},
|
||||
LoginCfg: cdp.QRLoginConfig{
|
||||
LoginURL: "https://creator.douyin.com/",
|
||||
LoginPathMarker: "creator.douyin.com/?",
|
||||
QRSelector: ".qrcode-v2 img, .qrcode img, img[src*=qrcode]",
|
||||
SuccessWait: 3 * time.Minute,
|
||||
},
|
||||
}
|
||||
return &Executor{base: p}
|
||||
}
|
||||
|
||||
// Platform 平台标识
|
||||
func (e *Executor) Platform() string { return "douyin" }
|
||||
|
||||
// Execute 发布
|
||||
func (e *Executor) Execute(ctx context.Context, task exec.Task) exec.Result {
|
||||
return e.base.Publish(ctx, task)
|
||||
}
|
||||
|
||||
// SolveChallenge 扫码登录(QR 截图经 onQR 展示)
|
||||
func (e *Executor) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
return e.base.SolveChallenge(ctx, ch, onQR)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package exec_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/exec/fake"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
func TestFakeExecutor(t *testing.T) {
|
||||
e := fake.Executor{SimMS: 5}
|
||||
start := time.Now()
|
||||
res := e.Execute(context.Background(), exec.Task{TaskID: "1", Platform: "douyin", Title: "t"})
|
||||
if time.Since(start) < 5*time.Millisecond {
|
||||
t.Fatal("should simulate delay")
|
||||
}
|
||||
if res.Status != "success" || res.PublishedURL == "" {
|
||||
t.Fatalf("expect success, got %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFakeSolver(t *testing.T) {
|
||||
e := fake.Executor{SimMS: 1}
|
||||
solved, value := e.SolveChallenge(context.Background(), proto.Challenge{ChallengeID: "1"}, nil)
|
||||
if !solved || value == "" {
|
||||
t.Fatalf("expect solved, got %v %s", solved, value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryFallback(t *testing.T) {
|
||||
r := exec.NewRegistry()
|
||||
r.SetFallback(fake.Executor{SimMS: 1})
|
||||
if r.Get("douyin") == nil {
|
||||
t.Fatal("fallback should serve any platform")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package exec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Task 执行任务(由 task.push 转换而来)
|
||||
type Task struct {
|
||||
TaskID string
|
||||
Platform string
|
||||
AccountID string
|
||||
AccountName string
|
||||
Title string
|
||||
Content string
|
||||
Tags []string
|
||||
MaterialURLs []string
|
||||
ScheduleAt int64
|
||||
Priority int
|
||||
}
|
||||
|
||||
// Result 执行结果(回传 task.result)
|
||||
type Result struct {
|
||||
TaskID string
|
||||
Status string
|
||||
PublishedURL string
|
||||
Receipts []string
|
||||
Error string
|
||||
}
|
||||
|
||||
// Executor 平台执行器(每个平台一个实现;D10 起接入真实平台)
|
||||
type Executor interface {
|
||||
Platform() string
|
||||
Execute(ctx context.Context, task Task) Result
|
||||
}
|
||||
|
||||
// ChallengeSolver 能自动完成挑战的平台执行器(扫码/验证码)。
|
||||
// onQR:平台生成二维码时回调(把 qrToken/qrUrl 推给壳展示,可为 nil)。
|
||||
type ChallengeSolver interface {
|
||||
SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (solved bool, value string)
|
||||
}
|
||||
|
||||
// Registry 执行器注册表(并发安全)
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
m map[string]Executor
|
||||
fallback Executor
|
||||
}
|
||||
|
||||
// NewRegistry 创建注册表
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{m: make(map[string]Executor)}
|
||||
}
|
||||
|
||||
// Register 注册平台执行器
|
||||
func (r *Registry) Register(e Executor) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.m[e.Platform()] = e
|
||||
}
|
||||
|
||||
// SetFallback 注册兜底执行器(未接入平台用)
|
||||
func (r *Registry) SetFallback(e Executor) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.fallback = e
|
||||
}
|
||||
|
||||
// Get 取执行器(无匹配返回 nil)
|
||||
func (r *Registry) Get(platform string) Executor {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if e, ok := r.m[platform]; ok {
|
||||
return e
|
||||
}
|
||||
return r.fallback
|
||||
}
|
||||
|
||||
// Solve 取挑战解决器(nil 表示不支持自动解决)
|
||||
func (r *Registry) Solve(platform string) ChallengeSolver {
|
||||
if s, ok := r.Get(platform).(ChallengeSolver); ok {
|
||||
return s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// fake 假执行器:D8 闭环验收用,模拟平台执行(延迟后返回成功)。
|
||||
package fake
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Executor 假执行器(可作兜底:任何平台都返回成功)
|
||||
type Executor struct {
|
||||
SimMS int
|
||||
}
|
||||
|
||||
// Platform 空串表示通用(注册为兜底)
|
||||
func (e Executor) Platform() string { return "" }
|
||||
|
||||
// Execute 模拟执行:延迟 SimMS 后返回成功
|
||||
func (e Executor) Execute(ctx context.Context, task exec.Task) exec.Result {
|
||||
select {
|
||||
case <-time.After(time.Duration(e.SimMS) * time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
return exec.Result{TaskID: task.TaskID, Status: "failed", Error: "cancelled"}
|
||||
}
|
||||
return exec.Result{
|
||||
TaskID: task.TaskID,
|
||||
Status: "success",
|
||||
PublishedURL: "https://example.com/fake/" + task.TaskID,
|
||||
Receipts: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
// SolveChallenge 模拟扫码:延迟后返回已解决
|
||||
func (e Executor) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
if onQR != nil {
|
||||
onQR("fake-qr-token", "https://example.com/fake-qr")
|
||||
}
|
||||
select {
|
||||
case <-time.After(time.Duration(e.SimMS) * time.Millisecond):
|
||||
case <-ctx.Done():
|
||||
return false, ""
|
||||
}
|
||||
return true, "fake-qr-token"
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// kuaishou 快手执行器(CDP:cp.kuaishou.com)。
|
||||
package kuaishou
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/exec/cdnbase"
|
||||
"everypublish/agentcore/internal/exec/cdp"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Executor 快手发布执行器
|
||||
type Executor struct {
|
||||
base *cdnbase.Platform
|
||||
}
|
||||
|
||||
// New 构造执行器
|
||||
func New(v *vault.Vault, rootDir, proxy, chromePath string, headless bool) *Executor {
|
||||
p := &cdnbase.Platform{
|
||||
Vault: v,
|
||||
RootDir: rootDir,
|
||||
Proxy: proxy,
|
||||
ChromePath: chromePath,
|
||||
Headless: headless,
|
||||
ReceiptDir: rootDir + "/receipts",
|
||||
Name: "kuaishou",
|
||||
LoginDomain: ".kuaishou.com",
|
||||
PublishCfg: cdp.PublishConfig{
|
||||
UploadURL: "https://cp.kuaishou.com/article/publish/video",
|
||||
SuccessMarker: "article/manage/video",
|
||||
FileInputSel: "input[type=\"file\"]",
|
||||
TitleSel: "input[placeholder*=\"标题\"]",
|
||||
DescSel: "[contenteditable=\"true\"]",
|
||||
PublishBtnSel: "button:has-text(\"发布\")",
|
||||
FormWait: 180 * time.Second,
|
||||
SuccessWait: 120 * time.Second,
|
||||
},
|
||||
LoginCfg: cdp.QRLoginConfig{
|
||||
LoginURL: "https://cp.kuaishou.com/",
|
||||
LoginPathMarker: "passport.kuaishou.com",
|
||||
QRSelector: ".qrcode-img, img[src*=qrcode], .qrcode img",
|
||||
SuccessWait: 3 * time.Minute,
|
||||
},
|
||||
}
|
||||
return &Executor{base: p}
|
||||
}
|
||||
|
||||
// Platform 平台标识
|
||||
func (e *Executor) Platform() string { return "kuaishou" }
|
||||
|
||||
// Execute 发布
|
||||
func (e *Executor) Execute(ctx context.Context, task exec.Task) exec.Result {
|
||||
return e.base.Publish(ctx, task)
|
||||
}
|
||||
|
||||
// SolveChallenge 扫码登录
|
||||
func (e *Executor) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
return e.base.SolveChallenge(ctx, ch, onQR)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// xiaohongshu 小红书执行器(CDP:creator.xiaohongshu.com)。
|
||||
package xiaohongshu
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"everypublish/agentcore/internal/exec"
|
||||
"everypublish/agentcore/internal/exec/cdnbase"
|
||||
"everypublish/agentcore/internal/exec/cdp"
|
||||
"everypublish/agentcore/internal/vault"
|
||||
"everypublish/shared/proto"
|
||||
)
|
||||
|
||||
// Executor 小红书发布执行器
|
||||
type Executor struct {
|
||||
base *cdnbase.Platform
|
||||
}
|
||||
|
||||
// New 构造执行器
|
||||
func New(v *vault.Vault, rootDir, proxy, chromePath string, headless bool) *Executor {
|
||||
p := &cdnbase.Platform{
|
||||
Vault: v,
|
||||
RootDir: rootDir,
|
||||
Proxy: proxy,
|
||||
ChromePath: chromePath,
|
||||
Headless: headless,
|
||||
ReceiptDir: rootDir + "/receipts",
|
||||
Name: "xiaohongshu",
|
||||
LoginDomain: ".xiaohongshu.com",
|
||||
PublishCfg: cdp.PublishConfig{
|
||||
UploadURL: "https://creator.xiaohongshu.com/publish/publish",
|
||||
SuccessMarker: "publish/success",
|
||||
FileInputSel: "input[type=\"file\"]",
|
||||
TitleSel: "input[placeholder*=\"填写标题\"]",
|
||||
DescSel: "#post-textarea",
|
||||
PublishBtnSel: "button:has-text(\"发布\")",
|
||||
FormWait: 180 * time.Second,
|
||||
SuccessWait: 120 * time.Second,
|
||||
},
|
||||
LoginCfg: cdp.QRLoginConfig{
|
||||
LoginURL: "https://creator.xiaohongshu.com/login",
|
||||
LoginPathMarker: "creator.xiaohongshu.com/login",
|
||||
QRSelector: ".qrcode-img, img[src*=qrcode], .qrcode img",
|
||||
SuccessWait: 3 * time.Minute,
|
||||
},
|
||||
}
|
||||
return &Executor{base: p}
|
||||
}
|
||||
|
||||
// Platform 平台标识
|
||||
func (e *Executor) Platform() string { return "xiaohongshu" }
|
||||
|
||||
// Execute 发布
|
||||
func (e *Executor) Execute(ctx context.Context, task exec.Task) exec.Result {
|
||||
return e.base.Publish(ctx, task)
|
||||
}
|
||||
|
||||
// SolveChallenge 扫码登录
|
||||
func (e *Executor) SolveChallenge(ctx context.Context, ch proto.Challenge, onQR func(qrToken, qrURL string)) (bool, string) {
|
||||
return e.base.SolveChallenge(ctx, ch, onQR)
|
||||
}
|
||||
Reference in New Issue
Block a user