返回 Social Auto Upload
1 """通过 Patchright 在 Facebook 个人主页发布视频。
2
3 这里使用 Facebook 首页的个人/主页发帖 composer。Meta Business Suite 的 Page
4 发布和定时发布需要另一套已登录主体与权限,不能把它们和个人主页流程混用。
5 """
6
7 from __future__ import annotations
8
9 import asyncio
10 import os
11 import re
12 from pathlib import Path
13
14 from patchright.async_api import Page, Playwright, async_playwright, expect
15
16 from utils.log import facebook_logger
17
18
19 FACEBOOK_HOME_URL = "https://www.facebook.com/"
20 # 代理只从显式 CLI 参数或用户自行设置的环境变量读取;未设置时直连。
21 FACEBOOK_PROXY = os.environ.get("SAU_FACEBOOK_PROXY")
22 FACEBOOK_LOGIN_INPUT = 'input[name="email"]'
23 # 首页发帖附件同时接受图片与视频,头像/封面控件不具备这组 MIME 类型。
24 FACEBOOK_MEDIA_INPUT = 'input[type="file"][accept*="image/"][accept*="video/"]'
25
26
27 def _proxy_options(proxy: str | None) -> dict[str, str] | None:
28 """未传参数时使用显式环境配置,否则直连;空字符串可覆盖环境配置并直连。"""
29 address = (FACEBOOK_PROXY if proxy is None else proxy) or ""
30 address = address.strip()
31 return {"server": address} if address else None
32
33
34 async def _is_logged_out(page: Page) -> bool:
35 """根据登录流程标记和首页发帖业务锚点判断会话是否有效。"""
36 current_url = page.url.lower()
37 # two_step_verification 是登录流程中的二次验证页,不能误判成已登录首页。
38 if any(
39 marker in current_url
40 for marker in ("/login", "checkpoint", "two_step_verification", "/authentication/")
41 ):
42 return True
43 email_input = page.locator(FACEBOOK_LOGIN_INPUT)
44 if await email_input.count() and await email_input.first.is_visible():
45 return True
46 # 发帖附件控件是首页 composer 已挂载的正向证据,空白页/登录中页面不能当作已登录。
47 return await page.locator(FACEBOOK_MEDIA_INPUT).count() != 1
48
49
50 async def _open_facebook_page(playwright: Playwright, account_file: Path, *, proxy: str | None, headless: bool):
51 """使用 storage state 打开 Facebook,并保留代理配置到浏览器进程。"""
52 launch_options = {
53 "channel": "chrome",
54 "headless": headless,
55 "proxy": _proxy_options(proxy),
56 }
57 browser = await playwright.chromium.launch(**launch_options)
58 try:
59 context = await browser.new_context(storage_state=str(account_file))
60 page = await context.new_page()
61 page.set_default_timeout(30_000)
62 await page.goto(FACEBOOK_HOME_URL, wait_until="domcontentloaded", timeout=90_000)
63 await page.locator("body").wait_for(state="visible", timeout=30_000)
64 return browser, context, page
65 except Exception:
66 # 导航或 storage state 失败时,浏览器已经属于本函数,必须在抛错前释放。
67 await browser.close()
68 raise
69
70
71 async def facebook_cookie_auth(account_file: str | Path, *, proxy: str | None = None) -> bool:
72 """检查保存的 Facebook storage state 是否仍能进入已登录首页。"""
73 account_file = Path(account_file)
74 if not account_file.is_file():
75 return False
76 async with async_playwright() as playwright:
77 browser, context, page = await _open_facebook_page(
78 playwright, account_file, proxy=proxy, headless=True
79 )
80 try:
81 return not await _is_logged_out(page)
82 finally:
83 await browser.close()
84
85
86 async def facebook_setup(
87 account_file: str | Path,
88 *,
89 handle: bool = False,
90 return_detail: bool = False,
91 headless: bool = False,
92 proxy: str | None = None,
93 timeout_seconds: int = 600,
94 ):
95 """校验登录态;登录命令用可见浏览器等待用户完成登录后保存状态。"""
96 account_file = Path(account_file)
97 account_file.parent.mkdir(parents=True, exist_ok=True)
98 valid = await facebook_cookie_auth(account_file, proxy=proxy)
99 if valid:
100 result = {
101 "success": True,
102 "status": "cookie_valid",
103 "message": "Facebook 登录态有效",
104 "account_file": str(account_file),
105 }
106 return result if return_detail else True
107 if not handle:
108 result = {
109 "success": False,
110 "status": "cookie_invalid",
111 "message": "Facebook 登录态不存在或已失效",
112 "account_file": str(account_file),
113 }
114 return result if return_detail else False
115
116 async with async_playwright() as playwright:
117 browser = await playwright.chromium.launch(
118 channel="chrome", headless=headless, proxy=_proxy_options(proxy)
119 )
120 try:
121 context = await browser.new_context(
122 storage_state=str(account_file) if account_file.is_file() else None
123 )
124 page = await context.new_page()
125 page.set_default_timeout(30_000)
126 await page.goto(FACEBOOK_HOME_URL, wait_until="domcontentloaded", timeout=90_000)
127 facebook_logger.info("请在打开的 Facebook 浏览器中完成登录,程序会自动保存登录态")
128 deadline = asyncio.get_running_loop().time() + timeout_seconds
129 while asyncio.get_running_loop().time() < deadline:
130 if not await _is_logged_out(page):
131 await context.storage_state(path=str(account_file))
132 result = {
133 "success": True,
134 "status": "logged_in",
135 "message": "Facebook 登录成功,登录态已保存",
136 "account_file": str(account_file),
137 "current_url": page.url,
138 }
139 return result if return_detail else True
140 await page.wait_for_timeout(1000)
141 result = {
142 "success": False,
143 "status": "timeout",
144 "message": "等待 Facebook 登录超时,未保存登录态",
145 "account_file": str(account_file),
146 "current_url": page.url,
147 }
148 return result if return_detail else False
149 finally:
150 await browser.close()
151
152
153 class FacebookPost:
154 """通过个人主页 composer 发布一个视频或一组图片。"""
155
156 def __init__(
157 self,
158 title: str,
159 file_path: str | Path | list[Path],
160 description: str,
161 tags: list[str],
162 account_file: str | Path,
163 proxy: str | None = None,
164 headless: bool = True,
165 ):
166 self.title = title.strip()
167 self.files = [Path(item) for item in file_path] if isinstance(file_path, list) else [Path(file_path)]
168 self.file_path = self.files[0] if self.files else Path()
169 self.description = description.strip()
170 self.tags = [tag.strip().lstrip("#") for tag in tags if tag.strip().lstrip("#")]
171 self.account_file = Path(account_file)
172 self.proxy = proxy
173 self.headless = headless
174
175 def _caption(self) -> str:
176 """Facebook 首页没有独立视频标题字段,按项目统一约定合并为正文。"""
177 parts = [part for part in (self.title, self.description) if part]
178 if self.tags:
179 parts.append(" ".join(f"#{tag}" for tag in self.tags))
180 return "\n\n".join(parts)
181
182 async def _find_caption_editor(self, page: Page):
183 # 外层 aria-modal dialog 属于本次发帖表单,排除首页评论框及隐藏模板。
184 editor = page.locator('[role="dialog"][aria-modal="true"] [contenteditable="true"][role="textbox"]')
185 await expect(editor).to_have_count(1)
186 return editor
187
188 async def _find_publish_button(self, page: Page):
189 # 发帖 form 的最后一个业务动作是提交,前面的按钮分别为编辑器关闭、隐私及附件编辑。
190 # 图文/视频实际 DOM 均已检查;嵌套 dialog 实际是编辑器标题栏,不能把它当提交区域。
191 form = page.locator('[role="dialog"][aria-modal="true"] form')
192 await expect(form).to_have_count(1)
193 button = form.get_by_role('button').last
194 await expect(button).to_be_visible()
195 return button
196
197 async def _wait_until_publishable(self, page: Page) -> None:
198 deadline = asyncio.get_running_loop().time() + 180
199 while asyncio.get_running_loop().time() < deadline:
200 error = page.locator('[role="dialog"] [role="alert"]')
201 if await error.count() and await error.first.is_visible():
202 message = (await error.first.inner_text()).strip()
203 if message:
204 raise RuntimeError(f"Facebook 视频上传失败: {message}")
205 try:
206 publish_button = await self._find_publish_button(page)
207 if await publish_button.is_enabled():
208 return
209 except RuntimeError as exc:
210 if "未找到 Facebook 发布按钮" not in str(exc):
211 raise
212 await page.wait_for_timeout(1000)
213 raise TimeoutError("Facebook 视频上传或处理超时,发布按钮未就绪")
214
215 async def _publish_and_verify(self, page: Page) -> None:
216 publish_button = await self._find_publish_button(page)
217 # 已实测成功提示是完整句子,不能把动态中任意“已发布”文案当成本次成功。
218 success_pattern = re.compile(r"^(?:你的帖子已成功分享给.+|你的帖子已发布|Your post has been published[.!]?)$", re.I)
219 success_text = page.get_by_text(success_pattern)
220 for index in range(await success_text.count()):
221 if await success_text.nth(index).is_visible():
222 raise RuntimeError("提交前已存在发布成功提示,无法区分本次结果;未提交")
223 await publish_button.click()
224 deadline = asyncio.get_running_loop().time() + 90
225 while asyncio.get_running_loop().time() < deadline:
226 # 只接受状态提示或成功文案;弹窗消失本身不足以证明服务端已受理。
227 success_text = page.get_by_text(success_pattern)
228 if await success_text.count():
229 for index in range(await success_text.count()):
230 if await success_text.nth(index).is_visible():
231 return
232 await page.wait_for_timeout(1000)
233 raise TimeoutError("已点击 Facebook 发布,但未观察到明确的发布成功状态")
234
235 async def upload(self, playwright: Playwright) -> None:
236 if not self.files:
237 raise ValueError("Facebook 发布素材不能为空")
238 for file in self.files:
239 if not file.is_file():
240 raise FileNotFoundError(f"Facebook 素材文件不存在: {file}")
241 if not self.title:
242 raise ValueError("Facebook 视频标题不能为空")
243 if not self.account_file.is_file():
244 raise RuntimeError(f"Facebook 登录态文件不存在: {self.account_file}")
245
246 browser, context, page = await _open_facebook_page(
247 playwright, self.account_file, proxy=self.proxy, headless=self.headless
248 )
249 try:
250 if await _is_logged_out(page):
251 raise RuntimeError("Facebook 登录态失效,请先执行 sau facebook login")
252
253 # 已实测首页的唯一混合影音 input;按 accept 同时支持图片和视频限定,排除头像等控件。
254 file_input = page.locator(FACEBOOK_MEDIA_INPUT)
255 if await file_input.count() != 1:
256 raise RuntimeError("首页发帖影音上传控件不唯一,未上传")
257 await file_input.set_input_files([str(file) for file in self.files])
258
259 # 选择素材后 composer 异步挂载;不能在同一轮立即检查 count 就判输入框不存在。
260 await page.locator('[role="dialog"] [contenteditable="true"][role="textbox"]:visible').wait_for(timeout=30000)
261 editor = await self._find_caption_editor(page)
262 caption = self._caption()
263 await editor.click()
264 await editor.fill(caption)
265 if (await editor.inner_text()).strip() != caption:
266 raise RuntimeError("Facebook 正文输入框未读回预期内容")
267
268 await self._wait_until_publishable(page)
269 await self._publish_and_verify(page)
270 await context.storage_state(path=str(self.account_file))
271 finally:
272 await browser.close()
273
274 async def main(self) -> None:
275 async with async_playwright() as playwright:
276 await self.upload(playwright)
277
278
279 # 保留原视频调用方的类名;视频和图文实际共用同一发帖表单,无额外包装层。
280 FacebookVideo = FacebookPost
281
281 lines PYTHON