返回 Social Auto Upload
1 """通过 Meta Business Suite 发布 Facebook Page 内容。"""
2
3 from __future__ import annotations
4
5 import asyncio
6 import json
7 import os
8 import re
9 from datetime import datetime
10 from pathlib import Path
11 from urllib.parse import parse_qs, urlparse
12 from uuid import uuid4
13
14 from patchright.async_api import Page, Playwright, async_playwright, expect, TimeoutError as BrowserTimeoutError
15
16 from uploader.base_video import BaseVideoUploader
17
18
19 META_BUSINESS_URL = "https://business.facebook.com/latest/composer/"
20 META_PLATFORMS = {"facebook-page"}
21 # 未配置环境变量或 --proxy 时使用系统直连。
22 FACEBOOK_PAGE_PROXY = os.environ.get("SAU_FACEBOOK_PAGE_PROXY")
23
24
25 def meta_account_file(platform: str, account_name: str) -> Path:
26 if platform not in META_PLATFORMS:
27 raise ValueError(f"不支持的 Meta Business 平台: {platform}")
28 return Path("cookies") / f"{platform}_{account_name}.json"
29
30
31 def _proxy_options(proxy: str | None) -> dict[str, str] | None:
32 address = (FACEBOOK_PAGE_PROXY if proxy is None else proxy) or ""
33 address = address.strip()
34 return {"server": address} if address else None
35
36
37 async def _open_business_page(
38 playwright: Playwright,
39 account_file: Path,
40 *,
41 proxy: str | None,
42 headless: bool,
43 ):
44 browser = await playwright.chromium.launch(
45 channel="chrome", headless=headless, proxy=_proxy_options(proxy)
46 )
47 try:
48 context = await browser.new_context(storage_state=str(account_file))
49 page = await context.new_page()
50 page.set_default_timeout(30_000)
51 await page.goto(META_BUSINESS_URL, wait_until="domcontentloaded", timeout=120_000)
52 await page.locator("body").wait_for(state="visible", timeout=30_000)
53 return browser, context, page
54 except Exception:
55 await browser.close()
56 raise
57
58
59 async def dismiss_guidance_cards(page: Page) -> None:
60 """关闭带明确 GeoGuidanceCard 业务标识的说明卡,不处理未知弹窗。"""
61 # 中英日卡片中关闭按钮无 aria-label,了解更多带 aria-label;不用 Close/关闭/閉じる 文案。
62 close_buttons = page.locator('[data-surface$="lib:GeoGuidanceCard"] [role="button"]:not([aria-label]):visible')
63 # data-surface 可能同时出现在包裹节点和日志节点上;直接选其后代按钮,由 CSS 去重。
64 for close in await close_buttons.all():
65 await close.click()
66 await expect(close).to_be_hidden()
67
68
69 async def _is_business_logged_out(page: Page) -> bool:
70 url = page.url.lower()
71 if "/login" in url or "checkpoint" in url or "two_step_verification" in url:
72 return True
73 if await page.locator('input[name="email"]').count() and await page.locator('input[name="email"]').first.is_visible():
74 return True
75 # 导航 href 与页面业务 surface 均独立于显示语言;空白页不能作为已登录证据。
76 navigation = page.locator('a[href*="/latest/home"]')
77 return not await navigation.filter(visible=True).count()
78
79
80
81 async def meta_cookie_auth(account_file: str | Path, *, proxy: str | None = None) -> bool:
82 account_file = Path(account_file)
83 if not account_file.is_file():
84 return False
85 async with async_playwright() as playwright:
86 browser, context, page = await _open_business_page(
87 playwright, account_file, proxy=proxy, headless=True
88 )
89 try:
90 return not await _is_business_logged_out(page)
91 finally:
92 await browser.close()
93
94
95 async def meta_setup(
96 account_file: str | Path,
97 *,
98 handle: bool = False,
99 proxy: str | None = None,
100 headless: bool = False,
101 return_detail: bool = False,
102 ):
103 account_file = Path(account_file)
104 account_file.parent.mkdir(parents=True, exist_ok=True)
105 if await meta_cookie_auth(account_file, proxy=proxy):
106 result = {"success": True, "status": "cookie_valid", "account_file": str(account_file)}
107 return result if return_detail else True
108 if not handle:
109 result = {"success": False, "status": "cookie_invalid", "account_file": str(account_file)}
110 return result if return_detail else False
111
112 async with async_playwright() as playwright:
113 browser = await playwright.chromium.launch(
114 channel="chrome", headless=headless, proxy=_proxy_options(proxy)
115 )
116 try:
117 # 已有 Facebook 登录态可作为 Business Suite 的初始 Cookie,避免重复登录。
118 source = account_file
119 context = await browser.new_context(storage_state=str(source) if source.is_file() else None)
120 page = await context.new_page()
121 page.set_default_timeout(30_000)
122 await page.goto(META_BUSINESS_URL, wait_until="domcontentloaded", timeout=120_000)
123 deadline = asyncio.get_running_loop().time() + 600
124 while asyncio.get_running_loop().time() < deadline:
125 if not await _is_business_logged_out(page):
126 await context.storage_state(path=str(account_file))
127 result = {
128 "success": True,
129 "status": "logged_in",
130 "account_file": str(account_file),
131 "current_url": page.url,
132 }
133 return result if return_detail else True
134 await page.wait_for_timeout(1000)
135 result = {"success": False, "status": "timeout", "account_file": str(account_file)}
136 return result if return_detail else False
137 finally:
138 await browser.close()
139
140
141 class MetaBusinessUploader(BaseVideoUploader):
142 """Business Suite 中的 Facebook Page 视频和图文发布器。"""
143
144 def __init__(
145 self,
146 platform: str,
147 account_file: str | Path,
148 *,
149 title: str,
150 description: str = "",
151 tags: list[str] | None = None,
152 video_file: str | Path | None = None,
153 image_files: list[str | Path] | None = None,
154 schedule: datetime | int = 0,
155 page_name: str | None = None,
156 proxy: str | None = None,
157 headless: bool = False,
158 result_file: str | Path | None = None,
159 ):
160 if platform not in META_PLATFORMS:
161 raise ValueError(f"不支持的 Meta Business 平台: {platform}")
162 if not title.strip():
163 raise ValueError("标题不能为空")
164 if bool(video_file) == bool(image_files):
165 raise ValueError("必须且只能传入视频或图片文件")
166 self.platform = platform
167 self.account_file = Path(account_file)
168 self.title = title.strip()
169 self.description = description.strip()
170 self.tags = [tag.strip().lstrip("#") for tag in (tags or []) if tag.strip().lstrip("#")]
171 self.video_file = Path(video_file) if video_file else None
172 self.image_files = [Path(item) for item in (image_files or [])]
173 self.schedule = self.validate_publish_date(schedule)
174 self.page_name = page_name.strip() if page_name else None
175 self.proxy = proxy
176 self.headless = headless
177 self.result_file = Path(result_file) if result_file else Path('.local/meta-results') / f'{uuid4().hex}.json'
178 self.result = {"platform": platform, "title": self.title, "status": "not_submitted"}
179
180 def _caption(self) -> str:
181 parts = [self.title, self.description] if self.description else [self.title]
182 if self.tags:
183 parts.append(" ".join(f"#{tag}" for tag in self.tags))
184 return "\n\n".join(parts)
185
186 async def _select_publish_location(self, page: Page) -> None:
187 # 发布位置的可访问名称区别于正文和 CTA 的 combobox,不依赖全页顺序。
188 # 发布主体选择器带 Facebook 品牌徽标;CTA 下拉框和正文均没有该徽标。
189 # 中英文实际页面均保留此品牌 alt,避免依赖“发布位置/Post to”的翻译。
190 combo = page.locator('[data-surface$="bizweb_create_post:left_panel"] [role="combobox"][aria-haspopup="listbox"]').filter(has=page.locator('img[alt="Facebook"]'))
191 await combo.wait_for(state="visible")
192 if self.page_name and self.page_name not in await combo.inner_text():
193 await combo.click()
194 option = page.get_by_role("option", name=self.page_name, exact=True)
195 if not await option.count():
196 raise RuntimeError(f"Business Suite 未找到指定发布主体: {self.page_name}")
197 await option.click()
198 if self.page_name:
199 await expect(combo).to_contain_text(self.page_name)
200 else:
201 self.page_name = (await combo.inner_text()).replace('\u200b', '').strip()
202 assets = parse_qs(urlparse(page.url).query).get('asset_id', [])
203 if len(assets) != 1 or not assets[0].isdigit():
204 raise RuntimeError("无法核实当前 Page asset_id,未提交")
205 self.result.update(page_id=assets[0], page_name=self.page_name, expected_text=self.title)
206
207 async def _upload_files(self, page: Page) -> None:
208 # 页面可能保留隐藏的响应式布局;按钮语义及 visible 限定当前实际上传入口。
209 # 空媒体区的业务顺序为本地影音上传、可选 AI 生成;中英文实测分别有 1/2 个入口。
210 # 仅接受空区这两种结构,上传后生成的编辑/移除动作不能混入;不按翻译或图标路径匹配。
211 media = page.locator('[data-surface$="lib:bizweb_create_post:media"]')
212 await expect(media.locator('img')).to_have_count(0)
213 entries = media.get_by_role('button')
214 if await entries.count() not in (1, 2):
215 raise RuntimeError('空媒体区结构未识别,未上传')
216 trigger = entries.nth(0)
217 files = [str(self.video_file)] if self.video_file else [str(path) for path in self.image_files]
218 async with page.expect_file_chooser() as chooser_info:
219 await trigger.click()
220 await (await chooser_info.value).set_files(files)
221 # 视频在新版 Business Suite 会进入“创建 Reels”向导,不渲染 video 标签;
222 # 图片则留在原 composer。两种状态都必须等到文件名或向导业务标题出现。
223 if self.video_file:
224 await page.get_by_text(self.video_file.name, exact=True).wait_for(state="visible", timeout=180_000)
225 # 新版 Reel 向导有独立业务 surface;不依赖 Create reel/创建 Reels 标题。
226 await page.locator('[data-surface$="lib:bizweb_create_reel"]').wait_for()
227 await dismiss_guidance_cards(page)
228 await page.get_by_text('100%', exact=True).wait_for(state='visible', timeout=180000)
229 else:
230 # 上传后媒体区生成服务端预览及像素尺寸;不以中文“移除照片”或正文框代表上传完成。
231 await expect(media.locator('img')).to_have_count(len(files), timeout=180000)
232 await expect(media.get_by_text(re.compile(r"^\d+ x \d+$")).filter(visible=True)).to_have_count(len(files), timeout=180000)
233
234 async def _fill_caption(self, page: Page) -> None:
235 # Reel 标题为 left_panel 中唯一普通 text input;关键词输入另有 combobox 角色。
236 reels_title = page.locator('[data-surface$="bizweb_create_reel:left_panel"] input[type="text"]:not([role]):visible')
237 separate_title = self.video_file and await reels_title.count() and await reels_title.is_visible()
238 if separate_title:
239 await reels_title.fill(self.title)
240 # 实测同名隐藏 textbox 与可见 combobox 并存;只匹配当前向导可见正文,防止误填旧布局。
241 # 当前可见 contenteditable 是正文;隐藏 textbox 属于旧布局,角色会随图文/Reel 改变。
242 editor = page.locator('[contenteditable="true"]:visible')
243 await expect(editor).to_have_count(1)
244 await editor.wait_for(state="visible", timeout=30_000)
245 caption = self.description if separate_title else self._caption()
246 if self.tags and separate_title:
247 caption = f"{caption}\n\n{' '.join(f'#{tag}' for tag in self.tags)}" if caption else " ".join(f"#{tag}" for tag in self.tags)
248 if not caption and not self.video_file:
249 caption = self._caption()
250 await editor.fill(caption)
251 if (await editor.inner_text()).strip() != caption:
252 raise RuntimeError("Business Suite 正文未读回预期内容")
253
254 async def _advance_reels(self, page: Page) -> None:
255 if not self.video_file:
256 return
257 root = page.locator('[data-surface$="lib:bizweb_create_reel"]')
258 # 向导的三个步骤有 aria-labelledby,当前步骤有 aria-current;缩略图切换没有。
259 steps = root.locator('[role="button"][aria-labelledby]:not([aria-haspopup])')
260 await expect(steps).to_have_count(3)
261 # 两次下一步都来自 footer,不与缩略图的上/下一张混选;带 aria-label 的是反馈入口。
262 # 已实测创建、编辑、分享三阶段底栏均为返回/取消 + 主动作这两个业务按钮。
263 for index in (0, 1):
264 await expect(steps.nth(index)).to_have_attribute('aria-current', 'step')
265 actions = page.locator('[data-surface$="bizweb_create_reel:footer"] [role="button"]:not([aria-label])')
266 await expect(actions).to_have_count(2)
267 await expect(actions.nth(1)).to_be_enabled(timeout=180000)
268 await actions.nth(1).click()
269 await expect(steps.nth(index + 1)).to_have_attribute('aria-current', 'step')
270 # 快拍开关与当前 Page 的 Facebook 徽标属于同一单开关业务组;其余开关没有品牌图片。
271 story = page.locator('[data-surface$="bizweb_create_reel:left_panel"] input[role="switch"]').locator(
272 'xpath=self::input[ancestor::div[.//img[@alt="Facebook"] and count(.//input[@role="switch"])=1]]')
273 await expect(story).to_have_count(1)
274 if await story.is_checked():
275 await story.click()
276 # Once 是平台真实选项值,只关闭本条快拍分享;Always 会改变后续默认设置。
277 dialog = page.get_by_role('dialog').filter(has=page.locator('input[type="radio"][value="Once"]'))
278 await expect(dialog).to_have_count(1)
279 await dialog.locator('input[value="Once"]').check()
280 actions = dialog.get_by_role('button')
281 # 实测确认框三项为关闭、取消、确认;严格核对数量后使用该业务顺序。
282 await expect(actions).to_have_count(3)
283 await actions.nth(2).click()
284 await expect(dialog).to_have_count(0)
285 await expect(story).not_to_be_checked()
286
287 async def _fill_schedule(self, page: Page) -> None:
288 if not self.schedule:
289 return
290 # 此表单按浏览器本地时区解释时间,当前真实验证为 Asia/Shanghai。
291 zone = await page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone")
292 if zone != "Asia/Shanghai" or self.schedule.tzinfo is not None:
293 raise ValueError("当前 Meta 定时要求 Asia/Shanghai 浏览器及不带时区的北京时间输入")
294 if self.video_file:
295 region = page.locator('[data-surface$="bizweb_create_reel:left_panel"]')
296 # 分享阶段的三种发布模式是立即、定时、草稿;其 aria-pressed 表示模式,非提交。
297 modes = region.locator('[role="button"][aria-pressed]').locator('xpath=self::*[not(ancestor::*[@role="grid"])]')
298 await expect(modes).to_have_count(3)
299 await modes.nth(1).click()
300 await expect(modes.nth(1)).to_have_attribute('aria-pressed', 'true')
301 else:
302 region = page.locator('[data-surface$="lib:bizweb_create_post:publishing_options"]')
303 await region.locator('input[role="switch"]').check()
304 # 日期是定时区唯一有 placeholder 的普通 input;小时/分钟靠语义数值范围区分。
305 date_input = region.locator('input[placeholder]:not([role])')
306 await expect(date_input).to_have_count(1)
307 await date_input.click()
308 grid = region.locator('[role="grid"][aria-labelledby]')
309 await expect(grid).to_have_count(1)
310 # 日历 aria-labelledby 实测含月、年,前缀 js_* 随会话变化,只解析其日期后缀。
311 month_id = await grid.get_attribute('aria-labelledby')
312 match = re.search(r'-(\d{1,2})-(\d{4})$', month_id or '')
313 if not match:
314 raise RuntimeError('无法读取日历的月份/年份,未提交')
315 month, year = map(int, match.groups())
316 month_delta = (self.schedule.year - year) * 12 + self.schedule.month - month
317 if abs(month_delta) > 12:
318 raise ValueError('定时日期超出已验证日历范围')
319 # 日历非 grid 内的两个按钮分别为上一月/下一月;日按钮属于 gridcell,排除它们。
320 calendar = grid.locator('xpath=ancestor::div[.//*[@role="button"][@aria-busy]][1]')
321 navigation = calendar.locator('[role="button"][aria-busy]')
322 await expect(navigation).to_have_count(2)
323 for _ in range(abs(month_delta)):
324 await navigation.nth(1 if month_delta > 0 else 0).click()
325 await expect(grid).to_have_attribute('aria-labelledby', re.compile(fr'-{self.schedule.month}-{self.schedule.year}$'))
326 # 已核对日历年月后按日期数字选择,避免依赖 aria-label 的星期/月名翻译。
327 day = grid.get_by_role('button').filter(has_text=re.compile(fr'^{self.schedule.day}$'))
328 await expect(day).to_have_count(1)
329 if await day.get_attribute('aria-disabled') == 'true':
330 raise ValueError('平台日历不允许选定日期,未提交')
331 await day.click()
332 hour = region.locator('[role="spinbutton"][aria-valuemax="23"], [role="spinbutton"][aria-valuemax="12"]')
333 await expect(hour).to_have_count(1)
334 twelve_hour = await hour.get_attribute('aria-valuemax') == '12'
335 value_hour = (self.schedule.hour % 12 or 12) if twelve_hour else self.schedule.hour
336 for control, value in ((hour, value_hour), (region.locator('[role="spinbutton"][aria-valuemax="59"]'), self.schedule.minute)):
337 await control.click()
338 for digit in f'{value:02d}':
339 await control.press(digit)
340 await control.press('Tab')
341 await expect(control).to_have_attribute('aria-valuenow', str(value))
342 if twelve_hour:
343 # AM/PM 的真实数值是 0/1;按键切换后读回,拒绝只填小时造成 12 小时偏差。
344 period = region.locator('[role="spinbutton"][aria-valuemax="1"]')
345 target = str(int(self.schedule.hour >= 12))
346 if await period.get_attribute('aria-valuenow') != target:
347 await period.press('ArrowUp')
348 await expect(period).to_have_attribute('aria-valuenow', target)
349 # 日期控件在中英日页面实测读回均包含年月日数字;允许分隔符本地化,不猜月份名称。
350 parts = [int(part) for part in re.findall(r'\d+', await date_input.input_value())]
351 if parts != [self.schedule.year, self.schedule.month, self.schedule.day]:
352 raise RuntimeError(f'日期未读回请求值:{await date_input.input_value()}')
353
354 async def _publish(self, page: Page) -> None:
355 # 图文底栏的业务动作固定为取消、存草稿、最终提交;限定 footer 并严格核对三项,
356 # 只在已观察的布局中采用此业务顺序,布局变化时停止,禁止用全页同名按钮或猜测翻译。
357 if not self.video_file:
358 actions = page.locator('[data-surface$="lib:bizweb_create_post:footer"] [role="button"]')
359 await expect(actions).to_have_count(3)
360 button = actions.nth(2)
361 else:
362 # 分享阶段仍为返回 + 最终主动作,不能选择顶部 Share 步骤导航。
363 actions = page.locator('[data-surface$="bizweb_create_reel:footer"] [role="button"]:not([aria-label])')
364 await expect(actions).to_have_count(2)
365 button = actions.nth(1)
366 await expect(button).to_be_enabled()
367 self.result['status'] = 'submission_unknown'
368 self.result_file.parent.mkdir(parents=True, exist_ok=True)
369 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
370 # 只捕获本次点击触发的创建作品响应;上传素材 ID 和广告建议中的 story ID 都不能代替内容编号。
371 async with page.expect_response(lambda response: '/api/graphql' in response.url and
372 parse_qs(response.request.post_data or '').get('fb_api_req_friendly_name') == ['BusinessComposerStoryCreationMutation'], timeout=90000) as response_info:
373 await button.click()
374 payload = await (await response_info.value).json()
375 if payload.get('errors'):
376 raise RuntimeError('平台创建作品响应包含错误;请查原记录,勿重复提交')
377 creation = payload.get('data', {}).get('xfamily_content_create', {})
378 if any(creation.get('errors', {}).values()):
379 raise RuntimeError('平台返回作品创建错误;请查原记录,勿重复提交')
380 items = creation.get('items')
381 if isinstance(items, dict):
382 items = [items]
383 if not isinstance(items, list) or len(items) != 1:
384 raise RuntimeError('已提交但未取得唯一内容编号;结果待查询')
385 # 实测 Reels 响应的 pending_publish_content_id 为空,需在成功确认后查原作品详情。
386 pending_id = items[0].get('pending_publish_content_id')
387 if pending_id:
388 self.result['content_id'] = str(pending_id)
389 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
390 if self.video_file:
391 # 创建响应后页面仍执行后续发布步骤,不能立即导航走;实测完成框带本次标题、
392 # 作品预览及关闭/完成两个动作。标题是本次业务参数,非某种语言的成功文案。
393 completion = page.locator('[role="dialog"][aria-labelledby][tabindex="-1"]').filter(has_text=self.title)
394 await expect(completion).to_have_count(1, timeout=120000)
395 await expect(completion.get_by_role('heading')).to_have_count(1)
396 await expect(completion.get_by_role('button')).to_have_count(2)
397 # 完成框两个动作均是关闭/完成;点击最后一个代表平台已受理本次 Reel。
398 await completion.get_by_role('button').last.click()
399 await expect(completion).to_have_count(0)
400 if not self.schedule:
401 # Reel 创建响应实测可能没有 pending_publish_content_id,作品列表也可能在视频处理期间不展示。
402 # 完成弹窗和无错误的创建响应已经是“提交成功、正在处理”的业务证据;编号只用于后续核验/删除,不能阻断发布结果。
403 self.result['status'] = 'processing'
404 self.result['schedule'] = None
405 self.result['timezone'] = 'Asia/Shanghai'
406 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
407 return
408 # 创建响应明确受理后按 Page 和原作品编号查询;不依赖任何语言的成功提示。
409 # 定时作品必须读回排期;图文立即发布必须读回原作品;这两类结果不能只凭弹窗判断。
410 from uploader.meta_uploader.facebook_page_uploader.posts import open_meta_post
411 state = 'scheduled_posts' if self.schedule else 'published_posts'
412 list_url = f'https://business.facebook.com/latest/posts/{state}?asset_id={self.result["page_id"]}'
413 _, content_id, _ = await open_meta_post(page, list_url=list_url, page_name=self.page_name,
414 expected_text=self.title, content_id=self.result.get('content_id'), schedule=self.schedule)
415 self.result['content_id'] = content_id
416 self.result['status'] = 'scheduled' if self.schedule else ('processing' if self.video_file else 'published')
417 self.result['schedule'] = self.schedule.isoformat() if self.schedule else None
418 self.result['timezone'] = 'Asia/Shanghai'
419
420 async def upload(self) -> dict:
421 if self.video_file:
422 self.validate_video_file(self.video_file)
423 for path in self.image_files:
424 self.validate_image_file(path)
425 async with async_playwright() as playwright:
426 browser, context, page = await _open_business_page(
427 playwright, self.account_file, proxy=self.proxy, headless=self.headless
428 )
429 try:
430 if await _is_business_logged_out(page):
431 raise RuntimeError("Business Suite 登录态失效,请先执行对应平台 login")
432 await dismiss_guidance_cards(page)
433 await self._select_publish_location(page)
434 await self._upload_files(page)
435 await self._fill_caption(page)
436 await self._advance_reels(page)
437 await self._fill_schedule(page)
438 await self._publish(page)
439 await context.storage_state(path=str(self.account_file))
440 return self.result
441 finally:
442 self.result_file.parent.mkdir(parents=True, exist_ok=True)
443 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
444 await browser.close()
445
445 lines PYTHON