"""Wiki 页面处理核心。
从原 ``rust/wiki/wiki_processor.py`` 提取。改动:
- 包内相对导入(api/files/markdown/config)
- cookie 文件路径参数化(贯穿所有 API 调用)
- ``print`` 改为 ``logging``
- ``process_wiki_url`` / ``process_all_docs_in_kanban`` 返回 ``PullResult``,
包含主文档路径与所有产出 .md 文件路径列表(供 bot-brain 触发增量更新)
"""
from __future__ import annotations
import base64
import html as html_module
import logging
import os
import re
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Callable
from urllib.parse import urlparse, parse_qs
from .api import COOKIE_EXPIRED, get_session, wiki_api_get
from .config import ensure_login
from .files import download_file_via_api, extract_media_from_html, sanitize_filename
from .markdown import html_to_markdown
logger = logging.getLogger(__name__)
class CookieExpiredError(Exception):
"""Raised when a wiki API response indicates the login cookie has expired."""
@dataclass
class PullResult:
"""一次 wiki 拉取的结果。"""
success: bool = False
main_file: str | None = None
files: list[str] = field(default_factory=list)
output_dir: str = ""
error: str | None = None
def parse_wiki_url_with_title(url: str):
"""从 Wiki URL 中提取 domain_id, kanban_id, sn, title。
返回 (domain_id, kanban_id, sn, title);sn 可能为 None(不带 SN 的 URL)。
"""
pattern = r'https?://wiki\.huawei\.com/domains/(\d+)/wiki/(\d+)/([A-Z0-9]+)'
match = re.search(pattern, url)
if match:
domain_id = match.group(1)
kanban_id = match.group(2)
sn = match.group(3)
parsed = urlparse(url)
title = parse_qs(parsed.query).get('title', [None])[0]
return domain_id, kanban_id, sn, title
pattern_no_sn = r'https?://wiki\.huawei\.com/domains/(\d+)/wiki/(\d+)/?'
match = re.search(pattern_no_sn, url)
if match:
domain_id = match.group(1)
kanban_id = match.group(2)
parsed = urlparse(url)
title = parse_qs(parsed.query).get('title', [None])[0]
return domain_id, kanban_id, None, title
return None, None, None, None
def extract_wiki_links_from_text(text: str) -> list:
"""从文本中提取 wiki 文档链接(排除带 ?title= 的 API 链接)。"""
links = set()
pattern = r'(https?://wiki\.huawei\.com/domains/\d+/wiki/\d+/([A-Z0-9]+))(?:\?[^"\s)\]]*)?'
for match in re.finditer(pattern, text):
full_url = match.group(1)
sn = match.group(2)
query = match.group(0)[len(full_url):] if len(match.group(0)) > len(full_url) else ''
if '?title=' in query:
continue
if sn and len(sn) > 5:
links.add((sn, full_url))
return list(links)
def query_kanban_structure(session, domain_id, kanban_id, cookie_file=None):
"""查询看板目录结构(仅用于不带 SN 的看板级 URL)。"""
post_data = {"domain_id": int(domain_id), "kanban_id": int(kanban_id)}
result = wiki_api_get(
session, domain_id, kanban_id, "query_kanban_children",
post_data=post_data, cookie_file=cookie_file,
)
if result is COOKIE_EXPIRED:
raise CookieExpiredError("cookie 已失效,请重新上传 wiki cookie")
return result
def _extract_children_payload(result):
"""从 children_wiki_by_sn 响应中提取子节点列表(提取不到返回 None)。"""
if result is None:
return None
if isinstance(result, list):
return result
if isinstance(result, dict):
wiki_sub_file = result.get("wikiSubFile", {})
if isinstance(wiki_sub_file, dict):
children = wiki_sub_file.get("children", [])
return children if isinstance(children, list) else []
return []
return None
_CHILD_PAGE_SIZE = 50
_CHILD_MAX_PAGES = 200
def query_children_by_sn(session, domain_id, kanban_id, sn, cookie_file=None):
"""通过 SN 查询子节点列表(GET 请求,自动翻页)。
服务端按 pageSize 分页。仅请求单页时,子文档数超过一页上限的部分会被
静默截断,因此这里在返回满一页时继续请求下一页,按 sn 去重合并,直到
出现不足一页的页。防御性处理:
- 首页查询失败 → 返回 None(与历史行为一致,调用方按"无子文档"处理)
- 后续页失败 → 返回已获取的部分列表并告警(优于静默丢失)
- 服务端忽略页码参数导致重复返回同一页 → 按 sn 重叠检测终止并告警
"""
page_size = _CHILD_PAGE_SIZE
collected: list = []
seen_sns: set = set()
page_num = 1
while True:
params = {
"sn": sn,
"pageSize": page_size,
"page_num": page_num,
"request_tag": str(int(time.time() * 1000)),
}
result = wiki_api_get(
session, domain_id, kanban_id, "children_wiki_by_sn",
params=params, cookie_file=cookie_file,
)
if result is COOKIE_EXPIRED:
raise CookieExpiredError("cookie 已失效,请重新上传 wiki cookie")
children = _extract_children_payload(result)
if children is None:
if page_num == 1:
return None
logger.warning(
" ⚠️ 子文档第 %d 页查询失败,已获取前 %d 个,结果可能不完整",
page_num, len(collected),
)
break
new_items = [
item for item in children
if isinstance(item, dict) and item.get("sn")
and item.get("sn") not in seen_sns
]
for item in new_items:
seen_sns.add(item["sn"])
collected.extend(new_items)
if len(children) < page_size:
break
if not new_items:
logger.warning(
" ⚠️ 子文档查询第 %d 页与之前重复(服务端可能不支持分页),"
"仅获取到 %d 个子文档",
page_num, len(collected),
)
break
page_num += 1
if page_num > _CHILD_MAX_PAGES:
logger.warning(
" ⚠️ 子文档翻页达到上限 %d 页,仅获取到 %d 个子文档",
_CHILD_MAX_PAGES, len(collected),
)
break
return collected
def find_node_by_sn(nodes, target_sn):
"""从节点列表中递归查找指定 sn 的节点。"""
for node in nodes:
if node.get("sn") == target_sn:
return node
if node.get("has_child") and "children" in node:
found = find_node_by_sn(node["children"], target_sn)
if found:
return found
return None
def _collect_md_files(directory: str) -> list[str]:
"""收集目录下所有 .md 文件(递归),返回相对 directory 的路径。"""
result = []
for root, _dirs, files in os.walk(directory):
for fname in files:
if fname.endswith(".md"):
result.append(os.path.join(root, fname))
return result
def fetch_wiki_page_via_api(
session,
url,
output_dir,
visited_urls=None,
depth=0,
domain_id=None,
kanban_id=None,
parent_dir=None,
parent_map=None,
skip_children=False,
skip_refs=False,
is_ref=False,
root_domain_id=None,
root_kanban_id=None,
parsed_domain_override=None,
parsed_kanban_override=None,
ref_list=None,
cookie_file=None,
produced_files=None,
):
"""使用 Wiki 内部 API 获取文档内容,转换为 Markdown,递归处理子链接。
``produced_files``:若传入一个 list,所有产出的 .md 文件路径会追加进去,
供调用方收集(bot-brain 据此触发增量图谱更新)。
返回主文档的 .md 文件路径。
"""
if visited_urls is None:
visited_urls = set()
if ref_list is None:
ref_list = []
task_queue = [(url, output_dir, depth, domain_id, kanban_id, parent_dir, False, root_domain_id, root_kanban_id)]
main_md_filepath = None
while task_queue:
task = task_queue.pop(0)
if len(task) == 9:
(current_url, current_output_dir, current_depth, current_domain_id,
current_kanban_id, current_parent_dir, current_is_ref,
current_root_domain_id, current_root_kanban_id) = task
elif len(task) == 8:
current_url, current_output_dir, current_depth, current_domain_id, current_kanban_id, current_parent_dir, current_is_ref, current_root_domain_id = task
current_root_kanban_id = None
else:
current_url, current_output_dir, current_depth, current_domain_id, current_kanban_id, current_parent_dir = task
current_is_ref = False
current_root_domain_id = None
current_root_kanban_id = None
normalized_url = current_url.rstrip("/").split("#")[0].split("?")[0]
if normalized_url in visited_urls:
continue
visited_urls.add(normalized_url)
indent = " " * current_depth
logger.info("%s📄 处理文档: %s", indent, current_url)
parsed_domain, parsed_kanban, sn, title_param = parse_wiki_url_with_title(current_url)
if not all([parsed_domain, parsed_kanban, sn]):
logger.info("%s❌ 无法解析 URL", indent)
continue
if current_is_ref:
current_domain_id = parsed_domain
current_kanban_id = parsed_kanban
else:
if current_domain_id is None:
current_domain_id = parsed_domain
if current_kanban_id is None:
current_kanban_id = parsed_kanban
doc_data = wiki_api_get(
session, current_domain_id, current_kanban_id, "get_document",
post_data={
"wiki_sn": sn,
"type": "UI",
"domain_id": int(current_domain_id),
"kanban_id": int(current_kanban_id),
},
cookie_file=cookie_file,
)
if doc_data is COOKIE_EXPIRED:
raise CookieExpiredError("cookie 已失效,请重新上传 wiki cookie")
if not isinstance(doc_data, dict):
logger.info("%s⚠️ 可能权限不够,无法访问该文档(跨知识库引用)", indent)
continue
doc_title = doc_data.get("title", sn)
folder_name = sanitize_filename(doc_title)
if current_parent_dir:
doc_dir = os.path.join(current_parent_dir, folder_name)
else:
doc_dir = os.path.join(current_output_dir, folder_name)
assets_dir = os.path.join(doc_dir, ".asserts")
os.makedirs(assets_dir, exist_ok=True)
paragraphs = doc_data.get("paragraphs", [])
total_media_count = 0
md_parts = []
for para in paragraphs:
ui_source = para.get("ui_source", 1)
content = para.get("content", "")
if ui_source == 2:
try:
try:
padding = 4 - len(content) % 4
if padding != 4:
content_padded = content + "=" * padding
else:
content_padded = content
decoded_bytes = base64.b64decode(content_padded)
content = decoded_bytes.decode("utf-8")
except Exception:
try:
content = content.decode("utf-8") if isinstance(content, bytes) else str(content)
except Exception:
try:
content = content.decode("gbk") if isinstance(content, bytes) else str(content)
except Exception:
content = str(content)
content = html_module.unescape(content)
def replace_md_media(m):
nonlocal total_media_count
alt = m.group(1)
url_m = m.group(2)
if "vision-file-storage" in url_m:
path_match = re.search(r'(/vision-file-storage/api/file/download/[^"\')\s?]+)', url_m)
if path_match:
path = path_match.group(1)
local = download_file_via_api(session, path, assets_dir, base_url=None, wiki_sn=sn, cookie_file=cookie_file)
if local != path:
total_media_count += 1
return f""
else:
local = download_file_via_api(session, url_m, assets_dir, base_url=current_url, cookie_file=cookie_file)
if local != url_m:
total_media_count += 1
return f""
return m.group(0)
def replace_md_attachment(m):
nonlocal total_media_count
text_m = m.group(1)
url_m = m.group(2)
if m.group(0).startswith('!'):
return m.group(0)
if "vision-file-storage" in url_m:
path_match = re.search(r'(/vision-file-storage/api/file/download/[^"\')\s?]+)', url_m)
if path_match:
path = path_match.group(1)
local = download_file_via_api(session, path, assets_dir, base_url=None, wiki_sn=sn, cookie_file=cookie_file)
if local != path:
total_media_count += 1
return f"[{text_m}]({local})"
else:
local = download_file_via_api(session, url_m, assets_dir, base_url=current_url, cookie_file=cookie_file)
if local != url_m:
total_media_count += 1
return f"[{text_m}]({local})"
return m.group(0)
content = re.sub(r'!\[([^\]]*)\]\(([^)]+)\)', replace_md_media, content)
content = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', replace_md_attachment, content)
except Exception as e:
logger.warning("处理 Markdown 内容时出错: %s", e)
md_parts.append(content)
else:
processed_html, media_count = extract_media_from_html(
content, current_domain_id, current_kanban_id, assets_dir, session, current_url, sn, cookie_file=cookie_file,
)
total_media_count += media_count
md_content = html_to_markdown(processed_html)
md_parts.append(md_content)
md_lines = [
f"# {doc_title}",
"",
f"> 来源: [{current_url}]({current_url})",
f"> 导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"",
"---",
"",
]
for part in md_parts:
if part.strip():
md_lines.append(part)
md_lines.append("")
md_content = "\n".join(md_lines)
md_filename = f"{folder_name}.md"
md_filepath = os.path.join(doc_dir, md_filename)
with open(md_filepath, "w", encoding="utf-8") as f:
f.write(md_content)
logger.info("%s 📝 已保存: %s (%d 个媒体资源)", indent, md_filename, total_media_count)
if produced_files is not None:
produced_files.append(md_filepath)
if main_md_filepath is None:
main_md_filepath = md_filepath
child_sns = set()
if is_ref:
logger.info("%s ⏭️ 当前文档为引用文档,跳过子页面和引用页面拉取", indent)
else:
if not skip_children:
query_domain_id = parsed_domain
query_kanban_id = parsed_kanban
children = query_children_by_sn(session, query_domain_id, query_kanban_id, sn, cookie_file=cookie_file)
if children:
logger.info("%s 📋 获取到 %d 个子文档", indent, len(children))
for child in children:
child_sn = child.get("sn", "")
child_title = child.get("title", "")
if not child_sn or child_sn == sn:
continue
if child_sn in child_sns:
continue
child_sns.add(child_sn)
child_url = f"https://wiki.huawei.com/domains/{current_domain_id}/wiki/{current_kanban_id}/{child_sn}"
if child_url not in visited_urls:
logger.info("%s 📎 发现子文档: %s (%s)", indent, child_title, child_sn)
task_queue.append((child_url, current_output_dir, current_depth + 1, current_domain_id, current_kanban_id, doc_dir, False, current_root_domain_id, current_root_kanban_id))
else:
logger.info("%s ℹ️ 当前文档无子文档", indent)
if not skip_refs:
sub_links = extract_wiki_links_from_text(md_content)
new_links = []
for link_sn, link_url in sub_links:
link_normalized = link_url.rstrip("/").split("#")[0].split("?")[0]
if link_sn != sn and link_normalized not in visited_urls and link_sn not in child_sns:
new_links.append((link_sn, link_url))
if new_links:
logger.info("%s 🔗 发现 %d 个文本内子链接待处理", indent, len(new_links))
for link_sn, link_url in new_links:
if ref_list is not None:
ref_list.append((current_url, link_sn, link_url, current_output_dir, current_depth + 1, current_domain_id, current_kanban_id, doc_dir, True, current_root_domain_id, current_root_kanban_id))
logger.info("%s 📝 记录引用关系: %s", indent, link_sn)
else:
task_queue.append((link_url, current_output_dir, current_depth + 1, current_domain_id, current_kanban_id, doc_dir, True, current_root_domain_id, current_root_kanban_id))
else:
logger.info("%s ⏭️ 跳过子页面拉取(skip_children=True)", indent)
return main_md_filepath
def process_wiki_url(
session,
url: str,
output_dir: str,
skip_refs: bool = False,
skip_children: bool = False,
cookie_file: str | None = None,
on_progress: Callable[[str], None] | None = None,
) -> PullResult:
"""处理单个 wiki URL,返回 PullResult。
``output_dir``:文档保存目录(绝对路径)。
``cookie_file``:cookie 文件路径(None 用默认)。
"""
logger.info("=" * 60)
logger.info("开始处理 Wiki 页面: %s", url)
logger.info("=" * 60)
os.makedirs(output_dir, exist_ok=True)
produced_files: list[str] = []
parsed_domain, parsed_kanban, sn, title_param = parse_wiki_url_with_title(url)
if parsed_domain and parsed_kanban and sn:
try:
children = query_children_by_sn(session, parsed_domain, parsed_kanban, sn, cookie_file=cookie_file)
if children:
logger.info(" ℹ️ 目标 wiki 有 %d 个子文档,将正常拉取子页面", len(children))
else:
skip_children = True
logger.info(" ℹ️ 目标 wiki 无子文档,将跳过子页面拉取")
except Exception as e:
logger.warning(" ⚠️ 查询子节点失败: %s,将按默认方式处理", e)
ref_list = []
if on_progress:
on_progress("开始下载文档...")
result = fetch_wiki_page_via_api(
session, url, output_dir, parent_dir=None, parent_map=None,
skip_children=skip_children, skip_refs=skip_refs,
root_domain_id=parsed_domain, root_kanban_id=parsed_kanban,
ref_list=ref_list, cookie_file=cookie_file, produced_files=produced_files,
)
if ref_list:
logger.info("📝 开始处理 %d 个引用的Wiki...", len(ref_list))
if on_progress:
on_progress(f"处理 {len(ref_list)} 个引用文档...")
visited_urls = set()
for ref_item in ref_list:
ref_url = ref_item[2]
ref_normalized = ref_url.rstrip("/").split("#")[0].split("?")[0]
if ref_normalized not in visited_urls:
visited_urls.add(ref_normalized)
ref_parsed_domain, ref_parsed_kanban, ref_sn, _ = parse_wiki_url_with_title(ref_url)
if ref_parsed_domain and ref_parsed_kanban and ref_sn:
if ref_parsed_domain == parsed_domain and ref_parsed_kanban == parsed_kanban:
logger.info(" 📌 引用文档 %s 属于当前知识库,跳过下载", ref_sn)
else:
logger.info(" 🔧 处理外部引用文档: %s", ref_sn)
fetch_wiki_page_via_api(
session, ref_url, ref_item[3], visited_urls=set(), depth=ref_item[4],
domain_id=ref_item[5], kanban_id=ref_item[6], parent_dir=ref_item[7],
is_ref=ref_item[8], root_domain_id=ref_item[9], root_kanban_id=ref_item[10],
skip_children=True, skip_refs=True,
cookie_file=cookie_file, produced_files=produced_files,
)
if result:
logger.info("=" * 60)
logger.info("✅ 完成!文档已保存到: %s", result)
logger.info("=" * 60)
if on_progress:
on_progress(f"下载完成,共 {len(produced_files)} 个文件")
return PullResult(success=True, main_file=result, files=produced_files, output_dir=output_dir)
logger.error("处理失败")
return PullResult(success=False, files=produced_files, output_dir=output_dir, error="fetch returned no main file")
def process_all_docs_in_kanban(
session,
domain_id,
kanban_id,
output_dir,
url=None,
skip_refs=False,
skip_children=False,
cookie_file=None,
on_progress: Callable[[str], None] | None = None,
) -> PullResult:
"""处理类目下所有文档。"""
logger.info("=" * 60)
logger.info("开始处理类目 %s 下的所有文档", kanban_id)
logger.info("=" * 60)
os.makedirs(output_dir, exist_ok=True)
produced_files: list[str] = []
root_sn = None
if url:
parsed_domain, parsed_kanban, sn, title_param = parse_wiki_url_with_title(url)
if parsed_domain and parsed_kanban:
domain_id = parsed_domain
kanban_id = parsed_kanban
root_sn = sn
all_nodes = query_kanban_structure(session, domain_id, kanban_id, cookie_file=cookie_file)
if not all_nodes:
logger.error("❌ 获取看板目录结构失败")
return PullResult(success=False, output_dir=output_dir, error="获取看板目录结构失败")
if root_sn:
root_url = f"https://wiki.huawei.com/domains/{domain_id}/wiki/{kanban_id}/{root_sn}"
result = fetch_wiki_page_via_api(
session, root_url, output_dir, visited_urls=set(), depth=0,
domain_id=domain_id, kanban_id=kanban_id, parent_dir=None, parent_map=None,
skip_refs=skip_refs, skip_children=skip_children,
root_domain_id=domain_id, root_kanban_id=kanban_id,
cookie_file=cookie_file, produced_files=produced_files,
)
success = bool(result)
else:
root_nodes = []
for node in all_nodes:
node_sn = node.get("sn", "")
title = node.get("cur_title", node.get("title", ""))
if node_sn:
root_nodes.append((node_sn, title))
if not root_nodes:
logger.error("❌ 看板目录树中没有找到任何顶层节点")
return PullResult(success=False, output_dir=output_dir, error="无顶层节点")
logger.info("📋 发现 %d 个顶层节点,开始逐个处理...", len(root_nodes))
if on_progress:
on_progress(f"发现 {len(root_nodes)} 个顶层节点,开始下载...")
success_count = 0
for i, (node_sn, node_title) in enumerate(root_nodes, 1):
node_url = f"https://wiki.huawei.com/domains/{domain_id}/wiki/{kanban_id}/{node_sn}"
logger.info("[%d/%d] 处理节点: %s (%s)", i, len(root_nodes), node_title, node_sn)
if on_progress:
on_progress(f"下载 {i}/{len(root_nodes)}: {node_title} ({node_sn})")
try:
result = fetch_wiki_page_via_api(
session, node_url, output_dir, visited_urls=set(), depth=0,
domain_id=domain_id, kanban_id=kanban_id, parent_dir=None, parent_map=None,
skip_refs=skip_refs, skip_children=skip_children,
root_domain_id=domain_id, root_kanban_id=kanban_id,
cookie_file=cookie_file, produced_files=produced_files,
)
if result:
success_count += 1
except Exception as e:
logger.error(" ❌ 处理节点 %s 失败: %s", node_sn, e)
success = success_count > 0
logger.info("=" * 60)
logger.info("✅ 处理完成!产出 %d 个文件", len(produced_files))
logger.info("=" * 60)
return PullResult(success=success, files=produced_files, output_dir=output_dir)
def pull_wiki(
url: str,
output_dir: str,
cookie_file: str | None = None,
all_docs: bool = False,
include_refs: bool = False,
include_children: bool = False,
on_progress: Callable[[str], None] | None = None,
) -> PullResult:
"""高层入口:确保登录 → 建立 session → 拉取 → 返回结果。
参数语义与原 ``huawei_wiki_helper.py`` 一致:
- ``all_docs``:处理整个 kanban 下所有文档
- ``include_refs``/``include_children``:默认均为 False(不拉引用/子文档),
与原脚本 ``--pull`` 的默认行为(-no-ref -no-child)一致。
- ``on_progress``:可选回调,接收进度描述字符串(如 "已下载 3/15 篇")。
"""
try:
if not ensure_login(cookie_file):
return PullResult(success=False, output_dir=output_dir, error="登录失败或 cookie 过期,请先调用 upload_wiki_cookie 上传 cookie")
session = get_session(cookie_file)
except RuntimeError as e:
return PullResult(success=False, output_dir=output_dir, error=str(e))
except ImportError as e:
return PullResult(success=False, output_dir=output_dir, error=f"缺少依赖: {e}")
parsed_domain, parsed_kanban, sn, _ = parse_wiki_url_with_title(url)
if not parsed_domain or not parsed_kanban:
return PullResult(success=False, output_dir=output_dir, error=f"无法解析 URL: {url}")
skip_refs = not include_refs
skip_children = not include_children
try:
if all_docs or sn is None:
return process_all_docs_in_kanban(
session, parsed_domain, parsed_kanban, output_dir,
url=url, skip_refs=skip_refs, skip_children=skip_children,
cookie_file=cookie_file, on_progress=on_progress,
)
return process_wiki_url(
session, url, output_dir,
skip_refs=skip_refs, skip_children=skip_children,
cookie_file=cookie_file, on_progress=on_progress,
)
except CookieExpiredError as e:
return PullResult(
success=False, output_dir=output_dir,
error=f"cookie 已失效: {e}。请重新上传 wiki cookie",
)