Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
6.1 KiB
Python
145 lines
6.1 KiB
Python
"""Números dos posts pela janela logada (TikTok e Instagram). Só LÊ: não clica em nada além de rolar a página.
|
|
|
|
Validado com a conta real em 17/11/2026:
|
|
- TikTok Studio, /tiktokstudio/content: cada post é uma linha (`data-tt="components_RowLayout_FlexRow"`) com o link
|
|
`/@conta/video/<id>` e o texto terminando em "Todos\\n<visualizações>\\n<curtidas>\\n<comentários>".
|
|
- Instagram, aba Reels do perfil: a página busca os reels em /api/graphql com `code`, `play_count` (visualizações),
|
|
`like_count` e `comment_count`; a grade mostra as visualizações no próprio quadradinho ("1.499").
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import time
|
|
from typing import Any, Iterable
|
|
from urllib.parse import urljoin
|
|
|
|
from ..base import Sleep
|
|
from ..stats import PostStats, parse_count
|
|
from . import instagram_web
|
|
from .common import detect_block, needs_login
|
|
|
|
# ---------- TikTok
|
|
|
|
TIKTOK_CONTENT_URL = "https://www.tiktok.com/tiktokstudio/content"
|
|
_TIKTOK_VIDEO = re.compile(r"/video/(\d+)")
|
|
|
|
# Linha de cada link de vídeo: o ancestral mais próximo cujo texto tem várias linhas e a privacidade do post.
|
|
_TIKTOK_ROWS_JS = r"""() => [...document.querySelectorAll('a[href*="/video/"]')].map(a => {
|
|
let el = a;
|
|
for (let i = 0; i < 14 && el; i++, el = el.parentElement) {
|
|
if (el.getAttribute && el.getAttribute('data-tt') === 'components_RowLayout_FlexRow') break;
|
|
}
|
|
return {href: a.href, text: el ? el.innerText : ''};
|
|
})"""
|
|
|
|
|
|
def tiktok_row_stats(href: str, text: str) -> PostStats | None:
|
|
"""As três últimas linhas da linha do Studio são visualizações, curtidas e comentários."""
|
|
match = _TIKTOK_VIDEO.search(href or "")
|
|
lines = [line.strip() for line in (text or "").split("\n") if line.strip()]
|
|
if not match or len(lines) < 3:
|
|
return None
|
|
counts = [parse_count(line) for line in lines[-3:]]
|
|
if any(c is None for c in counts):
|
|
return None
|
|
return PostStats(match.group(1), counts[0], counts[1], counts[2])
|
|
|
|
|
|
def tiktok_stats(page: Any, ids: Iterable[str], sleep: Sleep = time.sleep, scrolls: int = 8) -> dict[str, PostStats]:
|
|
wanted = set(ids)
|
|
found: dict[str, PostStats] = {}
|
|
page.goto(TIKTOK_CONTENT_URL, wait_until="domcontentloaded")
|
|
_guard(page)
|
|
for attempt in range(scrolls + 4):
|
|
sleep(3)
|
|
for row in page.evaluate(_TIKTOK_ROWS_JS) or []:
|
|
stats = tiktok_row_stats(row.get("href", ""), row.get("text", ""))
|
|
if stats and stats.remote_id in wanted:
|
|
found[stats.remote_id] = stats
|
|
if wanted <= set(found):
|
|
break
|
|
if attempt >= 3: # a lista carrega mais posts ao rolar até o fim
|
|
page.mouse.wheel(0, 4000)
|
|
return found
|
|
|
|
|
|
# ---------- Instagram
|
|
|
|
INSTAGRAM_HOME = instagram_web.HOME_URL
|
|
_TILES_JS = r"""() => [...document.querySelectorAll('a[href*="/reel/"]')].map(a => ({href: a.getAttribute('href'), text: a.innerText}))"""
|
|
_REEL_CODE = re.compile(r"/reels?/([\w-]+)")
|
|
|
|
|
|
def instagram_media(payload: Any, out: dict[str, PostStats]) -> None:
|
|
"""Percorre a resposta do /api/graphql e guarda cada mídia com `code` e números."""
|
|
if isinstance(payload, dict):
|
|
code = payload.get("code")
|
|
if isinstance(code, str) and any(k in payload for k in ("play_count", "like_count", "view_count")):
|
|
views = next((payload[k] for k in ("play_count", "ig_play_count", "view_count", "video_view_count")
|
|
if isinstance(payload.get(k), int)), None)
|
|
likes = payload.get("like_count") if isinstance(payload.get("like_count"), int) else None
|
|
comments = payload.get("comment_count") if isinstance(payload.get("comment_count"), int) else None
|
|
if views is not None or likes is not None:
|
|
out[code] = PostStats(code, views, likes, comments)
|
|
for value in payload.values():
|
|
instagram_media(value, out)
|
|
elif isinstance(payload, list):
|
|
for value in payload:
|
|
instagram_media(value, out)
|
|
|
|
|
|
def instagram_stats(page: Any, codes: Iterable[str], sleep: Sleep = time.sleep, scrolls: int = 6) -> dict[str, PostStats]:
|
|
wanted = set(codes)
|
|
bodies: list[str] = []
|
|
|
|
def on_response(response: Any) -> None:
|
|
try:
|
|
if "/api/graphql" in response.url or "/api/v1/" in response.url:
|
|
bodies.append(response.text())
|
|
except Exception: # noqa: BLE001 - resposta sem corpo (redirect, cancelada)
|
|
pass
|
|
|
|
page.on("response", on_response)
|
|
page.goto(INSTAGRAM_HOME, wait_until="domcontentloaded")
|
|
_guard(page)
|
|
sleep(4)
|
|
href = page.evaluate(instagram_web._PROFILE_HREF_JS) # o mesmo do envio (barra lateral)
|
|
if not href:
|
|
raise needs_login("não achei o link do seu perfil no Instagram (a sessão pode ter saído)")
|
|
page.goto(urljoin(INSTAGRAM_HOME, href.rstrip("/") + "/reels/"), wait_until="domcontentloaded")
|
|
_guard(page)
|
|
api: dict[str, PostStats] = {}
|
|
tiles: dict[str, PostStats] = {}
|
|
for attempt in range(scrolls + 2):
|
|
sleep(4)
|
|
while bodies:
|
|
body = bodies.pop()
|
|
try:
|
|
instagram_media(json.loads(body), api)
|
|
except ValueError:
|
|
continue
|
|
# Reserva, se a resposta da API mudar de formato: as visualizações do quadradinho da grade.
|
|
for tile in page.evaluate(_TILES_JS) or []:
|
|
match = _REEL_CODE.search(tile.get("href") or "")
|
|
views = parse_count((tile.get("text") or "").split("\n")[0])
|
|
if match and views is not None:
|
|
tiles[match.group(1)] = PostStats(match.group(1), views)
|
|
# A grade aparece antes da resposta da API: só para cedo com a API; com a grade, depois de umas voltas.
|
|
if wanted <= set(api) or (attempt >= 2 and wanted <= set(api) | set(tiles)):
|
|
break
|
|
if attempt >= 1:
|
|
page.mouse.wheel(0, 4000)
|
|
found = {**tiles, **api}
|
|
return {code: stats for code, stats in found.items() if code in wanted}
|
|
|
|
|
|
def _guard(page: Any) -> None:
|
|
reason = detect_block(page)
|
|
if reason:
|
|
raise needs_login(reason)
|
|
|
|
|
|
READERS = {"tiktok": (TIKTOK_CONTENT_URL, tiktok_stats), "instagram": (INSTAGRAM_HOME, instagram_stats)}
|