[feat] solution,postgres-init,docs: SNS 게재 — 사장님이 누르면 쓰고, 승인받아, 사장님 계정으로 올린다
발행한 사이트로 사람을 데려올 경로가 제품 안에 없었다. IndexNow 통보와 사이트맵뿐이고 그건
검색엔진이 언제 읽을지 우리가 모른다. 이제 사장님이 [Threads에 알리기] 를 누르면 확인된 fact 로
짧은 글을 쓰고, 승인을 받아 사장님 개인 계정으로 올린다. 올린 글은 발행본 맨 아래에도 실린다.
★ 이 레포가 처음으로 ①외부에 쓰기를 하고 ②남의 계정 자격증명을 보관하고 ③되돌릴 수 없는
행위를 한다. 아래 결정이 전부 여기서 나왔다.
승인을 다시 둔다 — 7절("승인 없이 나간다")의 예외다(DECISIONS 7-1). 기준은 문장의 참/거짓이
아니라 명의(사장님 계정의 발언) · 회수 가능성(없다) · 무엇이 주로 틀리나(문장이 아니라 링크 —
`_publish_target` 이 계산하므로 앞 게이트가 못 본다)다. 7절의 함정은 구조로 막았다:
시작이 사장님 클릭이라 "안 눌러서 영영 안 나감" 이 생기지 않고, 승인 경로가 둘(화면·알림톡)이며,
미승인은 EXPIRED 로 화면에 보이게 남는다.
★ 게시는 `domain` 이 확정된 사이트에만. 비면 슬러그가 상호명에서 파생돼(`_publish_target`)
상호를 고치는 순간 주소가 바뀌고, 이미 올라간 글의 링크는 404 가 된다 — 그 글은 수정할 수 없다.
★ 승인은 GET 이 아니라 POST. 메신저 링크 미리보기·백신·프리페치가 사람이 누르기 전에 URL 을
연다. 일회성은 토큰이 아니라 `status='PENDING_APPROVAL'` 조건이 붙은 단일 UPDATE 가 보장한다.
★ 사진은 올리지 않는다 — 1-2 의 격리("나중에 필터로 뺀다")가 SNS 에서는 구조적으로 불가능하다.
필터가 아니라 첨부 코드를 아예 만들지 않았다.
★ 게시는 기본으로 꺼져 있다(`SOCIAL_POSTING_ENABLED=0`). 플랫폼 계약과 1-4(해지 시 처리)
결론을 확인한 뒤 사람이 연다 — 1-4 가 이 기능의 전제조건이 됐다.
플랫폼은 스레드다. X 는 URL 이 든 글에 요청당 $0.20 이 안내돼 있어 "계정 단위 고정비" 라는
처음 가정이 틀렸다(사이트마다 나가는 변동비다). 어댑터 경계는 두되 X 어댑터는 넣지 않았다.
- place_social_posts · owner_social_accounts 신설(init.sql + 0012·0013). 승인 대기는 잡이 아니라
행의 상태다 — 잡으로 매달면 lease 만료로 DEAD 가 된다
- services/social_service · social_account_service · notify_service · external/{threads,alimtalk,social}
- router/v1/social — GET 은 상태를 바꾸지 않고, POST 가 링크·계정을 재검사한 뒤 CAS 한다
- 빌더 SocialPanel(발행 완료 화면) + 무인증 승인 페이지 `/approve/:postId`
- 발행본 SocialPostsSection — 정적 카드 + 원문 링크. 위젯·임베드 없음. 고유 콘텐츠 계수에서 제외
- nginx: `/approve/` 는 no-referrer · no-store · noindex + 액세스 로그 끔
밟은 함정 둘
- ORM 기본값에 쉼표가 딸려 들어갔다: `text("'[]',")` → `DEFAULT '[]', NOT NULL` 로 나가
CREATE TABLE 이 통째로 실패. 운영 DB 는 init.sql 로 만들어져 안 드러나고 ORM 이 스키마를
만드는 테스트 DB 에서만 터진다 — 09-10 의 `now()` 기본값 사고와 같은 자리다
- 승인 스윕이 1분 주기라 쓰기 커넥션을 계속 집어 들었다 → 5분. 이 스윕은 만료 표시와 중단 정리뿐이라
분 단위 정밀도가 필요 없다
검증: 백엔드 645 passed / 5 failed(전부 환경 — 프론트 소스 부재·레이트리밋).
★ 테스트에 실제 API 키가 새면 BUILD 잡이 Suno·Perplexity 를 진짜로 부른다(실측: 한 파일 12분 →
키를 비우면 10초). 키를 비운 상태가 정상 실행 조건이다.
에디터 목록 대조(test_site_theme) 22건 통과 · tsc·eslint 통과 · vitest 62 passed
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c07e2bddf4
commit
0e0f2cf038
54 files changed
+2555
-13
No files matched your search
+57
@@ -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")
|
||||
@@ -268,3 +268,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
@@ -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
@@ -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}
|
||||
Reference in new issue
Block a user