fix(fetch): 钉钉空文档显式报 empty_document

DingTalk exports empty online documents to valid but contentless docx/xlsx;
WeKnora then rejects them with a generic remote_parse_failed. Detect blank
exports (no text, no embedded media) at fetch time and report the cause in
Chinese, and add the matching dead-letter hint.
This commit is contained in:
姚章浩
2026-09-15 17:20:37 +08:00
parent 0ef41594c2
commit 822896ea6c
3 changed files with 109 additions and 3 deletions
+40 -3
View File
@@ -381,20 +381,29 @@ def _space_key(roots, name):
def dingtalk_download(manifest, max_bytes):
spreadsheet = pathlib.PurePosixPath(manifest["name"]).suffix.lower() == ".axls"
def guarded(local_path):
if pathlib.PurePosixPath(str(local_path)).suffix.lower() in (".docx", ".xlsx") \
and exported_doc_is_blank(local_path, spreadsheet):
raise FetchError("钉钉文档正文为空,无需入库(如确有内容请在钉钉里补充后重新取件)",
retryable=False, code="empty_document")
return local_path
export = dingtalk_local_export(manifest)
modified = str(manifest.get("modified_at") or "")
if export:
path, fresh = export
size = os.path.getsize(path)
if size > 0 and (fresh or not modified):
return path, size, sha256_file(path), True
return guarded(path), size, sha256_file(path), True
# stale local export -> fall through to a live export when available
raw_key, declared_type = dingtalk_raw_keys(manifest)
headers = load_capture_headers()
live_path = live_export_dingtalk_document(raw_key, headers, manifest, max_bytes)
if export and not live_path:
path, fresh = export
return path, os.path.getsize(path), sha256_file(path), True # keep old bytes; staleness shown in UI
return guarded(path), os.path.getsize(path), sha256_file(path), True # keep old bytes; staleness shown in UI
if not live_path:
raise MissingSource("DingTalk file is not exported and cannot be exported automatically")
return live_path
@@ -436,6 +445,30 @@ def dingtalk_put_bytes(url, payload):
retryable=error.code == 429 or error.code >= 500, code="http_%d" % error.code)
def exported_doc_is_blank(path, spreadsheet):
"""DingTalk happily exports an empty online document to a valid but
contentless docx/xlsx. The parser rejects those with a generic
remote_parse_failed, so flag them here with an actionable message."""
try:
import zipfile
with zipfile.ZipFile(path) as archive:
names = archive.namelist()
if any(name.startswith("word/media/") or name.startswith("xl/media/") for name in names):
return False # image-only doc: the parser still has something to read
parts = ["xl/sharedStrings.xml"] if spreadsheet else ["word/document.xml"]
for part in parts:
try:
blob = archive.read(part)
except KeyError:
blob = b""
text = re.sub(rb"<[^>]+>", b"", blob).strip()
if text:
return False
return True
except Exception:
return False # unreadable zip: the magic/type checks handle that error
def dingtalk_export_adoc(info, headers, manifest, max_bytes, spreadsheet=False):
doc_key = str(info.get("docKey") or "")
dentry_key = str(info.get("dentryKey") or "")
@@ -479,7 +512,11 @@ def dingtalk_export_adoc(info, headers, manifest, max_bytes, spreadsheet=False):
headers, extra_headers=extra)
detail = status.get("data") or {}
if detail.get("status") == "success" and detail.get("ossUrl"):
return http_get(detail["ossUrl"], {}, 180, max_bytes) + (False,)
result = http_get(detail["ossUrl"], {}, 180, max_bytes)
if exported_doc_is_blank(result[0], spreadsheet):
raise FetchError("钉钉文档正文为空,无需入库(如确有内容请在钉钉里补充后重新取件)",
retryable=False, code="empty_document")
return result + (False,)
if detail.get("status") in ("fail", "failed", "error"):
raise FetchError("DingTalk export job failed", retryable=False, code="export_failed")
time.sleep(3)
+68
View File
@@ -0,0 +1,68 @@
import io
import pathlib
import tempfile
import unittest
import zipfile
MODULE_PATH = pathlib.Path(__file__).with_name("artifact_fetch.py")
import importlib.util
spec = importlib.util.spec_from_file_location("artifact_fetch", MODULE_PATH)
assert spec is not None and spec.loader is not None
artifact_fetch = importlib.util.module_from_spec(spec)
spec.loader.exec_module(artifact_fetch)
def make_docx(document_xml, media=None):
handle = tempfile.NamedTemporaryFile(suffix=".docx", delete=False)
with zipfile.ZipFile(handle, "w") as archive:
archive.writestr("word/document.xml", document_xml)
for name in media or []:
archive.writestr("word/media/" + name, b"\x89PNG fake")
return handle.name
class ExportedBlankDocTest(unittest.TestCase):
def test_empty_body_docx_is_flagged_blank(self):
# What DingTalk produces for an empty online document: valid zip,
# document.xml with no text nodes.
path = make_docx('<?xml version="1.0"?><w:document><w:body><w:p/></w:body></w:document>')
try:
self.assertTrue(artifact_fetch.exported_doc_is_blank(path, False))
finally:
pathlib.Path(path).unlink()
def test_text_docx_is_not_blank(self):
path = make_docx("<w:document><w:t>开箱步骤</w:t></w:document>")
try:
self.assertFalse(artifact_fetch.exported_doc_is_blank(path, False))
finally:
pathlib.Path(path).unlink()
def test_image_only_docx_is_not_blank(self):
path = make_docx("<w:document><w:body><w:p/></w:body></w:document>", media=["image1.png"])
try:
self.assertFalse(artifact_fetch.exported_doc_is_blank(path, False))
finally:
pathlib.Path(path).unlink()
def test_spreadsheet_checks_shared_strings(self):
handle = tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False)
with zipfile.ZipFile(handle, "w") as archive:
archive.writestr("xl/sharedStrings.xml", "<sst><si><t>表头</t></si></sst>")
try:
self.assertFalse(artifact_fetch.exported_doc_is_blank(handle.name, True))
finally:
pathlib.Path(handle.name).unlink()
def test_unreadable_file_is_not_judged_blank(self):
handle = tempfile.NamedTemporaryFile(suffix=".docx", delete=False)
handle.write(b"not a zip at all")
handle.close()
try:
self.assertFalse(artifact_fetch.exported_doc_is_blank(handle.name, False))
finally:
pathlib.Path(handle.name).unlink()
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -38,6 +38,7 @@ const failureHint = (failure: JobFailure) => {
if (detail.includes('invalid_format')) return '取回的内容不是有效的文档/文本格式,可能源头文件本身损坏;可下载原件确认后重试。'
if (detail.includes('source_unavailable')) return '来源服务当时不可达(网络/接口抖动)。任务若已自动重试成功,这里只是历史记录;仍在列表说明源头仍不可达。'
if (failure.error_code === 'test_upload_remote_failed' || detail.includes('test_upload_remote_failed')) return '向测试知识库上传被拒:确认 WeKnora 测试实例可达、目标知识库未停用后,点击重新入队。'
if (detail.includes('empty_document')) return '钉钉文档正文为空(源头就是空文档),解析器拒收空内容;无需重试,在钉钉里补充内容后重新取件即可。'
if (failure.error_code === 'remote_parse_failed') return '文档解析失败:建议先在 WeKnora 手动解析该文件确认格式,再重新入队。'
if (failure.error_code === 'handler_error') return '处理环节报错,展开原始错误定位;确认原因后可重新入队。'
return `错误码 ${failure.error_code}:确认原因后可重新入队。`