| 1 | """查询个人主页的原作品,并按核实的作品 ID 移至垃圾箱。""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import asyncio |
| 6 | import re |
| 7 | from datetime import datetime, timezone |
| 8 | from pathlib import Path |
| 9 | |
| 10 | from patchright.async_api import Page, async_playwright, expect |
| 11 | |
| 12 | from uploader.meta_uploader.facebook_uploader.main import _open_facebook_page |
| 13 | |
| 14 | |
| 15 | def facebook_post_id(url: str) -> str: |
| 16 | """只接受 Facebook 原作品链接,不把个人主页或外部网址当成删除对象。""" |
| 17 | from urllib.parse import parse_qs, urlparse |
| 18 | |
| 19 | parsed = urlparse(url) |
| 20 | if parsed.scheme != "https" or parsed.hostname not in {"www.facebook.com", "facebook.com"}: |
| 21 | raise ValueError("作品链接必须是 https://www.facebook.com/ 下的原作品") |
| 22 | match = re.fullmatch(r"/(?:reel|posts|videos)/(\d+|pfbid[A-Za-z0-9]+)/?", parsed.path) |
| 23 | if not match: |
| 24 | match = re.fullmatch(r"/[A-Za-z0-9._-]+/(?:posts|videos)/(\d+|pfbid[A-Za-z0-9]+)/?", parsed.path) |
| 25 | if match: |
| 26 | return match.group(1) |
| 27 | if parsed.path == "/permalink.php": |
| 28 | ids = parse_qs(parsed.query).get("story_fbid", []) |
| 29 | if len(ids) == 1 and re.fullmatch(r'\d+|pfbid[A-Za-z0-9]+', ids[0]): |
| 30 | return ids[0] |
| 31 | raise ValueError("无法从作品链接中读取明确的作品 ID") |
| 32 | |
| 33 | |
| 34 | async def find_facebook_post(page: Page, *, post_url: str, owner_id: str, expected_text: str): |
| 35 | """在当前登录用户的个人主页中,交叉核对正文、作者和作品链接。""" |
| 36 | post_id = facebook_post_id(post_url) |
| 37 | if not owner_id.isdigit() or not expected_text.strip(): |
| 38 | raise ValueError("需要数字 owner-id 和非空 expected-text 核验原作品") |
| 39 | # c_user 是本次浏览器登录主体;禁止用另一个账号对给定个人主页执行删除。 |
| 40 | cookies = await page.context.cookies("https://www.facebook.com/") |
| 41 | users = {cookie["value"] for cookie in cookies if cookie["name"] == "c_user"} |
| 42 | if users != {owner_id}: |
| 43 | raise RuntimeError("当前 Facebook 登录用户与 owner-id 不一致") |
| 44 | await page.goto(f"https://www.facebook.com/profile.php?id={owner_id}", wait_until="domcontentloaded", timeout=90000) |
| 45 | # article 是主页作品卡片,正文只用于缩小范围;真正身份还要核对作品 ID 和作者链接。 |
| 46 | articles = page.get_by_role("article").filter(has_text=expected_text) |
| 47 | deadline = asyncio.get_running_loop().time() + 45 |
| 48 | while asyncio.get_running_loop().time() < deadline: |
| 49 | matches = [] |
| 50 | for article in await articles.all(): |
| 51 | links = await article.locator("a[href]").evaluate_all("els => els.map(e => e.href)") |
| 52 | ids = set() |
| 53 | for link in links: |
| 54 | try: |
| 55 | ids.add(facebook_post_id(link)) |
| 56 | except ValueError: |
| 57 | continue |
| 58 | if post_id not in ids: |
| 59 | continue |
| 60 | from urllib.parse import parse_qs, urlparse |
| 61 | authors = [link for link in links if urlparse(link).path == "/profile.php" |
| 62 | and parse_qs(urlparse(link).query).get("id") == [owner_id]] |
| 63 | if not authors: |
| 64 | raise RuntimeError("原作品 ID 匹配,但作者身份未核实") |
| 65 | matches.append(article) |
| 66 | if len(matches) > 1: |
| 67 | raise RuntimeError("主页中出现多个相同作品 ID,停止操作") |
| 68 | if matches: |
| 69 | return matches[0] |
| 70 | # 只向下浏览现有主页,既不重发,也不把未找到解释为已删除。 |
| 71 | await page.mouse.wheel(0, 650) |
| 72 | await page.wait_for_timeout(1000) |
| 73 | raise RuntimeError("未在个人主页找到正文、作者及 ID 均匹配的原作品;未执行删除") |
| 74 | |
| 75 | |
| 76 | async def find_trashed_facebook_post(page: Page, *, post_url: str, owner_id: str, expected_text: str): |
| 77 | """从垃圾箱原记录的查看链接核对作品,不用标题猜测身份。""" |
| 78 | post_id = facebook_post_id(post_url) |
| 79 | # 此地址来自个人主页“动态记录 → 垃圾箱”的实际导航,category_key 明确限定垃圾箱。 |
| 80 | await page.goto(f"https://www.facebook.com/{owner_id}/allactivity?activity_history=false&category_key=TRASH&manage_mode=true&should_load_landing_page=false", |
| 81 | wait_until="domcontentloaded", timeout=90000) |
| 82 | # 查看链接保留原作品 ID;最近的含“更多选项”按钮的祖先就是单条活动记录。 |
| 83 | link = page.get_by_role('link', name='查看', exact=True).locator(f'xpath=self::a[contains(@href,"/{post_id}/") or contains(@href,"story_fbid={post_id}")]') |
| 84 | await expect(link).to_have_count(1, timeout=30000) |
| 85 | if facebook_post_id(await link.get_attribute('href')) != post_id: |
| 86 | raise RuntimeError("垃圾箱查看链接的作品编号不一致") |
| 87 | row = link.locator('xpath=ancestor::div[.//a[contains(@href,"profile.php?id=")] and .//*[@role="button" and contains(@aria-label,"的更多选项")]][1]') |
| 88 | await expect(row).to_have_count(1) |
| 89 | await expect(row).to_contain_text(expected_text) |
| 90 | author = row.locator(f'a[href="https://www.facebook.com/profile.php?id={owner_id}"]') |
| 91 | await expect(author).to_have_count(1) |
| 92 | return row |
| 93 | |
| 94 | |
| 95 | async def trash_facebook_post(page: Page, article, *, post_url: str, owner_id: str, expected_text: str) -> str: |
| 96 | """按已实测的帖子菜单进入垃圾箱;提交一次,等待平台明确确认。""" |
| 97 | # 菜单按钮位于已核实的原作品卡片内,aria-label 包含“这篇帖子”,排除点赞/分享等操作。 |
| 98 | menu_button = article.get_by_role("button", name=re.compile(r"^可对.+的这篇帖子执行的操作$")) |
| 99 | await expect(menu_button).to_have_count(1) |
| 100 | await menu_button.click() |
| 101 | menu = page.get_by_role("menu") |
| 102 | await expect(menu).to_have_count(1) |
| 103 | await menu.get_by_role("menuitem").filter(has_text="移至垃圾箱").click() |
| 104 | # 同一确认弹窗中的“转移”才是最终提交动作,不点击全页同名按钮。 |
| 105 | dialog = page.get_by_role("dialog").filter(has_text="移至垃圾箱?") |
| 106 | await expect(dialog).to_have_count(1) |
| 107 | await dialog.get_by_role("button", name="转移", exact=True).click() |
| 108 | # 实测没有成功 toast。等待确认窗及原卡片消失,再到垃圾箱查原 ID,不能猜成功文案。 |
| 109 | await expect(dialog).to_have_count(0, timeout=30000) |
| 110 | await expect(article).to_have_count(0, timeout=30000) |
| 111 | await find_trashed_facebook_post(page, post_url=post_url, owner_id=owner_id, expected_text=expected_text) |
| 112 | return "trashed" |
| 113 | |
| 114 | |
| 115 | async def verify_facebook_deletion(page: Page, *, owner_id: str, post_url: str) -> None: |
| 116 | """永久删除后允许后台列表短暂延迟,只轮询查询,不重复提交删除。""" |
| 117 | post_id = facebook_post_id(post_url) |
| 118 | deadline = asyncio.get_running_loop().time() + 90 |
| 119 | while asyncio.get_running_loop().time() < deadline: |
| 120 | await page.goto(f"https://www.facebook.com/{owner_id}/allactivity?activity_history=false&category_key=TRASH&manage_mode=true&should_load_landing_page=false", |
| 121 | wait_until="domcontentloaded", timeout=90000) |
| 122 | await page.get_by_text("只有你能看到垃圾箱里的内容。", exact=True).wait_for(timeout=30000) |
| 123 | # 导航标题先出现,记录后到;必须等空列表文案或实际记录链接,不能把加载中当作已删除。 |
| 124 | empty = page.get_by_text("好冷清,一片落叶飘过~", exact=True) |
| 125 | records = page.get_by_role("link", name="查看", exact=True) |
| 126 | for _ in range(30): |
| 127 | if await empty.is_visible() or await records.count(): |
| 128 | break |
| 129 | await page.wait_for_timeout(500) |
| 130 | else: |
| 131 | raise RuntimeError("垃圾箱记录未加载,无法核实永久删除结果;请查询原作品,不要重复删除") |
| 132 | ids = set() |
| 133 | for link in await records.evaluate_all("es => es.map(e => e.href)"): |
| 134 | try: |
| 135 | ids.add(facebook_post_id(link)) |
| 136 | except ValueError: |
| 137 | continue |
| 138 | if post_id not in ids: |
| 139 | return |
| 140 | await page.wait_for_timeout(3000) |
| 141 | raise TimeoutError("永久删除已提交,但垃圾箱仍有原 ID;结果待核实,禁止自动重试删除") |
| 142 | |
| 143 | |
| 144 | async def facebook_post_action(account_file: Path, *, post_url: str, owner_id: str, |
| 145 | expected_text: str, delete: bool = False, |
| 146 | permanent: bool = False, from_trash: bool = False, deleted: bool = False, |
| 147 | proxy: str | None = None, headless: bool = False) -> dict: |
| 148 | """CLI 的原作品查询/删除入口;只有明确的平台反馈才返回成功。""" |
| 149 | facebook_post_id(post_url) |
| 150 | async with async_playwright() as playwright: |
| 151 | browser, context, page = await _open_facebook_page(playwright, account_file, proxy=proxy, headless=headless) |
| 152 | try: |
| 153 | cookies = await context.cookies("https://www.facebook.com/") |
| 154 | if {c["value"] for c in cookies if c["name"] == "c_user"} != {owner_id}: |
| 155 | raise RuntimeError("当前 Facebook 登录用户与 owner-id 不一致") |
| 156 | if not owner_id.isdigit() or not expected_text.strip(): |
| 157 | raise ValueError("owner-id 必须是数字,expected-text 不能为空") |
| 158 | if deleted: |
| 159 | if delete: |
| 160 | raise ValueError("核实永久删除结果不能同时执行删除") |
| 161 | await verify_facebook_deletion(page, owner_id=owner_id, post_url=post_url) |
| 162 | elif from_trash: |
| 163 | article = await find_trashed_facebook_post(page, post_url=post_url, owner_id=owner_id, expected_text=expected_text) |
| 164 | else: |
| 165 | article = await find_facebook_post(page, post_url=post_url, owner_id=owner_id, expected_text=expected_text) |
| 166 | result = {"platform": "facebook", "owner_id": owner_id, |
| 167 | "post_id": facebook_post_id(post_url), "post_url": post_url, |
| 168 | "expected_text": expected_text, "status": "absent_from_trash" if deleted else "trashed" if from_trash else "found"} |
| 169 | if delete: |
| 170 | if not from_trash: |
| 171 | result["status"] = await trash_facebook_post(page, article, post_url=post_url, owner_id=owner_id, expected_text=expected_text) |
| 172 | if permanent: |
| 173 | row = await find_trashed_facebook_post(page, post_url=post_url, owner_id=owner_id, expected_text=expected_text) |
| 174 | # 垃圾箱单条记录的菜单与批量删除相隔离,禁止操作“全部”复选框。 |
| 175 | await row.get_by_role("button", name=re.compile(r"^针对.+的更多选项$")).click() |
| 176 | await page.get_by_role("menu").get_by_role("menuitem", name="删除", exact=True).click() |
| 177 | dialog = page.get_by_role("dialog").filter(has_text="确定删除?") |
| 178 | await expect(dialog).to_contain_text("你删除的内容将无法恢复。") |
| 179 | await dialog.get_by_role("button", name="删除", exact=True).click() |
| 180 | await expect(dialog).to_have_count(0, timeout=30000) |
| 181 | await expect(row).to_have_count(0, timeout=30000) |
| 182 | await verify_facebook_deletion(page, owner_id=owner_id, post_url=post_url) |
| 183 | result["status"] = "deleted" |
| 184 | result["checked_at"] = datetime.now(timezone.utc).isoformat() |
| 185 | await context.storage_state(path=str(account_file)) |
| 186 | return result |
| 187 | finally: |
| 188 | await browser.close() |
| 189 |