Merge branch 'feature/social-post'

This commit is contained in:
skkim committed 2026-09-18 09:00:07 +09:00
commit 46171b4f24
55 files changed
+2872 -7

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
"""알림톡 대행사 계약은 여기 한 곳에만 둔다. 승인 URL·전화번호·응답 원문을 로깅하지 않는다."""
import hashlib
import hmac
from config import social_config as config
import secrets
from datetime import datetime, timezone
def is_configured():
return all(
config.get(k)
for k in (
"ALIMTALK_API_KEY",
"ALIMTALK_API_SECRET",
"ALIMTALK_PROFILE_ID",
"ALIMTALK_SENDER",
"ALIMTALK_TEMPLATE_CODE",
)
)
async def send(to, template_code, variables, *, client):
date = datetime.now(timezone.utc).isoformat()
salt = secrets.token_hex(16)
signature = hmac.new(
config.required("ALIMTALK_API_SECRET").encode(),
(date + salt).encode(),
hashlib.sha256,
).hexdigest()
res = await client.post(
"https://api.solapi.com/messages/v4/send-many/detail",
headers={
"Authorization": f"HMAC-SHA256 apiKey={config.required('ALIMTALK_API_KEY')}, date={date}, salt={salt}, signature={signature}"
},
json={
"messages": [
{
"to": to,
"from": config.required("ALIMTALK_SENDER"),
"type": "ATA",
"kakaoOptions": {
"pfId": config.required("ALIMTALK_PROFILE_ID"),
"templateId": template_code,
"variables": variables,
"disableSms": True,
},
}
],
"allowDuplicates": False,
},
)
if res.status_code not in (200, 201):
raise RuntimeError("ALIMTALK_SEND_FAILED")
data = res.json()
if data.get("failedMessageList") or not data.get("groupInfo"):
raise RuntimeError("ALIMTALK_SEND_FAILED")
+41
View File
@@ -317,3 +317,44 @@ async def generate_song(
)
# 제목이 비면 상호를 쓴다 — 빈 제목은 플레이어에서 빈 줄로 보인다.
return GeneratedSong(title=title or place_name, lyrics=lyrics, style=style or "acoustic ballad")
async def generate_social_post(place_name, facts, link_url, provider=2, *, client=None):
"""실제 게시 문자열을 검증한다. 초과·근거 실패 시 다시 받고 문장을 자르지 않는다."""
from services.prompts import social
from services.external.social import adapter, weighted_length, URL
import unicodedata
if not facts:
raise GeminiInvalidOutput('NO_GROUNDED_FACTS')
if not is_configured():
raise GeminiNotConfigured('GEMINI_NOT_CONFIGURED')
limit = adapter(provider).weighted_limit()
allowed = {f.key for f in facts}
feedback = ''
owns = client is None
client = client or httpx.AsyncClient(timeout=45)
try:
for _ in range(3):
request = {'contents': [{'role': 'user', 'parts': [{'text': social.build_prompt(
place_name, facts, limit - weighted_length('\n\n' + link_url, provider), feedback)}]}],
'generationConfig': {'responseMimeType': 'application/json',
'responseSchema': social.RESPONSE_SCHEMA, 'temperature': 0.2,
'maxOutputTokens': 1024}}
result = await call(client, DEFAULT_TEXT_MODEL, request, max_retries=0)
try:
parsed = json.loads(extract_text(result))
body = unicodedata.normalize('NFC', parsed['body'].strip())
keys = parsed['fact_keys']
text = body + '\n\n' + link_url
ok, _ = ground_check(body, facts + [FactInput(key='name', label='상호명', value=place_name)])
if (body and isinstance(keys, list) and keys and all(k in allowed for k in keys)
and ok and not URL.search(body) and weighted_length(text, provider) <= limit):
return text
except (ValueError, KeyError, TypeError):
pass
feedback = '이전 응답은 길이 또는 근거 검증에 실패했다. 더 짧게, 제공된 사실만으로 다시 써라.'
raise GeminiInvalidOutput('SOCIAL_INVALID_OUTPUT')
finally:
if owns:
await client.aclose()
+50
View File
@@ -0,0 +1,50 @@
"""플랫폼 교체 경계. 전송 결과 불명은 재시도 가능한 실패와 절대 섞지 않는다."""
import re
import unicodedata
class SocialError(RuntimeError):
def __init__(self, code="SOCIAL_FAILED", *, reauth=False):
super().__init__(code)
self.reauth = reauth
class SocialOutcomeUnknown(SocialError):
pass
URL = re.compile(r"https?://[^\s]+", re.I)
def weighted_length(text: str, provider: int = 1) -> int:
text = unicodedata.normalize("NFC", text)
if provider == 2:
return len(text)
# 보수적으로 이모지 조합의 각 코드포인트도 센다. 공식 가중치보다 작게 세지 않는다.
def weight(c):
n = ord(c)
return (
1
if n <= 0x10FF
or 0x2000 <= n <= 0x200D
or 0x2010 <= n <= 0x201F
or 0x2032 <= n <= 0x2037
else 2
)
length = 0
pos = 0
for match in URL.finditer(text):
length += sum(weight(c) for c in text[pos : match.start()]) + 23
pos = match.end()
return length + sum(weight(c) for c in text[pos:])
def adapter(provider: int):
if provider == 2:
from services.external import threads
return threads
raise SocialError("UNSUPPORTED_PROVIDER")
+179
View File
@@ -0,0 +1,179 @@
"""Meta 공식 Threads API. 장기 액세스 토큰을 갱신하며 X의 refresh-token 계약을 요구하지 않는다."""
from config import social_config as config
from urllib.parse import urlencode, urlparse
import httpx
from services.external.social import SocialError, SocialOutcomeUnknown, weighted_length
BASE = "https://graph.threads.net/v1.0"
SCOPES = {"threads_basic", "threads_content_publish"}
def is_configured():
return all(
config.get(k)
for k in ("THREADS_APP_ID", "THREADS_APP_SECRET", "THREADS_REDIRECT_URI")
)
def weighted_limit():
return 500
def authorize_url(state, verifier):
# Threads는 서버측 코드 교환이다. X 전용 PKCE 파라미터를 전송하지 않는다.
return "https://threads.net/oauth/authorize?" + urlencode(
dict(
client_id=config.required("THREADS_APP_ID"),
redirect_uri=config.required("THREADS_REDIRECT_URI"),
response_type="code",
scope=",".join(sorted(SCOPES)),
state=state,
)
)
def _read(res):
try:
data = res.json()
except ValueError as ex:
raise SocialError("THREADS_INVALID_RESPONSE") from ex
if res.status_code >= 400 or data.get("error"):
error = data.get("error") or {}
raise SocialError(
f"THREADS_REJECTED_{res.status_code}",
reauth=error.get("code") == 190 or res.status_code == 401,
)
return data
async def exchange(code, verifier, *, client):
short = _read(
await client.post(
f"{BASE}/oauth/access_token",
data={
"client_id": config.required("THREADS_APP_ID"),
"client_secret": config.required("THREADS_APP_SECRET"),
"grant_type": "authorization_code",
"redirect_uri": config.required("THREADS_REDIRECT_URI"),
"code": code,
},
)
)
result = _read(
await client.get(
f"{BASE}/access_token",
params={
"grant_type": "th_exchange_token",
"client_secret": config.required("THREADS_APP_SECRET"),
},
headers={"Authorization": f"Bearer {short['access_token']}"},
)
)
token = result["access_token"]
debug = _read(
await client.get(
f"{BASE}/debug_token",
params={"input_token": token},
headers={
"Authorization": f"Bearer TH|{config.required('THREADS_APP_ID')}|{config.required('THREADS_APP_SECRET')}"
},
)
)["data"]
if (
not debug.get("is_valid")
or str(debug.get("app_id")) != config.required("THREADS_APP_ID")
or not SCOPES.issubset(set(debug.get("scopes", [])))
):
raise SocialError("THREADS_SCOPES_REQUIRED", reauth=True)
if int(result.get("expires_in", 0)) < 86400:
raise SocialError("THREADS_LONG_LIVED_TOKEN_REQUIRED", reauth=True)
result["scope"] = " ".join(sorted(SCOPES))
return result
async def refresh(token, *, client):
result = _read(
await client.get(
f"{BASE}/refresh_access_token",
params={"grant_type": "th_refresh_token"},
headers={"Authorization": f"Bearer {token}"},
)
)
if not result.get("access_token") or int(result.get("expires_in", 0)) <= 0:
raise SocialError("THREADS_REFRESH_FAILED", reauth=True)
result["scope"] = " ".join(sorted(SCOPES))
return result
async def me(token, *, client):
data = _read(
await client.get(
f"{BASE}/me",
params={"fields": "id,username"},
headers={"Authorization": f"Bearer {token}"},
)
)
return {
"id": data["id"],
"handle": data["username"],
"profile_url": f"https://www.threads.com/@{data['username']}",
}
async def publish(text, token, *, client):
if weighted_length(text, 2) > weighted_limit():
raise SocialError("TEXT_TOO_LONG")
headers = {"Authorization": f"Bearer {token}"}
# 컨테이너 생성은 아직 게시가 아니다. auto_publish_text를 켜면 이 구분이 사라진다.
try:
container = _read(
await client.post(
f"{BASE}/me/threads",
headers=headers,
data={"media_type": "TEXT", "text": text, "auto_publish_text": "false"},
)
)
container_id = container["id"]
except (httpx.TransportError, KeyError, TypeError) as ex:
raise SocialError("THREADS_CONTAINER_FAILED") from ex
try:
res = await client.post(
f"{BASE}/me/threads_publish",
headers=headers,
data={"creation_id": container_id},
)
if res.status_code >= 500 or res.status_code == 408:
raise SocialOutcomeUnknown("POST_RESULT_UNKNOWN")
# 성공 응답 파싱 실패·permalink 조회 실패도 이미 게시했을 수 있으므로 재전송 금지.
if res.status_code >= 400:
_read(res)
data = res.json()
post_id = str(data["id"])
if not post_id.isdigit():
raise ValueError()
except SocialError:
raise
except (httpx.TransportError, ValueError, KeyError, TypeError) as ex:
raise SocialOutcomeUnknown("POST_RESULT_UNKNOWN") from ex
try:
detail = _read(
await client.get(
f"{BASE}/{post_id}", params={"fields": "permalink"}, headers=headers
)
)
permalink = detail["permalink"]
parsed = urlparse(permalink)
if parsed.scheme != "https" or parsed.hostname not in (
"www.threads.net",
"threads.net",
"www.threads.com",
"threads.com",
):
raise ValueError()
except (httpx.TransportError, SocialError, ValueError, KeyError, TypeError):
# 게시 ID는 확보했다. 링크 조회 실패를 게시 실패로 취급하면 사장님이 다시 올린다.
permalink = None
return {"id": post_id, "permalink": permalink}