refactor: 重构多插件 UI 与配置结构,新增抖音/新美大平台核对插件
- 新增 XQ0042 抖音平台核对、XQ0041 新美大平台核对插件的 UI 源码与打包脚本 - 重构续签电子签、服务岗转正不通过电子签等插件的版本与配置 - 删除旧版考勤异常处理、微盟数据导出等冗余插件文件 - 修复出勤积分更新插件的 OPM 推送判断逻辑 - 优化壳子插件页面的 iframe 滚动条样式
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0042 抖音平台核对 - 数据层。"""
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 后续取数都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0042,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
import os
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/滑块),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,403 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出模块:核销明细 + 提现记录(余额提现记录)。
|
||||
|
||||
实测(2026-10-28):
|
||||
|
||||
核销明细(履约管理订单列表 → 导出工具)
|
||||
创建:POST /life/trade_view/v1/management/verify/query/download_verify_record_list
|
||||
body.condition.query_conditions = [商品类型 product_option, 核销时间 verify_time(秒级)]
|
||||
→ data.downloadStruct{download_id, file_name, status=1}
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=10031001
|
||||
|
||||
提现记录(财务 → 导出记录 /p/fulfillsettle/export_records/16)
|
||||
创建:GET /life/settle/v1/withdraw/capital/download_records_list/?start_date=&end_date=
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=16
|
||||
→ download_infos[] 里 status=2 表示生成完成,file_url 为预签名地址
|
||||
|
||||
公共约束
|
||||
平台同类导出记录最多 30 条,满了创建会返回 224000002;
|
||||
因此导出前先查列表,超限就删最早的(POST /life/settle/v1/download/delete/)。
|
||||
下载:file_url 直接 requests 取(带签名,不需要 Cookie)。
|
||||
|
||||
签名参数(a_bogus / msToken)由页面 SDK 注入,所以请求都在页面上下文里发。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR,返回 (status, text)。"""
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def _api_json(page, method, url, payload=None):
|
||||
status, text = _xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _account_id(page):
|
||||
"""root_life_account_id:页面 localStorage 里是 {用户id: 主账号id} 的 JSON 映射,
|
||||
取映射值;读不到/解析失败用配置兜底。"""
|
||||
try:
|
||||
val = page.run_js("return localStorage.getItem('root_life_account_id') || '';")
|
||||
text = str(val or '').strip()
|
||||
if text:
|
||||
try:
|
||||
obj = json.loads(text)
|
||||
if isinstance(obj, dict) and obj:
|
||||
return str(list(obj.values())[0])
|
||||
if isinstance(obj, str) and obj:
|
||||
return obj.strip()
|
||||
except Exception:
|
||||
return text.strip('"')
|
||||
except Exception:
|
||||
pass
|
||||
return config.ROOT_LIFE_ACCOUNT_ID
|
||||
|
||||
|
||||
def _group_id(page):
|
||||
"""groupid 从当前 URL 里取(?groupid=...),取不到用配置兜底。"""
|
||||
url = page.url or ''
|
||||
if 'groupid=' in url:
|
||||
val = url.split('groupid=', 1)[1].split('&', 1)[0]
|
||||
if val.isdigit():
|
||||
return val
|
||||
return config.ORDER_GROUP_ID
|
||||
|
||||
|
||||
def _ensure_page(page, url, hint, label):
|
||||
"""切到导出所在页面(同域上下文,SDK 才会给请求签名)。"""
|
||||
target = url.replace(config.ORDER_GROUP_ID, _group_id(page))
|
||||
if hint not in (page.url or ''):
|
||||
config.log(f'打开{label}页面')
|
||||
page.get(target)
|
||||
try:
|
||||
page.wait.doc_loaded(timeout=20)
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
# SPA 首屏文档加载完之后前端才注入签名 SDK,留一点时间再发业务请求
|
||||
time.sleep(2)
|
||||
return target
|
||||
|
||||
|
||||
def _ensure_order_page(page):
|
||||
return _ensure_page(page, config.ORDER_URL,
|
||||
'fulfillment-admin/order-list', '履约管理订单列表')
|
||||
|
||||
|
||||
def _ensure_withdraw_page(page):
|
||||
return _ensure_page(page, config.WITHDRAW_URL,
|
||||
'fulfillsettle/export_records', '提现记录')
|
||||
|
||||
|
||||
def _list_records(page, download_type):
|
||||
"""查某类导出记录列表(新的在前)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.DOWNLOAD_LIST_API}?download_type={download_type}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
data = _api_json(page, 'GET', url)
|
||||
return ((data or {}).get('download_infos') or [])
|
||||
|
||||
|
||||
def _delete_record(page, download_id):
|
||||
"""删除单条导出记录。"""
|
||||
aid = _account_id(page)
|
||||
url = config.DELETE_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
data = _api_json(page, 'POST', url, {'download_id': str(download_id)})
|
||||
base = ((data or {}).get('BaseResp') or {})
|
||||
return data is not None and base.get('StatusCode', -1) == 0
|
||||
|
||||
|
||||
def _delete_oldest(page, download_type, count, infos=None):
|
||||
"""删掉最早的 count 条导出记录(按 generate_start_time 升序)。返回删除条数。
|
||||
|
||||
限流:两条之间随机间隔 DELETE_MIN_INTERVAL ~ DELETE_MAX_INTERVAL 秒,
|
||||
单次运行最多删 DELETE_MAX_PER_RUN 条,避免短时间连续删除触发风控。
|
||||
"""
|
||||
if count <= 0:
|
||||
return 0
|
||||
limit = config.DELETE_MAX_PER_RUN
|
||||
if count > limit:
|
||||
config.log(f'本次只删最早的 {limit} 条(单次上限),其余留到下次运行', 'WARN')
|
||||
count = limit
|
||||
if infos is None:
|
||||
infos = _list_records(page, download_type)
|
||||
if not infos:
|
||||
return 0
|
||||
oldest_first = sorted(infos, key=lambda x: int(x.get('generate_start_time') or 0))[:int(count)]
|
||||
removed = 0
|
||||
for idx, rec in enumerate(oldest_first):
|
||||
did = rec.get('download_id')
|
||||
if not did:
|
||||
continue
|
||||
if idx or removed:
|
||||
pause = random.uniform(config.DELETE_MIN_INTERVAL, config.DELETE_MAX_INTERVAL)
|
||||
config.log(f'限流等待 {pause:.1f}s 再删下一条', 'DEBUG')
|
||||
time.sleep(pause)
|
||||
name = rec.get('file_name') or ''
|
||||
if _delete_record(page, did):
|
||||
removed += 1
|
||||
config.log(f'删除最早导出记录:{name}({did})')
|
||||
else:
|
||||
config.log(f'删除导出记录失败:{name}({did})', 'WARN')
|
||||
return removed
|
||||
|
||||
|
||||
def _ensure_capacity(page, download_type, limit):
|
||||
"""记录数超过保留阈值时,删最早的、只保留最新 limit 条。返回删除条数。"""
|
||||
infos = _list_records(page, download_type)
|
||||
total = len(infos)
|
||||
if total <= limit:
|
||||
config.log(f'导出记录 {total} 条(保留阈值 {limit}),无需清理', 'DEBUG')
|
||||
return 0
|
||||
config.log(f'导出记录 {total} 条,超过保留阈值 {limit},删除最早的 {total - limit} 条')
|
||||
return _delete_oldest(page, download_type, total - limit, infos)
|
||||
|
||||
|
||||
def _create_export(page, start_ts, end_ts):
|
||||
"""发起核销明细导出,返回 downloadStruct(含 download_id / file_name)。"""
|
||||
aid = _account_id(page)
|
||||
url = config.VERIFY_EXPORT_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
payload = {
|
||||
'condition': {
|
||||
'query_type': 101,
|
||||
'query_conditions': [
|
||||
{'column_name': 'product_option',
|
||||
'params': list(config.VERIFY_PRODUCT_OPTIONS), 'query_type': 9},
|
||||
{'column_name': 'verify_time',
|
||||
'params': [str(int(start_ts)), str(int(end_ts))], 'query_type': 12},
|
||||
],
|
||||
},
|
||||
'is_app': False,
|
||||
'show_reason': config.VERIFY_SHOW_REASON,
|
||||
'view_type': config.VERIFY_VIEW_TYPE,
|
||||
'download_field_option': 1,
|
||||
'permission_common_param': {},
|
||||
}
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'POST', url, payload)
|
||||
if data is None:
|
||||
config.log(f'发起导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
base = (data.get('BaseResp') or {})
|
||||
struct = ((data.get('data') or {}).get('downloadStruct') or {})
|
||||
code = base.get('StatusCode')
|
||||
if code == 0 and struct.get('download_id'):
|
||||
return struct
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好(如鉴权失败),直接返回,避免重复创建导出任务
|
||||
config.log(f'发起导出失败:{base.get("StatusMessage") or data}', 'WARN')
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _create_withdraw(page, start_ts, end_ts):
|
||||
"""发起提现记录导出,返回 (ok, 说明)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.WITHDRAW_EXPORT_API}?life_account_id_list='
|
||||
f'&start_date={int(start_ts)}&end_date={int(end_ts)}&status_array='
|
||||
f'&fund_account_type_list={config.WITHDRAW_FUND_ACCOUNT_TYPE}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
msg = ''
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'GET', url)
|
||||
if data is None:
|
||||
config.log(f'发起提现记录导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
code = data.get('status_code')
|
||||
base = (data.get('BaseResp') or {})
|
||||
if code == 0:
|
||||
return True, 'ok'
|
||||
msg = data.get('status_msg') or base.get('StatusMessage') or str(data)
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.WITHDRAW_DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好,直接返回,避免重复创建导出任务
|
||||
return False, msg
|
||||
return False, msg or '网络异常,未拿到导出响应'
|
||||
|
||||
|
||||
def _wait_record(page, download_type, match):
|
||||
"""轮询导出记录,等 status=2(生成完成)后返回记录;match(rec) 用来认本次任务。"""
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
last_status = None
|
||||
while time.time() < deadline:
|
||||
infos = _list_records(page, download_type)
|
||||
hit = next((x for x in infos if match(x)), None)
|
||||
if hit:
|
||||
status = hit.get('status')
|
||||
if status != last_status:
|
||||
last_status = status
|
||||
config.log(f'导出任务状态={status}({hit.get("file_name")})')
|
||||
if status == 2 and hit.get('file_url'):
|
||||
return hit
|
||||
if status not in (1, 2):
|
||||
config.log(f'导出任务异常:{hit}', 'WARN')
|
||||
return None
|
||||
else:
|
||||
config.log('导出记录里还没出现本次任务,继续等…', 'DEBUG')
|
||||
time.sleep(config.RECORD_POLL)
|
||||
config.log(f'等待导出生成超时({config.RECORD_SECONDS}s)', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _download(file_url, save_path):
|
||||
"""预签名地址直下,返回字节数(失败 0)。"""
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(file_url, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
try:
|
||||
os.remove(save_path)
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def _day_bounds(date_from, date_to):
|
||||
"""自然日区间 → 秒级时间戳(00:00:00 ~ 23:59:59)。"""
|
||||
start_ts = int(time.mktime(time.strptime(date_from + ' 00:00:00', '%Y-%m-%d %H:%M:%S')))
|
||||
end_ts = int(time.mktime(time.strptime(date_to + ' 23:59:59', '%Y-%m-%d %H:%M:%S')))
|
||||
return start_ts, end_ts
|
||||
|
||||
|
||||
def _save_record(record, save_dir, default_name, label):
|
||||
"""把生成好的记录下载落盘,返回统一结果 dict。"""
|
||||
download_id = str(record.get('download_id') or '')
|
||||
file_name = record.get('file_name') or default_name
|
||||
safe_name = str(file_name).replace('/', '_').replace('\\', '_')
|
||||
save_path = os.path.join(save_dir, safe_name)
|
||||
size = _download(record.get('file_url'), save_path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': f'{label}文件下载失败', 'path': '',
|
||||
'download_id': download_id, 'file_name': safe_name}
|
||||
config.log(f'已下载:{save_path}({size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'message': f'{label}已导出:{safe_name}', 'path': save_path,
|
||||
'download_id': download_id, 'file_name': safe_name, 'size': size}
|
||||
|
||||
|
||||
def run(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定「核销时间」区间的核销明细并下载。
|
||||
|
||||
date_from/date_to:YYYY-MM-DD;核销时间按自然日取整(00:00:00 ~ 23:59:59)。
|
||||
record_limit:导出记录保留条数(超出则先删最早的),默认 config.RECORD_LIMIT_VERIFY。
|
||||
返回 {ok, message, path, download_id, file_name}
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_VERIFY)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_order_page(page)
|
||||
config.log(f'发起核销明细导出:核销时间 {date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.DOWNLOAD_TYPE, limit)
|
||||
struct = _create_export(page, start_ts, end_ts)
|
||||
if not struct:
|
||||
return {'ok': False, 'message': '发起导出失败(接口未返回 download_id)', 'path': ''}
|
||||
download_id = str(struct.get('download_id'))
|
||||
file_name = struct.get('file_name') or f'核销明细_{date_from}_{date_to}.xlsx'
|
||||
config.log(f'导出任务已创建:download_id={download_id},文件名={file_name}')
|
||||
|
||||
record = _wait_record(page, config.DOWNLOAD_TYPE,
|
||||
lambda x: str(x.get('download_id')) == download_id)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '导出任务未生成完成', 'path': '',
|
||||
'download_id': download_id, 'file_name': file_name}
|
||||
return _save_record(record, save_dir, file_name, '核销明细')
|
||||
|
||||
|
||||
def run_withdraw(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定区间的「提现记录」(资金账户交易提现记录)并下载。
|
||||
|
||||
该接口不回 download_id,创建后按 generate_start_time 找最新那条记录。
|
||||
record_limit:导出记录保留条数,默认 config.RECORD_LIMIT_WITHDRAW。
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_WITHDRAW)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_withdraw_page(page)
|
||||
config.log(f'发起提现记录导出:{date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.WITHDRAW_DOWNLOAD_TYPE, limit)
|
||||
before = int(time.time()) - 5
|
||||
ok, msg = _create_withdraw(page, start_ts, end_ts)
|
||||
if not ok:
|
||||
return {'ok': False, 'message': f'发起提现记录导出失败:{msg}', 'path': ''}
|
||||
|
||||
record = _wait_record(page, config.WITHDRAW_DOWNLOAD_TYPE,
|
||||
lambda x: int(x.get('generate_start_time') or 0) >= before)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '提现记录导出任务未生成完成', 'path': ''}
|
||||
config.log(f'导出任务已创建:download_id={record.get("download_id")},'
|
||||
f'文件名={record.get("file_name")}')
|
||||
return _save_record(record, save_dir,
|
||||
f'资金账户交易提现记录_{date_from}_{date_to}.xlsx', '提现记录')
|
||||
@@ -0,0 +1,246 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抖音来客登录态:打开登录页 → 人工登录(含验证码/滑块/扫码)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
实测链路(2026-10-28):
|
||||
https://life.douyin.com/p/login 登录页(账密 / 短信验证码 / 扫码)
|
||||
sso.douyin.com / passport.douyin.com
|
||||
登录成功后跳 https://life.douyin.com/p/home?groupid=...,期间可能短暂回跳登录页
|
||||
|
||||
判定规则(三条同时满足):
|
||||
1) 当前 URL 是 life.douyin.com 的非登录页;
|
||||
2) douyin 域下存在会话票据 Cookie(sessionid* / sid_tt* / sid_guard*);
|
||||
3) 连续稳定 BACKEND_STABLE 秒,期间没有被踢回登录页。
|
||||
|
||||
落盘(%LOCALAPPDATA%\\37duAutomation\\.sessions\\douyin_*):
|
||||
douyin_cookies.json / douyin_cookies_header.txt / douyin_tokens.json / douyin_session_meta.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截快照(半截快照必然登录失效)。"""
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _host(url):
|
||||
try:
|
||||
return (url or '').split('://', 1)[-1].split('/', 1)[0].split('?', 1)[0].lower()
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login(登录页/统一登录域)/ backend(来客后台)/ other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
host = _host(low)
|
||||
if host.endswith(config.BACKEND_HOST):
|
||||
path = low.split(host, 1)[-1]
|
||||
if any(p in path for p in config.LOGIN_PAGE_HINTS):
|
||||
return 'login'
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _has_session_cookie(cookies):
|
||||
"""douyin 域下是否存在登录票据 Cookie(名字带 _ls 等分区后缀,按前缀匹配)。"""
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip().lower()
|
||||
if name.startswith(config.SESSION_COOKIE_PREFIXES) and c.get('value') \
|
||||
and 'douyin.com' in (c.get('domain') or ''):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _ticket_cookies(cookies):
|
||||
out = []
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip()
|
||||
low = name.lower()
|
||||
if not name or not c.get('value'):
|
||||
continue
|
||||
if any(k in low for k in config.IGNORE_KEY_HINTS):
|
||||
continue
|
||||
if any(k in low for k in config.TICKET_KEY_HINTS):
|
||||
out.append(name)
|
||||
return sorted(set(out))
|
||||
|
||||
|
||||
def _cookie_header(cookies):
|
||||
"""按浏览器原始顺序拼出 douyin 域 Cookie 头(passport/埋点域名不要)。"""
|
||||
skip = ('passport', 'sso', 'report', 'monitor', 'lx', 'dreport', 'open.douyin')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and 'douyin.com' in (c.get('domain') or '')
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
config.log(f'已保存 douyin 域 Cookie 头({header.count(";") + 1} 项)')
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'has_session_cookie': _has_session_cookie(cookies),
|
||||
'ticket_cookies': _ticket_cookies(cookies),
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
return summary
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 验证码」,返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录'
|
||||
'(账号密码 / 短信验证码 / 扫码 / 滑块均可,脚本不碰表单)')
|
||||
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进来客后台且票据已种下,等待 {config.BACKEND_STABLE}s '
|
||||
f'确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('离开后台或票据消失,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page, force=False):
|
||||
"""确保 page 已进入来客后台;必要时停在前台等人工登录。
|
||||
|
||||
force=True 跳过 profile 残留会话试探,直接等人工登录(换账号/排查问题用)。
|
||||
"""
|
||||
config.log(f'打开抖音来客:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用 profile 残留会话:能直接进后台就不用打扰用户
|
||||
if not force:
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
config.log(f'profile 残留会话有效,直接复用(URL={page.url})')
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state == 'login':
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
config.log('profile 无有效会话,转人工登录', 'WARN')
|
||||
|
||||
config.log(f'需要人工登录(含验证码/滑块),最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' +
|
||||
', '.join(sorted({c.get('name') for c in cookies if c.get('name')})), 'WARN')
|
||||
return False, '登录超时(未进入来客后台或会话票据缺失)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
Reference in New Issue
Block a user