dzen.nstarikov.ru/app/ok_api.py
2026-06-27 14:07:10 +03:00

256 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import hashlib
import json
import re
from pathlib import Path
from typing import Any
import httpx
from app.config import Settings
OK_API_URL = "https://api.ok.ru/fb.do"
class OkApiError(RuntimeError):
pass
TAG_STOPWORDS = {
"А", "Без", "Будет", "Был", "Была", "Были", "В", "Во", "Вот", "Все", "Для", "Если",
"Его", "Ее", "И", "Или", "Как", "Когда", "Кто", "На", "Над", "Не", "Но", "О", "Об",
"От", "По", "При", "Про", "С", "Со", "Так", "Что", "Это", "Этот", "Эта", "Эти",
"Видео", "Смотрите", "Хотите", "Открывайте", "Школы", "Геополитики",
}
def build_video_tags(title: str | None, description: str | None, limit: int = 12) -> str | None:
text = "\n".join(part for part in [title or "", description or ""] if part).replace("ё", "е")
if not text.strip():
return None
tags: list[str] = []
def add(tag: str) -> None:
clean = re.sub(r"[^\wА-Яа-яЁё\-\s]+", "", tag)
clean = re.sub(r"\s+", " ", clean).strip(" -_")
if len(clean) < 3 or clean in TAG_STOPWORDS or clean.lower() in {item.lower() for item in tags}:
return
tags.append(clean)
for match in re.finditer(r"\b[А-ЯЁA-Z]{2,}(?:-[А-ЯЁA-Z]{2,})?\b", text):
add(match.group(0))
for match in re.finditer(r"\b[А-ЯЁ][а-яё]+(?:-[А-ЯЁ]?[а-яё]+)?\b", text):
add(match.group(0))
for match in re.finditer(r"\b[А-ЯЁ][а-яё]+(?:\s+[А-ЯЁ][а-яё]+){1,2}\b", text):
phrase = " ".join(word for word in match.group(0).split() if word not in TAG_STOPWORDS)
if phrase and len(phrase) <= 60:
add(phrase)
tags = tags[:limit]
if not tags:
return None
result = ", ".join(tags)
return result[:1000]
def build_sig(params: dict[str, Any], session_secret_key: str) -> str:
signable = {
key: value
for key, value in params.items()
if key not in {"access_token", "sig"} and value is not None
}
payload = "".join(f"{key}={signable[key]}" for key in sorted(signable))
return hashlib.md5(f"{payload}{session_secret_key}".encode("utf-8")).hexdigest()
def call_ok(settings: Settings, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
if not settings.ok_access_token or not settings.ok_session_secret_key or not settings.ok_public_key:
raise OkApiError("OK credentials are not configured")
request_params: dict[str, Any] = {
"application_key": settings.ok_public_key,
"format": "json",
"method": method,
"access_token": settings.ok_access_token,
}
request_params.update(params or {})
request_params["sig"] = build_sig(request_params, settings.ok_session_secret_key)
with httpx.Client(timeout=60) as client:
response = client.post(OK_API_URL, data=request_params)
response.raise_for_status()
if not response.text.strip():
return {}
data = response.json()
if isinstance(data, dict) and data.get("error_code"):
raise OkApiError(json.dumps(data, ensure_ascii=False))
return data
def upload_photo_to_group(settings: Settings, image_path: Path) -> str:
if not settings.ok_group_id:
raise OkApiError("OK_GROUP_ID is not configured")
upload_data = call_ok(settings, "photosV2.getUploadUrl", {"gid": settings.ok_group_id, "count": 1})
upload_url = upload_data.get("upload_url")
if not upload_url:
raise OkApiError(f"OK photo upload_url is missing: {upload_data}")
with image_path.open("rb") as image_file:
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
with httpx.Client(timeout=120) as client:
response = client.post(upload_url, files=files)
response.raise_for_status()
result = response.json()
photos = result.get("photos")
if isinstance(photos, dict):
for photo_data in photos.values():
if isinstance(photo_data, dict) and photo_data.get("token"):
return str(photo_data["token"])
token = result.get("token") or result.get("photo_token")
if token:
return str(token)
raise OkApiError(f"OK photo token is missing: {result}")
def upload_video_cover(settings: Settings, image_path: Path) -> tuple[str, str]:
upload_data = call_ok(settings, "photosV2.getUploadUrl", {"count": 1})
upload_url = upload_data.get("upload_url")
photo_ids = upload_data.get("photo_ids") or []
photo_id = str(photo_ids[0]) if photo_ids else ""
if not upload_url or not photo_id:
raise OkApiError(f"OK cover upload data is missing: {upload_data}")
with image_path.open("rb") as image_file:
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
with httpx.Client(timeout=120) as client:
response = client.post(upload_url, files=files)
response.raise_for_status()
result = response.json()
photo_data = (result.get("photos") or {}).get(photo_id) or {}
token = photo_data.get("token")
if not token:
raise OkApiError(f"OK cover token is missing: {result}")
return photo_id, str(token)
def upload_video_to_group(
settings: Settings,
video_path: Path,
title: str | None,
description: str | None = None,
cover_path: Path | None = None,
publish_to_group_video: bool = True,
) -> str:
if publish_to_group_video and not settings.ok_group_id:
raise OkApiError("OK_GROUP_ID is not configured")
upload_params: dict[str, Any] = {
"file_name": video_path.name,
"file_size": video_path.stat().st_size,
"post_form": "true",
}
if publish_to_group_video:
upload_params["gid"] = settings.ok_group_id
upload_data = call_ok(
settings,
"video.getUploadUrl",
upload_params,
)
upload_url = upload_data.get("upload_url")
video_id = upload_data.get("video_id")
if not upload_url or not video_id:
raise OkApiError(f"OK video upload data is missing: {upload_data}")
with video_path.open("rb") as video_file:
files = {"data": (video_path.name, video_file, "video/mp4")}
with httpx.Client(timeout=3600) as client:
response = client.post(upload_url, files=files)
response.raise_for_status()
update_params: dict[str, Any] = {
"vid": video_id,
"title": (title or video_path.stem)[:1000],
}
if description:
update_params["description"] = description[:4000]
tags = build_video_tags(title, description)
if tags:
update_params["tags"] = tags
if cover_path and cover_path.exists():
cover_photo_id, cover_token = upload_video_cover(settings, cover_path)
update_params["cover_photo_id"] = cover_photo_id
update_params["cover_photo_upload_token"] = cover_token
call_ok(settings, "video.update", update_params)
return str(video_id)
def upload_moment_photo(settings: Settings, image_path: Path) -> tuple[str, str]:
upload_data = call_ok(settings, "moments.getUploadUrl", {"type": "PHOTO"})
upload_url = upload_data.get("upload_url")
if not upload_url:
raise OkApiError(f"OK moment upload_url is missing: {upload_data}")
with image_path.open("rb") as image_file:
files = {"pic1": (image_path.name, image_file, "image/jpeg")}
with httpx.Client(timeout=120) as client:
response = client.post(upload_url, files=files)
response.raise_for_status()
result = response.json()
photos = result.get("photos")
if isinstance(photos, dict):
for photo_id, photo_data in photos.items():
if isinstance(photo_data, dict) and photo_data.get("token"):
return str(photo_id), str(photo_data["token"])
raise OkApiError(f"OK moment photo token is missing: {result}")
def commit_group_moment(settings: Settings, photo_id: str, token: str) -> dict[str, Any]:
if not settings.ok_group_id:
raise OkApiError("OK_GROUP_ID is not configured")
photo_items = [{"photo_id": photo_id, "token": token}]
params = {
"photos": json.dumps(photo_items, ensure_ascii=False),
"owner_ref": f"group:{settings.ok_group_id}",
}
try:
return call_ok(settings, "moments.commit", params)
except OkApiError:
params["photos"] = json.dumps({"photos": photo_items}, ensure_ascii=False)
return call_ok(settings, "moments.commit", params)
def post_group_mediatopic(settings: Settings, attachment: dict[str, Any]) -> dict[str, Any]:
if not settings.ok_group_id:
raise OkApiError("OK_GROUP_ID is not configured")
return call_ok(
settings,
"mediatopic.post",
{
"type": "GROUP_THEME",
"gid": settings.ok_group_id,
"attachment": json.dumps(attachment, ensure_ascii=False),
},
)
def edit_mediatopic(settings: Settings, topic_id: str, attachment: dict[str, Any]) -> dict[str, Any]:
return call_ok(
settings,
"mediatopic.edit",
{
"topic_id": topic_id,
"attachment": json.dumps(attachment, ensure_ascii=False),
},
)