返回 Social Auto Upload
1 """Instagram 独立网页会话及照片、轮播、Reels 发布。"""
2 from __future__ import annotations
3
4 import asyncio
5 import hashlib
6 import json
7 import os
8 from pathlib import Path
9 from urllib.parse import urlparse
10 from uuid import uuid4
11
12 from patchright.async_api import Locator, Page, Playwright, TimeoutError as BrowserTimeoutError, async_playwright, expect
13
14 INSTAGRAM_HOME_URL = "https://www.instagram.com/"
15 # 未配置环境变量或 --proxy 时使用系统直连。
16 INSTAGRAM_PROXY = os.environ.get("SAU_INSTAGRAM_PROXY")
17 # 创建弹窗实际 accept 同时含照片与 MP4,此属性限定素材入口,排除编辑阶段的封面 input。
18 INSTAGRAM_MEDIA_INPUT = 'input[type="file"][accept*="video/mp4"]'
19 # _ac76 是已观察中/英文裁剪、编辑、配文页共用的向导标题栏组件;主动作不含 SVG,返回按钮含 SVG。
20 INSTAGRAM_PRIMARY_ACTION = '._ac76 [role="button"]:not(:has(svg))'
21
22
23 async def _dismiss_optional_prompt(guide: Locator, dismiss_button: Locator) -> bool:
24 """仅关闭已识别的可选提示;缺席可继续,出现后的操作失败必须报错。"""
25 try:
26 await guide.wait_for(state='visible', timeout=1500)
27 except BrowserTimeoutError:
28 return False
29 await expect(dismiss_button).to_have_count(1)
30 await dismiss_button.click()
31 await guide.wait_for(state='hidden')
32 return True
33
34
35 def _proxy_options(proxy: str | None) -> dict[str, str] | None:
36 """未传参数时使用显式环境配置,否则直连;空字符串可覆盖环境配置并直连。"""
37 address = (INSTAGRAM_PROXY if proxy is None else proxy) or ""
38 address = address.strip()
39 return {"server": address} if address else None
40
41
42 async def _open_instagram_page(playwright: Playwright, account_file: Path, *, proxy: str | None, headless: bool):
43 """使用工程 Chrome 和指定存储状态,导航失败保留原异常。"""
44 browser = await playwright.chromium.launch(channel="chrome", headless=headless, proxy=_proxy_options(proxy))
45 try:
46 context = await browser.new_context(storage_state=str(account_file))
47 page = await context.new_page()
48 page.set_default_timeout(30_000)
49 await page.goto(INSTAGRAM_HOME_URL, wait_until="domcontentloaded", timeout=120_000)
50 return browser, context, page
51 except Exception:
52 await browser.close()
53 raise
54
55
56 async def _is_instagram_logged_out(page: Page) -> bool:
57 """等待明确登录/未登录业务区域;网络或未知页面超时不能解释为 Cookie 失效。"""
58 # 消息入口是登录后的导航,href 前缀允许站点附加 hl 参数;登录表单字段不依赖翻译。
59 outcomes = page.locator('a[href^="/direct/inbox/"], input[name="username"], a[href^="/accounts/login/"]')
60 await expect(outcomes).not_to_have_count(0, timeout=60_000)
61 return not await page.locator('a[href^="/direct/inbox/"]').count()
62
63
64 async def instagram_identity(page: Page, account_file: Path) -> dict:
65 """将当前会话用户 ID 与账号文件绑定的 ID 比对,读取自己的导航主页。"""
66 if await _is_instagram_logged_out(page):
67 raise RuntimeError("Instagram 未登录,请执行 sau instagram login")
68 state = json.loads(account_file.read_text(encoding="utf-8"))
69 expected = {c['value'] for c in state['cookies'] if c['name'] == 'ds_user_id' and c['domain'].lstrip('.') == 'instagram.com'}
70 current = {c['value'] for c in await page.context.cookies(INSTAGRAM_HOME_URL) if c['name'] == 'ds_user_id'}
71 if len(expected) != 1 or current != expected:
72 raise RuntimeError("Instagram 当前登录用户与账号文件绑定的用户 ID 不匹配")
73 # 当前用户导航头像位于 aria-selected 图标容器中;动态流和推荐头像没有导航选中状态。
74 own_profile = page.locator('a[href]').filter(has=page.locator('[aria-selected] img'))
75 await expect(own_profile).to_have_count(1)
76 href = await own_profile.get_attribute('href')
77 username = urlparse(href).path.strip('/')
78 if not username or '/' in username:
79 raise RuntimeError("Instagram 当前用户主页链接结构不符")
80 return {"user_id": next(iter(expected)), "username": username}
81
82
83 async def instagram_cookie_auth(account_file: str | Path, *, proxy: str | None = None) -> bool:
84 """独立验证登录和账号绑定;未知页面/网络错误直接上报。"""
85 account_file = Path(account_file)
86 if not account_file.is_file():
87 return False
88 async with async_playwright() as playwright:
89 browser, context, page = await _open_instagram_page(playwright, account_file, proxy=proxy, headless=True)
90 try:
91 if await _is_instagram_logged_out(page):
92 return False
93 await instagram_identity(page, account_file)
94 return True
95 finally:
96 await browser.close()
97
98
99 async def instagram_setup(account_file: str | Path, *, handle: bool = False, proxy: str | None = None,
100 headless: bool = False, return_detail: bool = False, timeout_seconds: int = 900):
101 """工程浏览器人工登录,导出候选状态并在新 context 验证后替换账号文件。"""
102 account_file = Path(account_file)
103 account_file.parent.mkdir(parents=True, exist_ok=True)
104 if await instagram_cookie_auth(account_file, proxy=proxy):
105 result = {"success": True, "status": "cookie_valid", "account_file": str(account_file)}
106 return result if return_detail else True
107 if not handle:
108 result = {"success": False, "status": "cookie_invalid", "account_file": str(account_file)}
109 return result if return_detail else False
110 async with async_playwright() as p:
111 browser = await p.chromium.launch(channel="chrome", headless=headless, proxy=_proxy_options(proxy), args=["--start-maximized"])
112 candidate = account_file.with_name(f'{account_file.stem}.{uuid4().hex}.pending.json')
113 try:
114 context = await browser.new_context(no_viewport=not headless)
115 page = await context.new_page()
116 await page.goto(INSTAGRAM_HOME_URL + 'accounts/login/', wait_until='domcontentloaded', timeout=120_000)
117 # 消息入口仅在人工登录及挑战完成后出现;不按 URL 或登录表单消失宣告成功。
118 await page.locator('a[href^="/direct/inbox/"]').wait_for(state='visible', timeout=timeout_seconds * 1000)
119 await context.storage_state(path=str(candidate))
120 if not await instagram_cookie_auth(candidate, proxy=proxy):
121 raise RuntimeError('Instagram 导出的候选状态未通过新会话验证')
122 candidate.replace(account_file)
123 result = {"success": True, "status": "logged_in", "account_file": str(account_file)}
124 return result if return_detail else True
125 finally:
126 candidate.unlink(missing_ok=True)
127 await browser.close()
128
129
130 def instagram_response_payload(body: str) -> dict:
131 """解析已观察的普通 JSON 以及 Meta 防 JSON 劫持前缀,其他格式直接报错。"""
132 if body.startswith('for (;;);'):
133 body = body[len('for (;;);'):]
134 return json.loads(body)
135
136
137 def instagram_created_media(payload: dict, *, owner_id: str, caption: str) -> dict:
138 """只接受最终创建响应中匹配用户和配文的作品;处理中和 HTTP 200 均不是成功。"""
139 envelope = payload
140 payload = envelope.get('payload', envelope)
141 if envelope.get('error') or payload.get('status') not in (None, 'ok') or ('statusCode' in payload and payload['statusCode'] != 200):
142 raise RuntimeError(f"Instagram 创建未成功: {payload.get('message', payload.get('statusCode', payload.get('status')))}")
143 media = payload.get('media') or {}
144 if not media.get('code') or not media.get('id'):
145 raise RuntimeError('Instagram 创建响应缺少作品编号')
146 if str((media.get('user') or {}).get('pk')) != owner_id:
147 raise RuntimeError('Instagram 创建响应的作者 ID 不匹配')
148 if (media.get('caption') or {}).get('text') != caption:
149 raise RuntimeError('Instagram 创建响应的配文不匹配')
150 return media
151
152
153 class InstagramUploader:
154 """独立网页立即发布;最终创建响应确认成功后返回作品链接。"""
155
156 def __init__(self, account_file: str | Path, *, title: str, description: str = '', tags: list[str] | None = None,
157 video_file: str | Path | None = None, image_files: list[str | Path] | None = None,
158 thumbnail: str | Path | None = None,
159 proxy: str | None = None, headless: bool = False, result_file: str | Path | None = None):
160 self.account_file = Path(account_file)
161 self.title, self.description = title.strip(), description.strip()
162 self.tags = [t.strip().lstrip('#') for t in (tags or []) if t.strip().lstrip('#')]
163 self.video_file = Path(video_file) if video_file else None
164 self.image_files = [Path(p) for p in (image_files or [])]
165 self.thumbnail = Path(thumbnail) if thumbnail else None
166 if self.thumbnail and not self.video_file:
167 raise ValueError('Instagram 自定义封面仅用于视频/Reel')
168 if bool(self.video_file) == bool(self.image_files):
169 raise ValueError('必须且只能传入视频或图片文件')
170 if not self.title:
171 raise ValueError('标题不能为空')
172 self.proxy, self.headless = proxy, headless
173 self.result_file = Path(result_file) if result_file else Path('.local/instagram-results') / f'{uuid4().hex}.json'
174 self.result = {'platform': 'instagram', 'title': self.title, 'status': 'not_submitted'}
175 self.stage = 'validation'
176 if len(self._caption()) > 2200:
177 raise ValueError('Instagram 配文(标题、正文、标签合计)不能超过 2200 字符')
178
179 def _caption(self) -> str:
180 """Instagram 只有配文,将 CLI 标题、正文和标签合并。"""
181 parts = [p for p in (self.title, self.description) if p]
182 if self.tags:
183 parts.append(' '.join(f'#{t}' for t in self.tags))
184 return '\n\n'.join(parts)
185
186 async def _upload_files(self, page: Page) -> None:
187 """打开创建入口并等待裁剪阶段就绪,拒绝用上传后固定延时推断完成。"""
188 # 实际通知提示使用此固定图标及 _a9-z 动作区。两项依次为开启、稍后,
189 # 取第二个直接子按钮;限定图标和局部动作区,避免按翻译文案或全页按钮点击。
190 notifications = page.get_by_role('dialog').filter(
191 has=page.locator('img[src^="/images/instagram/xig/ico/xxhdpi_launcher.png"]'))
192 notification_buttons = notifications.locator('._a9-z > button')
193 # 中英文首页均观察到这四个导航弹出入口,依次为通知、创建、设置、Meta。
194 # 先断言完整组和各入口含 aria-selected 图标再取业务顺序第二项,避免全页任意 nth。
195 navigation_popups = page.locator('a._a6hd[href="#"]').filter(has=page.locator('[aria-selected]'))
196 # 实测通知可能晚于导航出现。动作检查期间处理此已知遮挡,避免先检查缺席、
197 # 再点击时才弹出造成竞态;没有提示时不会执行回调,也不添加固定等待。
198 await page.add_locator_handler(notifications, lambda: _dismiss_optional_prompt(notifications, notification_buttons.nth(1)))
199 try:
200 await expect(navigation_popups).to_have_count(4)
201 await navigation_popups.nth(1).click()
202 finally:
203 await page.remove_locator_handler(notifications)
204 dialog = page.get_by_role('dialog')
205 await expect(dialog).to_have_count(1)
206 file_input = dialog.locator(INSTAGRAM_MEDIA_INPUT)
207 await expect(file_input).to_have_count(1)
208 paths = [self.video_file] if self.video_file else self.image_files
209 await file_input.set_input_files([str(p.resolve()) for p in paths])
210 if self.video_file:
211 # 实际 Reels 介绍使用 reels_nux_icon;动作区“了解更多”位于 span 中,
212 # 确认按钮直接位于 div 中,按局部父子关系区分,不依赖语言与样式散列。
213 reels_intro = page.get_by_role('dialog').filter(
214 has=page.locator('img[src^="/images/instagram/clips/reels_nux_icon.png"]'))
215 await _dismiss_optional_prompt(reels_intro, reels_intro.locator('._a9-z div > button'))
216 # 裁剪标题栏主动作实际出现,才可推进;上传失败或未知弹窗阻断会保留现场并报错。
217 await expect(dialog.locator(INSTAGRAM_PRIMARY_ACTION)).to_have_count(1, timeout=60_000)
218
219 async def _advance_media_editor(self, page: Page) -> None:
220 """裁剪、编辑两步各等待标题改变,最终以 Lexical 配文输入框确认。"""
221 # 同一个创建弹窗标题栏存在于三个阶段;局部主动作不含图标,排除返回和媒体工具按钮。
222 dialog = page.get_by_role('dialog')
223 heading = dialog.locator('._ac76 [role="heading"]')
224 for step in range(2):
225 if step == 1 and self.thumbnail:
226 # 实际视频编辑弹窗中,精确 JPEG/PNG accept 是独立封面入口,排除初始视频素材 input。
227 cover = dialog.locator('input[type="file"][accept="image/jpeg,image/png"]')
228 # 主预览的 video 紧邻封面背景层;右侧视频帧条也有背景图,不能拿帧条验证封面。
229 poster = dialog.locator('video + div[style*="background-image"]')
230 await expect(cover).to_have_count(1)
231 await expect(poster).to_have_count(1)
232 previous_style = await poster.get_attribute('style')
233 await cover.set_input_files(str(self.thumbnail.resolve()))
234 await expect(poster).not_to_have_attribute('style', previous_style, timeout=30_000)
235 # 已观察页面直接以原图 blob 替换封面。核对实际预览字节并解码,文件选中本身不代表生效。
236 preview = await asyncio.wait_for(poster.evaluate('''async element => {
237 const background = getComputedStyle(element).backgroundImage;
238 const url = background.slice(5, -2);
239 const blob = await (await fetch(url)).blob();
240 const bitmap = await createImageBitmap(blob);
241 const digest = await crypto.subtle.digest('SHA-256', await blob.arrayBuffer());
242 const result = {width: bitmap.width, height: bitmap.height,
243 sha256: Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('')};
244 bitmap.close();
245 return result;
246 }'''), timeout=30)
247 if not preview['width'] or not preview['height'] or preview['sha256'] != hashlib.sha256(self.thumbnail.read_bytes()).hexdigest():
248 raise RuntimeError('Instagram 封面主预览与指定图片不匹配')
249 await expect(heading).to_have_count(1)
250 previous = await heading.inner_text()
251 action = dialog.locator(INSTAGRAM_PRIMARY_ACTION)
252 await expect(action).to_have_count(1)
253 await expect(action).to_be_enabled()
254 await action.click()
255 await expect(heading).not_to_have_text(previous, timeout=60_000)
256 # data-lexical-editor 标识真实正文编辑器,限定当前创建弹窗,排除评论输入框。
257 await expect(dialog.locator('[contenteditable="true"][role="textbox"][data-lexical-editor="true"]')).to_have_count(1)
258
259 async def _publish(self, page: Page, identity: dict) -> None:
260 """先登记最终响应监听再分享,响应不明时记录 unknown 且不重发。"""
261 # 配文页独有 Lexical 编辑器;标题栏唯一主动作此时是分享,不使用翻译后的按钮名称。
262 dialog = page.get_by_role('dialog')
263 editor = dialog.locator('[contenteditable="true"][role="textbox"][data-lexical-editor="true"]')
264 caption = self._caption()
265 await editor.fill(caption)
266 await expect(editor).to_have_text(caption)
267 action = dialog.locator(INSTAGRAM_PRIMARY_ACTION)
268 await expect(action).to_have_count(1)
269 await expect(action).to_be_enabled()
270 self.result.update(identity, status='submission_unknown')
271 self.result_file.parent.mkdir(parents=True, exist_ok=True)
272 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
273 # Reel 首次返回 202,浏览器会继续请求同一创建接口,后续才返回正式 media。
274 # 提交前安装队列监听,持续消费本次创建响应;只点击一次,不将上传响应或 202 视为发表成功。
275 responses = asyncio.Queue()
276 def on_response(response):
277 if response.request.method == 'POST' and urlparse(response.url).path.startswith('/api/v1/media/configure'):
278 responses.put_nowait(response)
279 page.on('response', on_response)
280 try:
281 await action.click()
282 deadline = asyncio.get_running_loop().time() + 180
283 while True:
284 remaining = deadline - asyncio.get_running_loop().time()
285 if remaining <= 0:
286 raise TimeoutError('Instagram 已提交,但等待最终作品创建响应超时')
287 response = await asyncio.wait_for(responses.get(), timeout=remaining)
288 remaining = deadline - asyncio.get_running_loop().time()
289 payload = instagram_response_payload(await asyncio.wait_for(response.text(), timeout=max(remaining, 0)))
290 body = payload.get('payload', payload)
291 if body.get('statusCode') == 202:
292 self.result['status'] = 'processing'
293 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
294 continue
295 media = instagram_created_media(payload, owner_id=identity['user_id'], caption=caption)
296 break
297 finally:
298 page.remove_listener('response', on_response)
299 kind = 'reel' if self.video_file else 'p'
300 self.result.update(status='published', content_id=media['id'], post_id=media['code'],
301 post_url=f"{INSTAGRAM_HOME_URL}{kind}/{media['code']}/", schedule=None,
302 media_count=len(media.get('carousel_media') or [media]))
303 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
304
305 async def upload(self) -> dict:
306 """在同一会话核验身份、上传并发表;失败保存阶段与本地证据。"""
307 if self.thumbnail:
308 if not self.thumbnail.is_file():
309 raise FileNotFoundError(f'Instagram 封面不存在: {self.thumbnail}')
310 if self.thumbnail.suffix.lower() not in {'.jpg', '.jpeg', '.png'}:
311 raise ValueError('Instagram 封面仅支持 JPG/JPEG/PNG')
312 paths = [self.video_file] if self.video_file else self.image_files
313 for path in paths:
314 if not path.is_file():
315 raise FileNotFoundError(f'Instagram 素材不存在: {path}')
316 allowed = {'.mp4', '.mov'} if self.video_file else {'.jpg', '.jpeg', '.png', '.avif', '.heic', '.heif'}
317 if path.suffix.lower() not in allowed:
318 raise ValueError(f'Instagram 不支持的素材类型: {path.suffix}')
319 async with async_playwright() as p:
320 browser, context, page = await _open_instagram_page(p, self.account_file, proxy=self.proxy, headless=self.headless)
321 try:
322 self.stage = 'identity'
323 identity = await instagram_identity(page, self.account_file)
324 self.stage = 'upload'
325 await self._upload_files(page)
326 self.stage = 'edit'
327 await self._advance_media_editor(page)
328 self.stage = 'publish'
329 await self._publish(page, identity)
330 self.stage = 'save_session'
331 await context.storage_state(path=str(self.account_file))
332 return self.result
333 except Exception as error:
334 folder = Path('.local/instagram-errors') / uuid4().hex
335 folder.mkdir(parents=True)
336 self.result.update(stage=self.stage, error=str(error), evidence_dir=str(folder))
337 self.result_file.parent.mkdir(parents=True, exist_ok=True)
338 self.result_file.write_text(json.dumps(self.result, ensure_ascii=False, indent=2), encoding='utf-8')
339 await page.screenshot(path=str(folder/'page.png'))
340 (folder/'page.html').write_text(await page.content(), encoding='utf-8')
341 raise RuntimeError(f'Instagram {self.stage} 未完成;结果记录: {self.result_file};原因: {error}') from error
342 finally:
343 await browser.close()
344
344 lines PYTHON