"""Safe rich text containing only text, formatting and owned media references.""" import re def normalize(value): count = 0 length = 0 media = [] plain = [] blocks = {'paragraph', 'heading', 'blockquote', 'bulletList', 'orderedList', 'listItem', 'media'} def walk(node, parent='', depth=0): nonlocal count, length count += 1 if count > 1200 or depth > 12 or not isinstance(node, dict): raise ValueError('正文结构过多或层级过深') kind = node.get('type') allowed = {'doc': blocks, 'paragraph': {'text', 'hardBreak'}, 'heading': {'text', 'hardBreak'}, 'blockquote': blocks, 'listItem': blocks, 'bulletList': {'listItem'}, 'orderedList': {'listItem'}} if parent and kind not in allowed.get(parent, set()): raise ValueError('正文格式不支持') if not parent and kind != 'doc': raise ValueError('正文格式不正确') result = {'type': kind} if kind == 'media': mid = (node.get('attrs') or {}).get('mediaId') if not isinstance(mid, str) or not re.fullmatch('[a-f0-9]{16}', mid): raise ValueError('素材引用不正确') media.append(mid) if len(media) > 30 or len(set(media)) > 9: raise ValueError('每条记事最多引用 9 个不同素材、30 处位置') result['attrs'] = {'mediaId': mid} return result if kind == 'text': text = node.get('text') if not isinstance(text, str) or not text: raise ValueError('正文文字不正确') length += len(text) if length > 5000: raise ValueError('正文文字最多 5000 字') result['text'] = text; plain.append(text) marks = node.get('marks', []) if not isinstance(marks, list) or len(marks) > 4: raise ValueError('文字格式不正确') if marks: names = [m.get('type') if isinstance(m, dict) else '' for m in marks] if any(n not in ('bold', 'italic', 'strike', 'underline') for n in names): raise ValueError('文字格式不支持') result['marks'] = [{'type': n} for n in dict.fromkeys(names)] return result if kind == 'hardBreak': plain.append('\n'); return result if kind not in allowed: raise ValueError('正文包含不支持的内容') children = node.get('content', []) if not isinstance(children, list): raise ValueError('正文内容不正确') if kind == 'heading': level = (node.get('attrs') or {}).get('level', 2) if type(level) is not int or level not in (2, 3): raise ValueError('标题层级不正确') result['attrs'] = {'level': level} if kind == 'orderedList': start = (node.get('attrs') or {}).get('start', 1) if type(start) is not int or not 1 <= start <= 9999: raise ValueError('列表编号不正确') result['attrs'] = {'start': start} result['content'] = [walk(child, kind, depth+1) for child in children] if kind in ('paragraph', 'heading'): plain.append('\n') return result doc = walk(value) return doc, ''.join(plain).strip(), list(dict.fromkeys(media))