编辑代码
数据管理
字段字典
代码管理
服务发布
编辑:wps_cloud.py
/home/ubuntu/app/dashboard/wps_cloud.py
"""云端 WPS 抓取(开放平台 OAuth 授权码模式)。 ## 为什么存在 本地监听器(watch_wps.py)靠 WorkBuddy 的 kdocs 代理拿登录态,因此必须有一台 常开的 Mac。要真正搬到云端,只能走 WPS 开放平台的**授权码模式**: 一次性授权换 refresh_token(90 天,可自动续期),之后云端直接用 Bearer token 读表。 ## 端点(已对照另一套系统的实测实现) 授权 GET https://openapi.wps.cn/oauth2/v1/authorize?client_id=&response_type=code&redirect_uri=&scope=&state= 换token GET https://openapi.wps.cn/oauthapi/v2/token?appid=&appkey=&code= → {result:0, token:{...}} 续期 POST https://openapi.wps.cn/oauthapi/v2/token/refresh {appid,appkey,refresh_token} 短链 GET /v7/links/{link_id}/meta → {file_id, ...} 工作表 GET /v7/sheets/{file_id}/worksheets → {sheets:[{sheet_id,name}]} 读区域 GET /v7/sheets/{file_id}/worksheets/{sheet_id}/range_data?row_from&row_to&col_from&col_to ## 关键约束 - 个人 WPS 账号的表格在「个人空间」,必须走授权码模式(client_credentials 读不到) - refresh_token 90 天,**每次续期会轮换**,必须立即落库,否则下次续不上 - 错误码 10001(token 无效)/ 10002(权限不足)→ 需要重新授权 """ import json import os import threading import time from urllib.parse import urlencode import requests BASE = "https://openapi.wps.cn" # 🔴 2026-10-27 实测修正(对着官方文档 + 抓真实错误码验证): # 授权页:GET /oauth2/auth ← 不是 /oauth2/v1/authorize(那个 404) # 换token:POST /oauth2/token ← 表单编码,不是 GET /oauthapi/v2/token # 刷新: POST /oauth2/token grant_type=refresh_token # 下面这些写错会得到「404 / invalid_scope / invalid_grant」而不是业务错误,极易误判。 AUTH_PATH = "/oauth2/auth" TOKEN_URL = BASE + "/oauth2/token" # 新版 WPS 365 权限点是 kso.* 命名;旧的 cloud_file/file_selector/user_info 会报 invalid_scope。 # 读表格所需:用户基础信息 + 文件读取 + 云盘列表 + 文档库 SCOPE = os.environ.get( "WPS_SCOPE", "kso.user_base.read,kso.file.read,kso.drive.readwrite,kso.doclib.read") PLATFORM = "wps" TIMEOUT = 25 _lock = threading.Lock() _token_cache = {"access_token": None, "expire_at": 0} # ---------------- 凭证存取(复用 platform_credentials + crypto_store 加密) ---------------- def get_creds() -> dict: """读凭证:环境变量优先,其次 platform_credentials(密文)。""" env_id = os.environ.get("WPS_APP_ID") env_key = os.environ.get("WPS_APP_KEY") env_rt = os.environ.get("WPS_REFRESH_TOKEN") if env_id and env_key: return {"app_id": env_id, "app_key": env_key, "refresh_token": env_rt or ""} from db import get_conn from crypto_store import decrypt_json conn = get_conn() try: row = conn.execute( "SELECT credentials FROM platform_credentials WHERE platform=?", (PLATFORM,)).fetchone() finally: conn.close() if not row or not row["credentials"]: return {} try: return decrypt_json(row["credentials"]) or {} except Exception: return {} def save_creds(creds: dict): from db import get_conn from crypto_store import encrypt_json from datetime import datetime conn = get_conn() try: conn.execute( "INSERT OR REPLACE INTO platform_credentials(platform, credentials, updated_at)" " VALUES(?,?,?)", (PLATFORM, encrypt_json(creds), datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) conn.commit() finally: conn.close() # ---------------- OAuth ---------------- def authorize_url(redirect_uri: str, state: str, app_id: str = None) -> str: c = get_creds() aid = app_id or c.get("app_id") if not aid: raise RuntimeError("尚未配置 WPS AppID,无法生成授权链接") q = urlencode({"client_id": aid, "response_type": "code", "redirect_uri": redirect_uri, "scope": SCOPE, "state": state}) return f"{BASE}{AUTH_PATH}?{q}" def exchange_code(code: str, redirect_uri: str = "") -> dict: """授权码换 token。成功后把 refresh_token 落库。""" c = get_creds() if not (c.get("app_id") and c.get("app_key")): raise RuntimeError("尚未配置 WPS AppID/AppKey") form = {"grant_type": "authorization_code", "client_id": c["app_id"], "client_secret": c["app_key"], "code": code} if redirect_uri: form["redirect_uri"] = redirect_uri r = requests.post(TOKEN_URL, data=form, timeout=TIMEOUT) j = r.json() if r.content else {} if not j.get("access_token"): err = j.get("msg") or j.get("error") or j desc = (j.get("debug") or {}).get("desc") or "" raise RuntimeError("换 token 失败:" + str(err)[:160] + (f"({desc[:140]})" if desc else "")) tok = j creds = {**c, "refresh_token": tok.get("refresh_token") or "", "openid": tok.get("openid") or "", "scope": tok.get("scope") or "", "authorized_at": time.strftime("%Y-%m-%d %H:%M:%S")} save_creds(creds) _cache_token(tok.get("access_token"), tok.get("expires_in")) return creds def _cache_token(tok, expires_in=None): if not tok: return try: ttl = int(expires_in or 7200) except (TypeError, ValueError): ttl = 7200 # 提前 5 分钟过期,避免边界失败 _token_cache["access_token"] = tok _token_cache["expire_at"] = time.time() + max(60, ttl - 300) def access_token(force: bool = False) -> str: """取可用的 access_token;必要时用 refresh_token 续期。""" with _lock: if not force and _token_cache["access_token"] and \ _token_cache["expire_at"] > time.time(): return _token_cache["access_token"] c = get_creds() rt = c.get("refresh_token") if not (c.get("app_id") and c.get("app_key") and rt): raise RuntimeError( "WPS 云端凭证未配置(需 AppID / AppKey / refresh_token)。" "请管理员完成一次授权:GET /api/oauth/wps/authorize 拿链接。") r = requests.post(TOKEN_URL, data={ "grant_type": "refresh_token", "client_id": c["app_id"], "client_secret": c["app_key"], "refresh_token": rt}, timeout=TIMEOUT) j = r.json() if r.content else {} if not j.get("access_token"): err = j.get("msg") or j.get("error") or j raise RuntimeError( "refresh_token 续期失败(refresh_token 有效期 365 天,可能已过期;" "或应用权限被回收):" + str(err)[:160] + ";需重新授权") tok = j # ⚠️ refresh_token 会轮换,必须立刻落库,否则下次续不上 new_rt = tok.get("refresh_token") or rt if new_rt != rt or tok.get("openid") or tok.get("scope"): try: save_creds({**c, "refresh_token": new_rt, "openid": tok.get("openid") or c.get("openid", ""), # scope 是"令牌实际拿到哪些权限"的唯一权威来源: # 授权页接受某 scope ≠ 令牌里有 —— 后者才决定 403 与否 "scope": tok.get("scope") or c.get("scope", "")}) except Exception: pass _cache_token(tok.get("access_token"), tok.get("expires_in")) return _token_cache["access_token"] def _api(path: str, retry=True): tok = access_token() r = requests.get(BASE + path, headers={"Authorization": "Bearer " + tok, "Content-Type": "application/json"}, timeout=TIMEOUT) j = r.json() if r.content else {} code = j.get("code") if code not in (0, None, 200): if code in (10001,) and retry: # token 失效 → 强制续期重试一次 access_token(force=True) return _api(path, retry=False) desc = (j.get("debug") or {}).get("desc") or "" raise RuntimeError(f"WPS API code={code}:{j.get('msg') or '未知错误'}" + (f"({desc})" if desc else "")) return j.get("data") or {} # ---------------- 文档读取 ---------------- def parse_link(url: str): """/l/xxx → ('link', id);/s/xxx 或裸 id → ('file', id)。""" u = str(url or "").strip() import re m = re.search(r"/l/([A-Za-z0-9_-]+)", u) if m: return ("link", m.group(1)) m = re.search(r"/s/([A-Za-z0-9_-]+)", u) if m: return ("file", m.group(1)) m = re.search(r"[?&]f=([A-Za-z0-9_-]+)", u) if m: return ("file", m.group(1)) if re.fullmatch(r"[A-Za-z0-9_-]{8,}", u): return ("file", u) return (None, None) def resolve_file_id(url: str) -> str: kind, ident = parse_link(url) if not kind: raise RuntimeError(f"无法解析 WPS 链接:{url}") if kind == "file": return ident meta = _api(f"/v7/links/{ident}/meta") fid = meta.get("file_id") or (meta.get("data") or {}).get("file_id") if not fid: raise RuntimeError(f"短链 {ident} 未解析出 file_id(文件可能未授权给应用)") return fid def link_meta(url: str) -> dict: """短链元信息(含 mtime/size 等,用于廉价变更探测)。""" kind, ident = parse_link(url) if not kind: raise RuntimeError(f"无法解析 WPS 链接:{url}") if kind == "file": # 直接给 file_id 时走 worksheets 列表估算;元信息端点见下 return {"file_id": ident, "raw": {}} return _api(f"/v7/links/{ident}/meta") def list_sheets(file_id: str) -> list: d = _api(f"/v7/sheets/{file_id}/worksheets") return d.get("sheets") or (d.get("data") or {}).get("sheets") or [] def pick_sheet(sheets: list, sheet_name: str = "") -> dict: if sheet_name: for s in sheets: if str(s.get("name", "")).strip() == sheet_name.strip(): return s return sheets[0] if sheets else {} def read_range(file_id: str, sheet_id: str, r0: int, r1: int, c0: int = 0, c1: int = 300) -> list: path = (f"/v7/sheets/{file_id}/worksheets/{sheet_id}/range_data" f"?row_from={r0}&row_to={r1}&col_from={c0}&col_to={c1}") d = _api(path) return d.get("values") or (d.get("data") or {}).get("values") or [] def promote_header(matrix: list): """表头行提升(与本地执行器同规则):前 5 行内找 ≥3 列非空且以文本为主的行。""" if not matrix: return [], [] hi = None for i, row in enumerate(matrix[:5]): vals = [str(c).strip() for c in row if str(c).strip()] if len(vals) < 3: continue if all(not v.replace(".", "", 1).replace("-", "").isdigit() for v in vals[:5]): hi = i break if hi is None: return [str(i) for i in range(len(matrix[0]))], matrix seen, out = {}, [] for j, name in enumerate(matrix[hi]): n = str(name).strip() or f"列{j + 1}" if n in seen: seen[n] += 1 n = f"{n}_{seen[n]}" else: seen[n] = 0 out.append(n) return out, matrix[hi + 1:] def fetch_dataset(ds: dict, page_rows: int = 500, max_pages: int = 40) -> dict: """抓一张工作表 → {columns, rows, pages, sheet}。""" url = ds.get("source_url") or "" sheet_name = ds.get("sheet_name") or "" file_id = resolve_file_id(url) sheets = list_sheets(file_id) if not sheets: raise RuntimeError("未返回工作表列表(文件可能未授权给该应用)") sh = pick_sheet(sheets, sheet_name) sid = sh.get("sheet_id") if not sid: raise RuntimeError("工作表缺少 sheet_id") declared = sh.get("row_count") or sh.get("row_to") matrix, r0, pages = [], 0, 0 while True: pages += 1 chunk = read_range(file_id, sid, r0, r0 + page_rows - 1) if chunk: matrix.extend(chunk) r0 += page_rows if not chunk: break if declared and r0 >= int(declared): break if pages >= max_pages: break # 去掉尾部全空行 while matrix and not any(str(c).strip() for c in matrix[-1]): matrix.pop() if not matrix: raise RuntimeError("读取到空表") cols, rows = promote_header(matrix) return {"columns": cols, "rows": rows, "pages": pages, "sheet": sh.get("name"), "declared": declared} def probe(ds_or_url) -> dict: """廉价探测:返回用于判断"有没有变"的指纹字段。""" url = ds_or_url if isinstance(ds_or_url, str) else (ds_or_url.get("source_url") or "") meta = link_meta(url) raw = meta.get("raw") if isinstance(meta.get("raw"), dict) else meta # 不同接口返回的字段名不一致,全都捞一遍 keys = ("mtime", "modified_time", "update_time", "version", "size", "hash") fp = {k: raw.get(k) for k in keys if raw.get(k) is not None} return {"file_id": meta.get("file_id"), "fp": fp, "raw_keys": list(raw.keys())[:12]}
保存到服务器
取消