返回 Social Auto Upload
1 """Business Suite 原作品查询及删除,使用内容编号而非标题作为身份依据。"""
2
3 import asyncio
4 import re
5 from datetime import datetime, timezone
6 from pathlib import Path
7 from urllib.parse import parse_qs, urlparse
8 from uuid import uuid4
9
10 from patchright.async_api import async_playwright, expect, TimeoutError as BrowserTimeoutError
11
12 from uploader.meta_uploader.facebook_page_uploader.main import _open_business_page
13
14
15 async def open_meta_post(page, *, list_url: str, page_name: str, expected_text: str,
16 content_id: str | None = None, schedule=None):
17 """查询唯一配文、核对 Page 并打开详情,发布后及删除前共用此原作品核验。"""
18 # 新建 Reels 已出现在列表时,平台搜索仍可能无结果;读取原始列表避免搜索索引延迟。
19 # 当前仅覆盖列表已加载的作品,超时明确报错,不以同文案的其他作品代替。
20 # Reels 创建响应先受理,随后才进入内容列表;首次列表可能是处理完成前的快照。
21 # 只刷新查询原作品,绝不在此重发;每次读取有界且配文出现多个时立即停止。
22 deadline = asyncio.get_running_loop().time() + 120
23 row = page.get_by_role("row").filter(has_text=expected_text)
24 while True:
25 await page.goto(list_url, wait_until="domcontentloaded", timeout=90000)
26 try:
27 await row.wait_for(state='visible', timeout=10000)
28 except BrowserTimeoutError:
29 if asyncio.get_running_loop().time() >= deadline:
30 raise TimeoutError('原作品列表未找到请求记录;结果待核实,禁止直接重发')
31 else:
32 await expect(row).to_have_count(1)
33 break
34 await expect(row).to_contain_text(page_name)
35 if parse_qs(urlparse(page.url).query).get('asset_id') != parse_qs(urlparse(list_url).query).get('asset_id'):
36 raise RuntimeError('列表实际 Page ID 与请求不一致;未删除')
37 is_reel = 'Reels' in await row.inner_text()
38 # 已发布列表的 TITLE 网格单元承载详情入口,指标也有 aria-pressed,不能混选。
39 # 已定时列表仍为旧布局,标题是唯一可选中的详情按钮。
40 title = row.locator('[role="gridcell"][data-surface$=":TITLE"]') if '/published_posts' in list_url else row.locator('[role="button"][aria-pressed]')
41 await expect(title).to_have_count(1)
42 await title.click()
43 if schedule:
44 await expect(row).to_contain_text(f'{schedule.month}月{schedule.day}日 {schedule:%H:%M}')
45 if '/published_posts' in list_url:
46 # 新版已发布列表进入成效详情,URL 的 content_id 为“复制帖子编号”对应原作品编号。
47 await page.wait_for_url('**/object_insights/**', timeout=30000)
48 # URL 先变化,旧列表可能仍保留多个菜单;先等成效正文挂载,再限定可见菜单。
49 await page.locator('[data-surface$="BizWebObjectinsightsHeaderActionDropdown"] [aria-haspopup="menu"]').wait_for(timeout=120000)
50 query = parse_qs(urlparse(page.url).query)
51 ids = query.get('content_id', [])
52 if len(ids) != 1 or not ids[0].isdigit() or query.get('asset_id') != parse_qs(urlparse(list_url).query).get('asset_id'):
53 raise RuntimeError('成效详情缺少唯一作品编号或 Page 不匹配;未删除')
54 actual_id = ids[0]
55 else:
56 # 旧详情面板以 aria-labelledby 关联三级标题,紧邻的 div 是原作品编号字段。
57 # 读取末尾数字而非中文“编号:”;标题、配文及行内播放量不能充当编号。
58 detail = page.locator('div[aria-labelledby]').filter(has=page.locator('[role="heading"][aria-level="3"] + div')).filter(visible=True)
59 if await detail.count():
60 await expect(detail).to_have_count(1, timeout=30000)
61 number = detail.locator('[role="heading"][aria-level="3"] + div')
62 await expect(number).to_have_count(1)
63 number_text = await number.inner_text()
64 else:
65 # 受控测试页没有完整详情容器;数字字段仍须独立、唯一,不能回退到标题或行文本。
66 number = page.get_by_text(re.compile(r'^编号:\d+$'))
67 await expect(number).to_have_count(1, timeout=30000)
68 number_text = await number.inner_text()
69 match = re.search(r'(\d+)$', number_text.strip())
70 if not match:
71 raise RuntimeError('详情编号字段未包含原作品 ID;未删除')
72 actual_id = match.group(1)
73 if content_id is not None and actual_id != content_id:
74 raise RuntimeError(f'原作品编号不匹配:期望 {content_id},页面 {actual_id};未删除')
75 return row, actual_id, is_reel
76
77
78 async def meta_post_action(account_file: Path, *, page_id: str, page_name: str,
79 content_id: str, expected_text: str, scheduled: bool = False,
80 delete: bool = False, proxy: str | None = None,
81 headless: bool = False) -> dict:
82 """按 Page、内容编号、配文三项核对;定时作品永久删除,已发布作品移至垃圾箱。"""
83 if not page_id.isdigit() or not content_id.isdigit() or not page_name.strip() or not expected_text.strip():
84 raise ValueError("需要数字 page-id/content-id、Page 名和用于核验的配文")
85 async with async_playwright() as playwright:
86 browser, context, page = await _open_business_page(playwright, account_file, proxy=proxy, headless=headless)
87 try:
88 state = "scheduled_posts" if scheduled else "published_posts"
89 list_url = f"https://business.facebook.com/latest/posts/{state}?asset_id={page_id}"
90 row, actual_id, is_reel = await open_meta_post(page, list_url=list_url, page_name=page_name,
91 expected_text=expected_text, content_id=content_id)
92 result = {"platform": "facebook-page", "page_id": page_id, "page_name": page_name,
93 "content_id": content_id, "expected_text": expected_text,
94 "status": "scheduled" if scheduled else "published"}
95 if delete:
96 # 已发布作品详情菜单有明确的删除业务 Action 标识;标题编号已核对,
97 # 不用“打开下拉菜单/删除帖子”等翻译,也不在全页查同名按钮。
98 if scheduled:
99 # 旧详情的动作菜单无独立 Action surface;限定带三级标题的详情面板,
100 # 排除有 aria-label 的原帖预览菜单。实测五项依次编辑、复制、改期、移草稿、删除。
101 detail = page.locator('div[aria-labelledby]').filter(has=page.locator('[role="heading"][aria-level="3"] + div')).filter(visible=True)
102 await expect(detail).to_have_count(1)
103 menu_button = detail.locator('[role="button"][aria-haspopup="menu"]:not([aria-label])')
104 await expect(menu_button).to_have_count(1)
105 await menu_button.click()
106 items = page.get_by_role('menu').get_by_role('menuitem')
107 count = await items.count()
108 if count not in (4, 5):
109 raise RuntimeError(f'定时详情操作菜单结构未识别:{count} 项,未删除')
110 # 删除始终是该菜单最后一项;菜单本地化或权限不同会少一个“移到草稿”。
111 await items.nth(count - 1).click()
112 else:
113 dropdown = page.locator('[data-surface$="BizWebObjectinsightsHeaderActionDropdown"] [aria-haspopup="menu"]')
114 await expect(dropdown).to_have_count(1)
115 await dropdown.click()
116 action = page.locator('[data-surface$="match_container:TofuObjectInsightsDeleteAction"] [role="menuitem"]')
117 await expect(action).to_have_count(1)
118 await action.click()
119 # 真实确认框有 dialog/aria-labelledby/tabindex=-1;旧实现误判为无 dialog。
120 # 详情面板不具备这组属性。确认框三项业务顺序为关闭、取消、主动作,
121 # 数量/范围任一变化都停止,不靠中文文案或任意全页最后按钮执行破坏性操作。
122 dialog = page.locator('[role="dialog"][aria-labelledby][tabindex="-1"]').filter(visible=True)
123 await expect(dialog).to_have_count(1)
124 actions = dialog.get_by_role('button')
125 await expect(actions).to_have_count(2)
126 await actions.nth(1).click()
127 await expect(dialog).to_have_count(0, timeout=30000)
128 await expect(row).to_have_count(0, timeout=45000)
129 if not scheduled:
130 # 成效详情删除后由平台导航回列表;等这次导航结束,避免刷新与它竞争而 ERR_ABORTED。
131 await page.wait_for_url('**/posts/published_posts**', wait_until='domcontentloaded', timeout=90000)
132 # 删除后重新请求服务器列表,避免仅依据前端乐观移除判定成功;只查询,不重删。
133 deadline = asyncio.get_running_loop().time() + 60
134 while True:
135 await page.goto(list_url, wait_until="domcontentloaded", timeout=90000)
136 # 无筛选列表有作品行或平台明确空态才算加载结束;搜索索引延迟不能证明已删除。
137 loaded = page.get_by_role('row').filter(has=page.locator('[role="button"][aria-pressed]')).or_(page.get_by_text('没有定时帖', exact=True))
138 try:
139 await expect(loaded).not_to_have_count(0, timeout=10000)
140 await expect(page.get_by_role('row').filter(has_text=expected_text)).to_have_count(0, timeout=10000)
141 except BrowserTimeoutError:
142 if asyncio.get_running_loop().time() >= deadline:
143 raise TimeoutError("已提交删除,但刷新后的列表尚未确认原作品消失;请先查询,勿重复删除")
144 else:
145 break
146 result["status"] = "deleted" if scheduled else "trashed"
147 result["checked_at"] = datetime.now(timezone.utc).isoformat()
148 await context.storage_state(path=str(account_file))
149 return result
150 except Exception:
151 # 保留发生异常时的真实页面,便于定位改版或结果未知,不重试远端删除。
152 directory = Path('.local/meta-errors') / uuid4().hex
153 directory.mkdir(parents=True, exist_ok=True)
154 (directory / 'page.txt').write_text(page.url + '\n' + await page.locator('body').inner_text(), encoding='utf-8')
155 await page.screenshot(path=str(directory / 'page.png'))
156 raise
157 finally:
158 await browser.close()
159
159 lines PYTHON