131 lines
6.2 KiB
Python
131 lines
6.2 KiB
Python
"""赋能中心展厅使用登记:实时读取金山文档在线表格。"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import shutil
|
|
import time
|
|
import urllib.request
|
|
from typing import Any
|
|
|
|
|
|
DEFAULT_LINK_ID = 'cnC7HwRAxKf9'
|
|
ENDPOINT = 'https://mcp-center.wps.cn/skill_hub/api/v1/tool'
|
|
CACHE_TTL_SECONDS = 60
|
|
MAX_ROWS = 500
|
|
FIELDS = ['序号', '日期', '时间', '使用场地', '参加人数', '使用事项', '使用单位', '使用单位联系人及联系方式', '赋能部值班人员及联系方式', '备注']
|
|
_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:
|
|
payload = json.loads(response.read().decode('utf-8'))
|
|
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_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 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 row in 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()):
|
|
records.append(values)
|
|
return records
|
|
|
|
|
|
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 环境变量')
|
|
subprocess = _run_cli(cli, link_id)
|
|
payload = json.loads(subprocess)
|
|
if payload.get('code') != 0:
|
|
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
|
info = payload['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)
|
|
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)
|
|
if data.get('code') != 0:
|
|
raise RuntimeError(f"金山文档接口返回 {data.get('code')}: {data.get('message')}")
|
|
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
|
|
header = grid[1] if len(grid) > 1 else FIELDS
|
|
records = []
|
|
for row in 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()):
|
|
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
|