Merge branch 'dev' —— 账号池对外只读 API
This commit is contained in:
@@ -389,6 +389,21 @@ App 从每段的动作组/任务带出来(列表里显示"动作组 · App"或
|
||||
`_finish_run(log_accounts=[...])` 负责这件事。**绝不能用 `号A、号B` 当文件夹名**:
|
||||
那样会在账号根目录下建出一个假账号(2026-10-18 实测踩过)。
|
||||
|
||||
### 4.12 🔑 账号池对外 API(其他应用只读)
|
||||
|
||||
其他应用要"看到账号池里有哪些号、在哪台手机"时,用独立令牌访问,**不需要登录会话**:
|
||||
|
||||
```
|
||||
GET /api/account_pool/accounts
|
||||
X-Account-Token: <token>
|
||||
```
|
||||
|
||||
- 页面入口:**① 资产管理 → 🔑 账号池 API**(查看/复制/重置令牌,仅管理员)。
|
||||
- 令牌存 `app_meta.account_pool_token`(随备份走),与设备端 Agent 令牌**分开**。
|
||||
- 过滤:`?device=A11` / `?q=锋哥` / `?status=正常` / `?online=1`。
|
||||
- 返回:昵称、抖音号、所属设备、地址、在线、账号状态、可发视频、备注。
|
||||
- 完整字段与示例见 [API.md](API.md) §18「账号池对外只读 API」。
|
||||
|
||||
## 5. 跑一轮做了什么(代码级)
|
||||
|
||||
```
|
||||
|
||||
+34
@@ -1096,6 +1096,7 @@ multipart 上传 `.zip` 或 `.db`(字段 `file`)→ 校验并暂存:
|
||||
| GET | `/api/af/roster` | **账号库**(名字 ↔ 哪台手机,每行带 `serial/pooled/online`) |
|
||||
| POST | `/api/af/roster/import` · `/resolve` | 粘贴导入(**按抖音号认同一行**,永不删)/ 只算名字→设备 |
|
||||
| DELETE | `/api/af/roster/<row_id>` | 删一行账号库(只有这里会删) |
|
||||
| GET | `/api/account_pool/accounts` | **账号池对外只读 API**(独立令牌,给其他应用;见下) |
|
||||
| GET/POST | `/api/af/apps`(`PUT/DELETE /api/af/apps/<id>`) | App 注册表(包名 + 首页定位) |
|
||||
| POST | `/api/af/run` | 多选账号跑一轮(后台线程,立刻返回 `runs`) |
|
||||
| POST | `/api/af/try` | 在指定设备上**单独试跑一个动作**(测「切账号」用,不套循环、不推素材) |
|
||||
@@ -1107,6 +1108,39 @@ multipart 上传 `.zip` 或 `.db`(字段 `file`)→ 校验并暂存:
|
||||
| POST | `/api/af/plan/<id>/run` | 跑一次:`{}` 整批 / `{"accounts":["号甲"]}` 试跑那个号 / `{"dry_run":true}` 只预检 |
|
||||
| GET | `/api/af/plan_runs` · `/api/af/plan_run/<id>` | 计划运行记录 / 某次的每号结局与原因+`ae_run_id` |
|
||||
|
||||
### 账号池对外只读 API(给其他应用)
|
||||
|
||||
其他应用**不需要登录会话**,用独立令牌访问(与设备端令牌分开,避免拿到 Agent 的写权限)。
|
||||
令牌在页面「① 资产管理 → 🔑 账号池 API」查看/复制/重置,存在 `app_meta.account_pool_token`(随备份走)。
|
||||
|
||||
| 方法 | 路径 | 鉴权 | 功能 |
|
||||
|------|------|------|------|
|
||||
| GET | `/api/account_pool/accounts` | `X-Account-Token: <token>` 或 `Authorization: Bearer <token>` | 账号池只读列表 |
|
||||
| GET | `/api/account_pool/token` | 管理员登录 | 查看令牌 + API 地址 |
|
||||
| POST | `/api/account_pool/token/reset` | 管理员登录 | 重置令牌(旧令牌立即失效) |
|
||||
|
||||
可选过滤:`?device=A11`、`?q=锋哥`(昵称/抖音号子串)、`?status=正常`、`?online=1`。
|
||||
|
||||
```bash
|
||||
curl -H "X-Account-Token: <token>" \
|
||||
"http://192.168.20.220:18050/api/account_pool/accounts?device=A11"
|
||||
```
|
||||
|
||||
```json
|
||||
{"ok": true, "total": 1, "total_all": 39,
|
||||
"server_time": "2026-10-20 12:00:00",
|
||||
"accounts": [
|
||||
{"id": "ceb95ecf", "nickname": "锋哥苏州百业探访", "douyin_id": "96020279089",
|
||||
"device_name": "A11", "serial": "192.168.20.87:5555", "phone": "...",
|
||||
"online": true, "pooled": true, "account_status": "正常",
|
||||
"can_post_video": false, "note": "", "updated_at": "..."}
|
||||
]}
|
||||
```
|
||||
|
||||
- 鉴权失败:`401 {"ok":false,"error":"unauthorized"}`
|
||||
- 响应带 `Access-Control-Allow-Origin: *`,浏览器应用也可直接读(仍需令牌)
|
||||
- `online` 是设备池当前在线状态;`account_status` 是资产页「账号状态」列
|
||||
|
||||
### 计划调度(`/api/af/plan*`)
|
||||
|
||||
一条计划 = "接下来这段时间,让电脑完成我这一批次的任务"(干什么/给谁干/发什么/什么时候/怎么跑
|
||||
|
||||
@@ -824,3 +824,17 @@ data/accounts/周周苏州探店日记、周周苏州约会好去处/_日志/202
|
||||
- 覆盖场景:平台切号(立即广播)、手机手动切号(≤5 秒巡检)、账号不在账号库
|
||||
(只能显示 MIUI 打码名,属于信息上限)。
|
||||
- 单测:`test_roster.py` ⑦(唯一匹配 / 对不上返回空 / 多匹配 tiebreak / 无历史不猜)。
|
||||
|
||||
## 27. 2026-10-20 新增:账号池对外只读 API
|
||||
|
||||
用户:"给我账号池的 API,我其他应用需要能看到账号池里的账号。"
|
||||
|
||||
- `GET /api/account_pool/accounts`:账号库只读列表,**独立令牌**(`X-Account-Token`
|
||||
或 `Authorization: Bearer`),不复用设备端 Agent 令牌。
|
||||
- 令牌存 `app_meta.account_pool_token`(随备份走);页面「① 资产管理 → 🔑 账号池 API」
|
||||
可查看、复制、重置(仅管理员)。
|
||||
- 过滤:`?device=A11`、`?q=锋哥`、`?status=正常`、`?online=1`;返回昵称/抖音号/
|
||||
所属设备/地址/在线/账号状态/可发视频/备注。
|
||||
- 响应带 CORS(`Access-Control-Allow-Origin: *`),网页应用也能直接读。
|
||||
- 管理端:`GET /api/account_pool/token`、`POST /api/account_pool/token/reset`。
|
||||
- 文档:API.md §18、ACCOUNT_FOLDER.md §4.12。
|
||||
|
||||
@@ -339,6 +339,7 @@ function afHtmlAsset() {
|
||||
'<div class="toolbar" style="flex-wrap:wrap;align-items:center">' +
|
||||
'<button class="btn btn-primary" onclick="afOpenAssetImport()" data-perm="devices">⬆ 批量上传素材(配模板)</button>' +
|
||||
'<button class="btn" onclick="afOpenRoster()" data-perm="devices">导入/维护账号库</button>' +
|
||||
'<button class="btn" onclick="afShowPoolApi()" data-perm="devices">🔑 账号池 API</button>' +
|
||||
'<button class="btn" onclick="afRefreshAll(true)">刷新</button>' +
|
||||
'<span class="text-muted" style="font-size:12px">账号表里点「入库 N」进素材库;' +
|
||||
'「所属手机」改了就**重新登记**(下次按新设备激活)。素材放进去 = 归这个账号。</span>' +
|
||||
@@ -1157,6 +1158,62 @@ function afHtmlRoster() {
|
||||
'</div></div>';
|
||||
}
|
||||
|
||||
// 账号池对外只读 API:给其他应用看"池子里有哪些号、在哪台手机"
|
||||
async function afShowPoolApi() {
|
||||
const r = await apiGet('/api/account_pool/token');
|
||||
if (!r || !r.ok) { showToast((r && r.error) || '需要管理员权限', 'error'); return; }
|
||||
const old = document.getElementById('af-pool-api');
|
||||
if (old) old.remove();
|
||||
const url = r.url || (location.origin + '/api/account_pool/accounts');
|
||||
const token = r.token || '';
|
||||
const curl = 'curl -H "X-Account-Token: ' + token + '" "' + url + '"';
|
||||
const d = document.createElement('div');
|
||||
d.id = 'af-pool-api';
|
||||
d.className = 'modal-overlay show';
|
||||
d.innerHTML = '<div class="modal" style="max-width:720px">' +
|
||||
'<div class="modal-header"><h3>🔑 账号池 API(只读)</h3>' +
|
||||
'<button class="close" onclick="document.getElementById(\'af-pool-api\').remove()">×</button></div>' +
|
||||
'<div class="modal-body">' +
|
||||
'<p class="text-muted" style="font-size:12px">其他应用直接 GET 这个地址,不需要登录;' +
|
||||
'请求头带 <code>X-Account-Token</code>(或 <code>Authorization: Bearer …</code>)。</p>' +
|
||||
'<div class="form-group"><label>地址</label>' +
|
||||
'<input class="form-control" readonly value="' + esc(url) + '"></div>' +
|
||||
'<div class="form-group"><label>令牌 ' + esc(r.token_created_at || '') + '</label>' +
|
||||
'<div style="display:flex;gap:6px">' +
|
||||
'<input class="form-control" readonly id="af-pool-token" value="' + esc(token) + '">' +
|
||||
'<button class="btn" onclick="afCopyPoolToken()">复制</button></div></div>' +
|
||||
'<div class="form-group"><label>示例</label>' +
|
||||
'<pre style="white-space:pre-wrap;font-size:12px;margin:0">' + esc(curl) + '</pre></div>' +
|
||||
'<p class="text-muted" style="font-size:12px">可选过滤:<code>?device=A11</code>、' +
|
||||
'<code>?q=锋哥</code>、<code>?status=正常</code>、<code>?online=1</code></p>' +
|
||||
'</div>' +
|
||||
'<div class="modal-footer">' +
|
||||
'<button class="btn btn-danger" onclick="afResetPoolToken()">重置令牌</button>' +
|
||||
'<button class="btn" onclick="document.getElementById(\'af-pool-api\').remove()">关闭</button>' +
|
||||
'</div></div>';
|
||||
document.body.appendChild(d);
|
||||
}
|
||||
|
||||
function afCopyPoolToken() {
|
||||
const el = document.getElementById('af-pool-token');
|
||||
if (!el) return;
|
||||
el.select();
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(el.value).then(function () { showToast('已复制', 'success'); });
|
||||
} else {
|
||||
document.execCommand('copy');
|
||||
showToast('已复制', 'success');
|
||||
}
|
||||
}
|
||||
|
||||
async function afResetPoolToken() {
|
||||
if (!confirm('重置后旧令牌立即失效,其他应用需要更新。继续?')) return;
|
||||
const r = await apiPost('/api/account_pool/token/reset', {});
|
||||
if (!r || !r.ok) { showToast((r && r.error) || '重置失败', 'error'); return; }
|
||||
showToast('令牌已重置', 'success');
|
||||
afShowPoolApi();
|
||||
}
|
||||
|
||||
function afOpenRoster() {
|
||||
const ov = document.getElementById('af-roster-overlay');
|
||||
if (ov) ov.remove();
|
||||
|
||||
+120
-1
@@ -17,21 +17,62 @@
|
||||
抓元素 / 测一下:**复用现有的**(前端 openPicker / `POST /api/steps/test`),这里不重复造
|
||||
"""
|
||||
import os
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from flask_login import current_user
|
||||
|
||||
from core import account_folder as af
|
||||
from core.db_config import meta_get, meta_set
|
||||
from core.logger import get_logger
|
||||
from web.auth import perm_required, PERM_DEVICES
|
||||
from web.auth import perm_required, admin_required, PERM_DEVICES
|
||||
|
||||
_log = get_logger("web")
|
||||
bp = Blueprint("account_folder", __name__)
|
||||
|
||||
PROFILE_ID = "default"
|
||||
|
||||
# ==================== 账号池对外 API(给其他应用只读访问)====================
|
||||
# 与「设备端令牌」分开:这里只读账号库,不暴露设备 Agent 的 bootstrap/上报能力。
|
||||
_K_POOL_TOKEN = "account_pool_token"
|
||||
_K_POOL_TOKEN_AT = "account_pool_token_at"
|
||||
|
||||
|
||||
def _pool_token():
|
||||
"""取(没有就生成)账号池 API 令牌,存 app_meta(随备份走)。"""
|
||||
tok = meta_get(_K_POOL_TOKEN) or ""
|
||||
if not tok:
|
||||
tok = secrets.token_urlsafe(24)
|
||||
meta_set(_K_POOL_TOKEN, tok)
|
||||
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
_log.info("账号池 API 令牌已生成")
|
||||
return tok
|
||||
|
||||
|
||||
def _pool_req_token():
|
||||
"""请求里的令牌:`X-Account-Token` 或 `Authorization: Bearer <token>`。"""
|
||||
tok = (request.headers.get("X-Account-Token") or "").strip()
|
||||
if tok:
|
||||
return tok
|
||||
auth = (request.headers.get("Authorization") or "").strip()
|
||||
if auth.lower().startswith("bearer "):
|
||||
return auth[7:].strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _pool_json(data, code=200):
|
||||
"""账号池 JSON 响应:带 CORS(其他应用/网页可直接读)。"""
|
||||
resp = jsonify(data)
|
||||
resp.status_code = code
|
||||
resp.headers["Access-Control-Allow-Origin"] = "*"
|
||||
resp.headers["Access-Control-Allow-Headers"] = "X-Account-Token, Authorization, Content-Type"
|
||||
resp.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
|
||||
return resp
|
||||
|
||||
|
||||
def _profile_row(create=True):
|
||||
"""取(或建)那唯一一条配置。"""
|
||||
@@ -364,6 +405,84 @@ def api_af_roster():
|
||||
return jsonify({"ok": True, "rows": rows, "groups": groups, "total": len(rows)})
|
||||
|
||||
|
||||
# ==================== 账号池对外只读 API ====================
|
||||
# 其他应用用 `X-Account-Token`(或 Bearer)访问,不需要登录会话。
|
||||
@bp.route("/api/account_pool/accounts", methods=["GET", "OPTIONS"])
|
||||
def api_account_pool_accounts():
|
||||
"""**账号池**(账号库)只读列表:给其他应用看"池子里有哪些号、在哪台手机"。
|
||||
|
||||
鉴权:`X-Account-Token: <token>` 或 `Authorization: Bearer <token>`
|
||||
(令牌在「资产管理 → 🔑 账号池 API」里查看/重置)。
|
||||
|
||||
可选过滤:`?device=A11`、`?q=锋哥`、`?status=正常`、`?online=1`。
|
||||
"""
|
||||
if request.method == "OPTIONS":
|
||||
return _pool_json({"ok": True})
|
||||
real = _pool_token()
|
||||
got = _pool_req_token()
|
||||
if not got or not hmac.compare_digest(got, real):
|
||||
_log.warning("账号池 API 鉴权失败(来源 %s)", request.remote_addr)
|
||||
return _pool_json({"ok": False, "error": "unauthorized"}, 401)
|
||||
|
||||
device = (request.args.get("device") or "").strip()
|
||||
q = (request.args.get("q") or "").strip().lower()
|
||||
status = (request.args.get("status") or "").strip()
|
||||
only_online = (request.args.get("online") or "").strip().lower() in ("1", "true", "yes")
|
||||
rows = af.roster_rows()
|
||||
out = []
|
||||
for r in rows:
|
||||
if device and (r.get("device_name") or "") != device:
|
||||
continue
|
||||
if status and (r.get("account_status") or "") != status:
|
||||
continue
|
||||
if only_online and not r.get("online"):
|
||||
continue
|
||||
if q and q not in (r.get("nickname") or "").lower() \
|
||||
and q not in (r.get("douyin_id") or "").lower():
|
||||
continue
|
||||
out.append({
|
||||
"id": r.get("id") or "",
|
||||
"nickname": r.get("nickname") or "",
|
||||
"douyin_id": r.get("douyin_id") or "",
|
||||
"device_name": r.get("device_name") or "",
|
||||
"serial": r.get("serial") or "",
|
||||
"phone": r.get("phone") or "",
|
||||
"online": bool(r.get("online")),
|
||||
"pooled": bool(r.get("pooled")),
|
||||
"account_status": r.get("account_status") or "",
|
||||
"can_post_video": bool(r.get("can_post_video")),
|
||||
"note": r.get("note") or "",
|
||||
"updated_at": r.get("updated_at") or "",
|
||||
})
|
||||
return _pool_json({"ok": True, "total": len(out), "total_all": len(rows),
|
||||
"server_time": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"accounts": out})
|
||||
|
||||
|
||||
@bp.route("/api/account_pool/token")
|
||||
@admin_required
|
||||
def api_account_pool_token():
|
||||
"""管理端:查看账号池 API 令牌(仅管理员;页面「资产 → 🔑 账号池 API」)。"""
|
||||
tok = _pool_token()
|
||||
return jsonify({"ok": True, "token": tok,
|
||||
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
|
||||
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts"})
|
||||
|
||||
|
||||
@bp.route("/api/account_pool/token/reset", methods=["POST"])
|
||||
@admin_required
|
||||
def api_account_pool_token_reset():
|
||||
"""管理端:重置账号池 API 令牌(旧令牌立即失效)。"""
|
||||
tok = secrets.token_urlsafe(24)
|
||||
meta_set(_K_POOL_TOKEN, tok)
|
||||
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
_log.info("账号池 API 令牌已重置 by %s", getattr(current_user, "username", ""))
|
||||
return jsonify({"ok": True, "token": tok,
|
||||
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
|
||||
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts",
|
||||
"msg": "令牌已重置(旧令牌立即失效)"})
|
||||
|
||||
|
||||
@bp.route("/api/af/roster/import", methods=["POST"])
|
||||
@perm_required(PERM_DEVICES)
|
||||
def api_af_roster_import():
|
||||
|
||||
Reference in New Issue
Block a user