fix(settings): add DingTalk spaces and render the real login QR

Address two gaps in the first DingTalk-session UI:
- add an explicit admin-only '+ 新增钉钉知识库' action on the data-source
  panel; it accepts an alidocs space URL, resolves the live name/root through
  the authenticated sidecar, writes the inventory root atomically, upserts a
  deterministic source connection, and enqueues its first catalog refresh
- read DingTalk's real QR canvas pixels rather than taking a DOM screenshot;
  select by dark-pixel content, composite onto a white quiet zone, and render
  at 320x320 so the dialog contains a large complete code, not a page thumbnail

The live refresh path resolves registered roots from the connection locator,
while existing name-based DingTalk sources remain compatible.
This commit is contained in:
姚章浩
2026-09-14 22:53:01 +08:00
parent 173b44abca
commit e60b10256a
15 changed files with 560 additions and 79 deletions
+16 -6
View File
@@ -4,7 +4,7 @@ Runs only inside the ordinary governance worker. It reads restricted credentials
uses allowlisted read-only APIs, writes temporary files under /tmp, and never
downloads AList content or invokes source write/delete APIs.
"""
import argparse,csv,io,json,os,pathlib,subprocess,sys,tempfile
import argparse,csv,io,json,os,pathlib,re,subprocess,sys,tempfile
from collections import deque
sys.path.insert(0,'/app/scripts')
from source_catalog_import import build_alist_source,build_dingtalk_sources,build_pp_live_source,catalog_sql,validate_source
@@ -54,9 +54,19 @@ def refresh_pp():
emit('building',78,'本地内容清单暂不可用,将记录为新资料待校验')
return build_pp_live_source(inventory,manifest)
def refresh_dingtalk(name):
def refresh_dingtalk(name,connection_id=''):
root=pathlib.Path('/sources/dingtalk/data/dingtalk-internal/inventory-state.json');state=json.loads(root.read_text())
matches=[(key,value) for key,value in state['roots'].items() if value.get('live_space_name')==name]
# Prefer the root registered on the connection row (spaces/<root>?space=):
# name matching is the legacy fallback for the imported sources.
root_id=''
if connection_id and re.fullmatch(r'[A-Za-z0-9_.:-]{1,36}',connection_id):
try:
rows=subprocess.run(['psql','-X','-At','-d',os.environ.get('DATABASE_URL',''),'-c',"SELECT base_url FROM source_connections WHERE id='"+connection_id+"'"],capture_output=True,text=True,timeout=30)
locator=rows.stdout.strip() if rows.returncode==0 else ''
if locator.startswith('spaces/'):root_id=locator.split('?',1)[0][len('spaces/'):]
except Exception:root_id=''
matches=[(key,value) for key,value in state['roots'].items() if (root_id and value.get('configured_root_id')==root_id) or value.get('live_space_name')==name]
if root_id and len(matches)>1:matches=[m for m in matches if m[1].get('configured_root_id')==root_id]
if len(matches)!=1:raise RuntimeError('DingTalk source root missing')
key,current=matches[0];output=pathlib.Path('/tmp')/('dingtalk-'+key+'-live.json')
if output.exists():output.unlink()
@@ -72,7 +82,7 @@ def refresh_dingtalk(name):
current_progress=10+(65*done//total if total else 65);last=max(last,current_progress)
emit('scanning',last,f"正在扫描目录:已完成 {done} 个文件夹,待处理 {pending} 个",done,total,scanned_directories=done,discovered_directories=total,scanned_files=files,estimated_total_files=files,total_is_estimate=True)
if process.wait()!=0 or not output.is_file():raise RefreshBlocked('钉钉登录会话已失效,请在来源链接重新扫码')
payload=json.loads(output.read_text());sources=build_dingtalk_sources(payload);match=[source for source in sources if source['name']==name]
payload=json.loads(output.read_text());sources=build_dingtalk_sources(payload);match=[source for source in sources if source.get('root_node_id')==current['configured_root_id'] or source['name']==name]
if len(match)!=1:raise RuntimeError('DingTalk refreshed source missing')
emit('building',80,'正在校验钉钉父子目录和文件数量')
return match[0]
@@ -114,11 +124,11 @@ def refresh_alist(name):
return build_alist_source(slug,name,dir_buf,file_buf)
def main():
parser=argparse.ArgumentParser();parser.add_argument('--connection-id',required=True);parser.add_argument('--source-type',choices=('pp','dingtalk','alist'),required=True);parser.add_argument('--source-name',required=True);args=parser.parse_args()
parser=argparse.ArgumentParser();parser.add_argument('--connection-id',required=True);parser.add_argument('--source-type',choices=('pp','dingtalk','alist'),required=True);parser.add_argument('--source-name',required=True);parser.add_argument('--source-space-id',default='');args=parser.parse_args()
global _source_name;_source_name=args.source_name
try:
if args.source_type=='pp':source=refresh_pp()
elif args.source_type=='dingtalk':source=refresh_dingtalk(args.source_name)
elif args.source_type=='dingtalk':source=refresh_dingtalk(args.source_name,args.connection_id)
else:source=refresh_alist(args.source_name)
validate_source(source);emit('activating',92,'正在写入不可变快照并切换当前版本',source['node_count'],source['node_count'])
run_psql(catalog_sql(source,args.connection_id,apply=True));emit('completed',100,f"实时快照完成:{source['folder_count']-1} 个目录,{source['file_count']} 份文件",source['node_count'],source['node_count'])