204 lines
9.5 KiB
Python
204 lines
9.5 KiB
Python
"""赋能中心展厅使用登记:实时读取金山文档在线表格。"""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
import os
|
||
import shutil
|
||
import subprocess
|
||
import time
|
||
import urllib.request
|
||
from typing import Any
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
|
||
DEFAULT_LINK_ID = 'cnC7HwRAxKf9'
|
||
ENDPOINT = 'https://mcp-center.wps.cn/skill_hub/api/v1/tool'
|
||
CACHE_TTL_SECONDS = 60
|
||
MAX_ROWS = 500
|
||
FIELDS = ['序号', '日期', '时间', '使用场地', '参加人数', '使用事项', '使用单位', '使用单位联系人及联系方式', '赋能部值班人员及联系方式', '备注']
|
||
LOG_DIR = Path(__file__).resolve().parent.parent / 'logs'
|
||
_cache: dict[str, Any] = {'fetched_at': 0.0, 'payload': None, 'error': None}
|
||
_lock = asyncio.Lock()
|
||
|
||
|
||
def _cli_path() -> str | None:
|
||
return shutil.which('kdocs-cli') or (r'C:\Users\ASUS\AppData\Local\kdocs-cli\kdocs-cli.exe' if os.name == 'nt' else None)
|
||
|
||
|
||
def _call_tool(tool: str, args: dict, token: str | None) -> dict:
|
||
body = json.dumps({'tool': tool, 'args': args}, ensure_ascii=False).encode('utf-8')
|
||
headers = {'Content-Type': 'application/json'}
|
||
if token:
|
||
headers['Authorization'] = f'Bearer {token}'
|
||
request = urllib.request.Request(ENDPOINT, data=body, headers=headers, method='POST')
|
||
with urllib.request.urlopen(request, timeout=15) as response:
|
||
raw = response.read().decode('utf-8')
|
||
payload = _parse_sse(raw)
|
||
if isinstance(payload, dict) and payload.get('code') not in (None, 0):
|
||
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
||
return payload
|
||
|
||
|
||
def _parse_sse(raw: str) -> dict:
|
||
"""兼容两种返回:纯 JSON 或 SSE 流(event:... / data:{...} 行)。"""
|
||
text = raw.strip()
|
||
if not text:
|
||
raise RuntimeError('金山文档接口返回空内容')
|
||
if text.startswith('{'):
|
||
return json.loads(text)
|
||
if 'data:' not in text:
|
||
raise RuntimeError(f'金山文档接口返回无法识别: {text[:120]}')
|
||
merged: dict = {}
|
||
for line in text.splitlines():
|
||
line = line.strip()
|
||
if not line.startswith('data:'):
|
||
continue
|
||
chunk = line[5:].strip()
|
||
if not chunk or chunk == '[DONE]':
|
||
continue
|
||
try:
|
||
item = json.loads(chunk)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
if isinstance(item, dict):
|
||
merged.update(item)
|
||
if not merged:
|
||
raise RuntimeError(f'金山文档流式返回中没有有效数据: {text[:120]}')
|
||
return merged
|
||
|
||
|
||
def _parse_grid(cells: list[dict], row_to: int, col_to: int) -> list[list[str]]:
|
||
grid = [['' for _ in range(col_to + 1)] for _ in range(row_to + 1)]
|
||
for cell in cells:
|
||
row, col = cell.get('rowFrom', 0), cell.get('colFrom', 0)
|
||
if row <= row_to and col <= col_to:
|
||
grid[row][col] = str(cell.get('cellText', '') or '').strip()
|
||
return grid
|
||
|
||
|
||
def _unwrap(payload: dict, label: str) -> dict:
|
||
"""兼容新旧 CLI 返回格式:新版直接返回 detail,旧版包在 code/data 里。"""
|
||
if 'detail' in payload:
|
||
return payload['detail']
|
||
if payload.get('code') not in (None, 0):
|
||
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
||
detail = (payload.get('data') or {}).get('detail')
|
||
if detail is None:
|
||
raise RuntimeError(f'金山文档返回格式无法识别({label})')
|
||
return detail
|
||
|
||
|
||
def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||
"""读取展厅使用登记表,返回去掉空行的记录列表。"""
|
||
token = os.getenv('KINGSOFT_DOCS_TOKEN') or None
|
||
cli = _cli_path()
|
||
sheets = _call_tool('sheet.get_sheets_info', {'link_id': link_id}, token)
|
||
info = sheets['data']['detail']['sheetsInfo'][0]
|
||
sheet_id = info['sheetId']
|
||
row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS)
|
||
col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1)
|
||
data = _call_tool('sheet.get_range_data', {'link_id': link_id, 'worksheet_id': sheet_id,
|
||
'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}, token)
|
||
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
|
||
header = grid[1] if len(grid) > 1 else FIELDS
|
||
records = []
|
||
for offset, row in enumerate(grid[2:]):
|
||
values = {header[i] if i < len(header) else f'列{i+1}': value for i, value in enumerate(row)}
|
||
if any(value.strip() for value in values.values()):
|
||
values['_row'] = offset + 2 # 0 基索引:跳过标题和表头
|
||
records.append(values)
|
||
return records
|
||
|
||
|
||
def write_cell(link_id: str, row_index: int, col_index: int, value: str, editor: str) -> None:
|
||
"""写入一个单元格(0 基索引),并记录谁改了什么。"""
|
||
token = os.getenv('KINGSOFT_DOCS_TOKEN')
|
||
op = {'opType': 'formula', 'rowFrom': row_index, 'rowTo': row_index, 'colFrom': col_index, 'colTo': col_index, 'formula': value}
|
||
if token:
|
||
_call_tool('sheet.update_range_data', {'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, token)
|
||
else:
|
||
cli = _cli_path()
|
||
if not cli:
|
||
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
||
args = json.dumps({'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, ensure_ascii=False)
|
||
completed = subprocess.run([cli, 'sheet', 'update-range-data', args], capture_output=True, timeout=20)
|
||
if completed.returncode != 0:
|
||
raise RuntimeError(f'金山文档写入失败: {completed.stderr.decode("utf-8", "ignore").strip()[:200]}')
|
||
payload = json.loads(completed.stdout.decode('utf-8', 'ignore'))
|
||
if payload.get('code') != 0:
|
||
raise RuntimeError(f"金山文档写入返回 {payload.get('code')}: {payload.get('message')}")
|
||
_log_edit(editor, row_index, col_index, value)
|
||
|
||
|
||
def _log_edit(editor: str, row_index: int, col_index: int, value: str) -> None:
|
||
line = f"{datetime.now():%Y-%m-%d %H:%M:%S} | {editor} | 行{row_index + 1} 列{col_index + 1} ({FIELDS[col_index] if col_index < len(FIELDS) else '未知列'}) | 新值: {value or '(清空)'}"
|
||
try:
|
||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||
with (LOG_DIR / 'hall-log-edits.log').open('a', encoding='utf-8') as fh:
|
||
fh.write(line + '\n')
|
||
except OSError:
|
||
print(f'[hall-log] 写日志失败: {line}', flush=True)
|
||
print(f'[hall-log] {line}', flush=True)
|
||
|
||
|
||
def fetch_via_cli(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||
cli = _cli_path()
|
||
if not cli:
|
||
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
||
payload = json.loads(_run_cli(cli, link_id))
|
||
info = _unwrap(payload, '工作表信息')['sheetsInfo'][0]
|
||
sheet_id = info['sheetId']
|
||
row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS)
|
||
col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1)
|
||
args = {'link_id': link_id, 'worksheet_id': sheet_id, 'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}
|
||
data_raw = _run_cli(cli, None, ['sheet', 'get-range-data', json.dumps(args, ensure_ascii=False)])
|
||
data = json.loads(data_raw)
|
||
grid = _parse_grid(_unwrap(data, '选区数据')['rangeData'], row_to, col_to)
|
||
header = grid[1] if len(grid) > 1 else FIELDS
|
||
records = []
|
||
for offset, row in enumerate(grid[2:]):
|
||
values = {header[i] if i < len(header) else f'列{i+1}': value for i, value in enumerate(row)}
|
||
if any(value.strip() for value in values.values()):
|
||
values['_row'] = offset + 2
|
||
records.append(values)
|
||
return records
|
||
|
||
|
||
def _run_cli(cli: str, link_id: str | None, command: list[str] | None = None) -> str:
|
||
import subprocess
|
||
args = [cli]
|
||
if command:
|
||
args.extend(command)
|
||
else:
|
||
args.extend(['sheet', 'get-sheets-info', json.dumps({'link_id': link_id}, ensure_ascii=False)])
|
||
completed = subprocess.run(args, capture_output=True, timeout=20)
|
||
if completed.returncode != 0:
|
||
raise RuntimeError(f'金山文档命令行工具调用失败: {completed.stderr.decode("utf-8", "ignore").strip()[:200]}')
|
||
return completed.stdout.decode('utf-8', 'ignore')
|
||
|
||
|
||
async def snapshot(force: bool = False) -> dict:
|
||
"""带 60 秒缓存的登记表快照,避免每次页面刷新都请求外部接口。"""
|
||
async with _lock:
|
||
now = time.monotonic()
|
||
if not force and _cache['payload'] is not None and now - _cache['fetched_at'] < CACHE_TTL_SECONDS:
|
||
return _cache['payload']
|
||
link_id = os.getenv('WORKLOG_HALL_LOG_LINK_ID') or DEFAULT_LINK_ID
|
||
try:
|
||
token = os.getenv('KINGSOFT_DOCS_TOKEN')
|
||
if token:
|
||
rows = await asyncio.to_thread(fetch_rows, link_id)
|
||
else:
|
||
rows = await asyncio.to_thread(fetch_via_cli, link_id)
|
||
payload = {'ok': True, 'fetched_at': int(time.time() * 1000), 'link': f'https://www.kdocs.cn/l/{link_id}', 'records': rows, 'count': len(rows)}
|
||
_cache.update(fetched_at=now, payload=payload, error=None)
|
||
return payload
|
||
except Exception as exc:
|
||
message = str(exc) or exc.__class__.__name__
|
||
stale = _cache['payload'] if now - _cache['fetched_at'] < 600 else None
|
||
payload = {'ok': False, 'error': message, 'fetched_at': int(time.time() * 1000), 'records': stale['records'] if stale else [], 'count': len(stale['records']) if stale else 0}
|
||
_cache.update(fetched_at=now, payload=payload, error=message)
|
||
return payload
|