[feat] solution/backend,docs: 미니블로그 승인 → 쓰레드 자동 게재, 쓰레드 초안 생성 OpenAI 전환
사장님 지시: "쓰레드에 연동되어 있으면 같이 업로드 되는 기능". 미니블로그의 두 승인 경로(이메일 GET 토큰, 로그인 "바로 발행")를 공통 메서드로 묶고, 그 끝에서 쓰레드 연동을 시도한다. 미니블로그 승인 자체가 발화 동의로 취급되므로 쓰레드 쪽 별도 승인은 묻지 않는다(DECISIONS 7-1-2 개정, 문구를 그대로 재사용하는 경우에 한정). 겸사겸사 쓰레드 초안 생성(generate_social_post)이 LLM_PROVIDER 를 안 타고 Gemini 를 직접 호출하던 것도 다른 생성 함수와 같은 추상화로 맞췄다. - blog_jobs._published_places: sites.domain IS NOT NULL 조건 추가(쓰레드 기준과 통일) - social_service.publish_reused_text: 연동 없음/게시 비활성/domain 미확정이면 스킵, 정상이면 APPROVED 삽입 + run_post(job_type=9) enqueue — 새 게시 로직은 안 만든다 - post_service: decide/approve_by_owner → _approve_and_publish 로 공통화, _try_social_share 는 실패를 전부 삼켜 미니블로그 승인을 막지 않는다 - gemini_text.generate_social_post: services.llm.provider.active() 로 전환, Gemini 전용 import 제거 - DECISIONS.md 7-1-2, MINI_BLOG.md 5·8절, SOCIAL.md 갱신 test_blog_owner.py·test_social.py 다수 추가/수정, 관련 스위트 전체 PASS
This commit is contained in:
1 parent
07c53d30bf
commit
47da2f29b3
9 files changed
+861
-101
No files matched your search
@@ -13,6 +13,7 @@ from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from config import social_config
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import place_posts, places, sites, users
|
||||
from common.enums import DBWRType, PostStatus, SiteStatus
|
||||
@@ -49,6 +50,7 @@ async def _published_places() -> list:
|
||||
places.deleted == False, # noqa: E712
|
||||
sites.deleted == False, # noqa: E712
|
||||
sites.status == SiteStatus.PUBLISHED.value,
|
||||
sites.domain.isnot(None),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -92,7 +94,7 @@ async def _generate_for_place(place) -> int:
|
||||
continue
|
||||
generated = await blog_service.generate_one(
|
||||
place_name=place.name, region=region, topic_kind=kind,
|
||||
material=material, used_topics=sorted(used_set),
|
||||
material=material, used_topics=sorted(used_set), place_category=place.category,
|
||||
)
|
||||
if not generated:
|
||||
continue
|
||||
@@ -171,7 +173,7 @@ async def generate_range(place_id: str, start_date: date, end_date: date) -> dic
|
||||
continue
|
||||
generated = await blog_service.generate_one(
|
||||
place_name=place.name, region=region, topic_kind=kind,
|
||||
material=material, used_topics=sorted(used_set),
|
||||
material=material, used_topics=sorted(used_set), place_category=place.category,
|
||||
)
|
||||
if not generated:
|
||||
continue
|
||||
@@ -219,7 +221,7 @@ async def generate_one_for_date(place_id: str, target_date: date) -> dict | None
|
||||
continue
|
||||
generated = await blog_service.generate_one(
|
||||
place_name=place.name, region=region, topic_kind=kind,
|
||||
material=material, used_topics=sorted(used_set),
|
||||
material=material, used_topics=sorted(used_set), place_category=place.category,
|
||||
)
|
||||
if not generated:
|
||||
continue
|
||||
@@ -261,6 +263,41 @@ def _mail_body(*, place_name: str, post, user, origin: str, approve_token: str)
|
||||
)
|
||||
|
||||
|
||||
def _notify_address(place, user) -> str:
|
||||
# notify_email 이 있으면 그 업장 전용 수신자다 — 없으면 계정 이메일(users.email)로 대체한다
|
||||
# (사장님 한 명이 사이트를 여러 개 가질 수 있어 계정 이메일 하나로는 업장별 수신자를 못 나눈다).
|
||||
return place.notify_email or user.email
|
||||
|
||||
|
||||
def _app_origin() -> str:
|
||||
"""메일의 승인·수정 링크가 향할 곳 — 빌더 앱(과 그 앞의 API)이 사는 오리진.
|
||||
|
||||
★ site_payload.publish_origin() 을 쓰면 안 된다 — 그건 발행된 고객 사이트(/s/<slug>)
|
||||
전용이다. 로컬에선 그게 solution-site 정적 서버(포트 80)라, 메일의 "수정하려면"
|
||||
링크(/blog?...)가 거기로 가서 404 났다(2026-09-21 실측). SNS 알림(notify_service.py)이
|
||||
이미 같은 목적으로 쓰는 SOCIAL_APP_ORIGIN 을 그대로 재사용한다 — 설정을 두 벌 안 둔다.
|
||||
비어 있으면(로컬에서 안 채웠으면) publish_origin() 으로 폴백해 링크가 아예 상대경로로
|
||||
깨지는 것보다는 낫게 한다."""
|
||||
return social_config.get("SOCIAL_APP_ORIGIN") or site_payload.publish_origin()
|
||||
|
||||
|
||||
async def _send_one(place, user, post) -> bool:
|
||||
"""토큰 발급 → 메일 본문 조립 → 발송 → 성공하면 SENT 로 표시. 실패하면 DB 를 안 건드린다."""
|
||||
token, token_hash, expires = blog_service.issue_token()
|
||||
body = _mail_body(
|
||||
place_name=place.name, post=post, user=user,
|
||||
origin=_app_origin(), approve_token=token,
|
||||
)
|
||||
ok = mail_service.send(to=_notify_address(place, user), subject=f"[{place.name}] 이번 글 올릴까요?", text=body)
|
||||
if not ok:
|
||||
return False
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()],
|
||||
[lambda s, pid=post.post_id, h=token_hash, e=expires: _crud.mark_sent(s, pid, h, e)],
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
async def send_reviewed() -> int:
|
||||
"""검수를 통과한 글을 사장님에게 한 통씩 보낸다. 보낸 수를 돌려준다."""
|
||||
if not mail_service.is_configured():
|
||||
@@ -273,22 +310,45 @@ async def send_reviewed() -> int:
|
||||
if not rows:
|
||||
return 0
|
||||
|
||||
targets = {str(place.place_id): (place.name, user) for place, user in await _published_places()}
|
||||
origin = site_payload.publish_origin()
|
||||
places_by_id = {str(place.place_id): (place, user) for place, user in await _published_places()}
|
||||
sent = 0
|
||||
for post in rows:
|
||||
target = targets.get(str(post.place_id))
|
||||
if not target or not mail_service.is_valid_address(target[1].email or ""):
|
||||
target = places_by_id.get(str(post.place_id))
|
||||
if not target:
|
||||
continue
|
||||
place_name, user = target
|
||||
token, token_hash, expires = blog_service.issue_token()
|
||||
body = _mail_body(place_name=place_name, post=post, user=user, origin=origin, approve_token=token)
|
||||
ok = mail_service.send(to=user.email, subject=f"[{place_name}] 이번 글 올릴까요?", text=body)
|
||||
if not ok:
|
||||
place, user = target
|
||||
if not mail_service.is_valid_address(_notify_address(place, user) or ""):
|
||||
continue
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()],
|
||||
[lambda s, pid=post.post_id, h=token_hash, e=expires: _crud.mark_sent(s, pid, h, e)],
|
||||
)
|
||||
sent += 1
|
||||
if await _send_one(place, user, post):
|
||||
sent += 1
|
||||
return sent
|
||||
|
||||
|
||||
async def send_now_for_place(place_id: str) -> dict:
|
||||
"""사장님이 빌더 화면에서 누르는 즉시 발송 — 아침 9시 스윕을 기다리지 않고 이 업장의
|
||||
오늘 몫을 지금 보낸다(2026-09-21, 사장님 요청: "지금 바로 발송할 수 있도록").
|
||||
'하루 한 통' 원칙은 그대로다 — 이미 오늘 보냈으면(REVIEWED 가 아니면) 보낼 게 없다."""
|
||||
if not mail_service.is_configured():
|
||||
return {"sent": False, "reason": "MAIL_NOT_CONFIGURED"}
|
||||
|
||||
place = user = None
|
||||
for p, u in await _published_places():
|
||||
if str(p.place_id) == str(place_id):
|
||||
place, user = p, u
|
||||
break
|
||||
if place is None:
|
||||
return {"sent": False, "reason": "NOTHING_DUE"}
|
||||
|
||||
post = await DB_SESSION_MNG.execute_lambda(
|
||||
place_posts.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: _crud.next_due_for_mail(s, place_id, PostStatus.REVIEWED.value, _today_kst()),
|
||||
)
|
||||
if post is None:
|
||||
return {"sent": False, "reason": "NOTHING_DUE"}
|
||||
|
||||
if not mail_service.is_valid_address(_notify_address(place, user) or ""):
|
||||
return {"sent": False, "reason": "NO_VALID_EMAIL"}
|
||||
|
||||
if not await _send_one(place, user, post):
|
||||
return {"sent": False, "reason": "SEND_FAILED"}
|
||||
return {"sent": True, "reason": None}
|
||||
+17
-14
@@ -25,10 +25,6 @@ from services.llm.errors import LlmError
|
||||
from services.llm.errors import LlmInvalidOutput as GeminiInvalidOutput
|
||||
from services.llm.errors import LlmNotConfigured as GeminiNotConfigured
|
||||
from services.prompts.copy import RESPONSE_SCHEMA, build_prompt
|
||||
# generate_social_post 는 공급자 선택(provider.active())을 타지 않고 Gemini 를 직접 부른다 —
|
||||
# 구조화 출력 재시도 루프(피드백 프롬프트로 다시 묻기)가 Gemini REST 응답 모양에 맞춰져 있다.
|
||||
# 모듈 최상단에서 이름으로 들여와야 테스트가 gemini_text.call 을 monkeypatch 할 수 있다.
|
||||
from services.llm.gemini import DEFAULT_MODEL as DEFAULT_TEXT_MODEL, call, extract_text
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
@@ -325,15 +321,22 @@ async def generate_song(
|
||||
|
||||
|
||||
async def generate_social_post(place_name, facts, link_url, provider=2, *, client=None):
|
||||
"""실제 게시 문자열을 검증한다. 초과·근거 실패 시 다시 받고 문장을 자르지 않는다."""
|
||||
"""실제 게시 문자열을 검증한다. 초과·근거 실패 시 다시 받고 문장을 자르지 않는다.
|
||||
|
||||
★ 2026-09-21: 다른 생성 함수(generate_copy 등)와 같은 이유로 공급자 선택을 탄다
|
||||
(`LLM_PROVIDER`, 기본 openai) — Gemini 고정을 없앴다. 인자 이름 `provider` 는
|
||||
SNS 플랫폼(쓰레드=2)을 가리키는 기존 값이라, LLM 공급자 모듈은 `llm_provider` 로
|
||||
따로 들여와 이름이 겹치지 않게 한다."""
|
||||
from services.prompts import social
|
||||
from services.external.social import adapter, weighted_length, URL
|
||||
from services.llm import provider as llm_provider
|
||||
import unicodedata
|
||||
|
||||
if not facts:
|
||||
raise GeminiInvalidOutput('NO_GROUNDED_FACTS')
|
||||
if not is_configured():
|
||||
raise GeminiNotConfigured('GEMINI_NOT_CONFIGURED')
|
||||
llm = llm_provider.active()
|
||||
if not llm.is_configured():
|
||||
raise GeminiNotConfigured(f"{llm.__name__.rsplit('.', 1)[-1].upper()}_API_KEY 가 설정되지 않았다")
|
||||
limit = adapter(provider).weighted_limit()
|
||||
allowed = {f.key for f in facts}
|
||||
feedback = ''
|
||||
@@ -341,14 +344,14 @@ async def generate_social_post(place_name, facts, link_url, provider=2, *, clien
|
||||
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)
|
||||
prompt = social.build_prompt(
|
||||
place_name, facts, limit - weighted_length('\n\n' + link_url, provider), feedback)
|
||||
result = await llm.generate(
|
||||
client, llm.DEFAULT_MODEL, prompt=prompt,
|
||||
response_schema=social.RESPONSE_SCHEMA, temperature=0.2, max_retries=0,
|
||||
)
|
||||
try:
|
||||
parsed = json.loads(extract_text(result))
|
||||
parsed = result.json if result.json is not None else json.loads(result.text)
|
||||
body = unicodedata.normalize('NFC', parsed['body'].strip())
|
||||
keys = parsed['fact_keys']
|
||||
text = body + '\n\n' + link_url
|
||||
|
||||
@@ -23,7 +23,7 @@ from common.utils.gtime import GTime
|
||||
from router.v1.site.protocol import (
|
||||
GenerationBatch, PostData, Res_GenerateNow, Res_GenerateOne, Res_GenerationHistory, Res_MyPosts,
|
||||
)
|
||||
from services import blog_jobs, blog_service
|
||||
from services import blog_jobs, blog_service, social_service
|
||||
from services.job_service import enqueue_job
|
||||
|
||||
EXPIRED = "처리할 수 없는 링크입니다."
|
||||
@@ -75,10 +75,7 @@ class PostService:
|
||||
)
|
||||
return {"success": True, "message": SKIPPED}
|
||||
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.approve(s, post_id)],
|
||||
)
|
||||
await self._enqueue_build(post_id, place_id)
|
||||
await self._approve_and_publish(post_id, place_id)
|
||||
return {"success": True, "message": APPROVED}
|
||||
|
||||
async def _load_place(self, user_info: UserInfo, place_id: str):
|
||||
@@ -191,7 +188,10 @@ class PostService:
|
||||
async def edit_by_owner(
|
||||
self, user_info: UserInfo, place_id: str, post_id: str, body: str
|
||||
) -> Res_WebPacketProtocol:
|
||||
"""로그인 세션으로 직접 고치기 — 메일이 아직 안 나간 REVIEWED 글도 여기서 바로 승인된다."""
|
||||
"""로그인 세션으로 직접 고치기 — 저장만 한다. ★ 승인은 여기서 하지 않는다(2026-09-21,
|
||||
사장님 지시: "승인되야 올라가도록 해야 한다") — 저장 후에는 이메일 승인 링크
|
||||
(router/v1/site/post.py approve_page → decide) 또는 바로 아래 approve_by_owner
|
||||
("바로 발행" 버튼)를 명시적으로 눌러야 게재된다."""
|
||||
res = Res_WebPacketProtocol()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
@@ -208,15 +208,13 @@ class PostService:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.update_body(s, pid, body)],
|
||||
)
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.approve(s, pid)],
|
||||
)
|
||||
await self._enqueue_build(pid, uuid.UUID(place_id))
|
||||
res.msg = APPROVED
|
||||
res.msg = "저장했습니다. 이메일 승인 링크를 눌러야 사이트에 반영됩니다."
|
||||
return res
|
||||
|
||||
async def approve_by_owner(self, user_info: UserInfo, place_id: str, post_id: str) -> Res_WebPacketProtocol:
|
||||
"""로그인 세션으로 바로 발행 — 고치지 않고 그대로. edit_by_owner 와 승인·빌드 경로는 같다."""
|
||||
"""로그인 세션으로 바로 발행 — 고치지 않고 그대로, 또는 방금 edit_by_owner 로 고친
|
||||
그대로 승인한다(2026-09-21, 사장님 지시: "이메일 승인으로도 발행 가능하고
|
||||
바로발행버튼으로도 발행 가능하도록"). 이메일 승인 링크와 별개의 두 번째 경로다."""
|
||||
res = Res_WebPacketProtocol()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
@@ -224,13 +222,37 @@ class PostService:
|
||||
return res
|
||||
|
||||
pid = uuid.UUID(post_id)
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.approve(s, pid)],
|
||||
)
|
||||
await self._enqueue_build(pid, uuid.UUID(place_id))
|
||||
await self._approve_and_publish(pid, uuid.UUID(place_id))
|
||||
res.msg = APPROVED
|
||||
return res
|
||||
|
||||
async def delete_by_owner(self, user_info: UserInfo, place_id: str, post_id: str) -> Res_WebPacketProtocol:
|
||||
"""소프트 삭제 — 상태 제한 없이 지운다. 이미 게재된 글이면 그 자리에서 빠지도록
|
||||
재발행 잡까지 큐에 넣는다(그 외 상태는 사이트에 나간 적이 없어 재발행이 필요 없다)."""
|
||||
res = Res_WebPacketProtocol()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
pid = uuid.UUID(post_id)
|
||||
row = await DB_SESSION_MNG.execute_lambda(
|
||||
place_posts.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.by_id(s, pid),
|
||||
)
|
||||
if row is None or str(row.place_id) != str(place_id):
|
||||
res.result.SetResult(ErrorType.PLACE_NOT_FOUND)
|
||||
return res
|
||||
|
||||
was_published = row.status == PostStatus.PUBLISHED.value
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.delete(s, pid)],
|
||||
)
|
||||
if was_published:
|
||||
await self._enqueue_build(pid, uuid.UUID(place_id))
|
||||
res.msg = "삭제했습니다."
|
||||
return res
|
||||
|
||||
async def generate_range(self, user_info: UserInfo, place_id: str, start_date: date, end_date: date) -> Res_GenerateNow:
|
||||
"""새벽 크론(04:10)을 기다리지 않고, 사장님이 고른 구간을 그 자리에서 채운다
|
||||
(2026-09-17, 사장님 지시: "지금 생성하기에서 시작이랑 끝 날짜를 정해야하지 않을까")."""
|
||||
@@ -274,6 +296,34 @@ class PostService:
|
||||
res.msg = "만들었습니다."
|
||||
return res
|
||||
|
||||
_SEND_NOW_MSG = {
|
||||
"MAIL_NOT_CONFIGURED": "메일 발송이 설정되어 있지 않습니다.",
|
||||
"NO_VALID_EMAIL": "받을 이메일 주소가 올바르지 않습니다.",
|
||||
"SEND_FAILED": "메일 발송에 실패했습니다.",
|
||||
}
|
||||
|
||||
async def send_now(self, user_info: UserInfo, place_id: str) -> Res_WebPacketProtocol:
|
||||
"""빌더 화면의 '지금 발송하기' — 아침 9시 스윕을 기다리지 않고 이 업장의 오늘 몫을
|
||||
바로 보낸다(2026-09-21, 사장님 요청). 보낼 게 없는 건 오류가 아니다 — generate_range
|
||||
의 '이미 다 있거나 소재가 없다'와 같은 결의 안내로 끝낸다."""
|
||||
res = Res_WebPacketProtocol()
|
||||
err_type, _place = await self._load_place(user_info, place_id)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
outcome = await blog_jobs.send_now_for_place(place_id)
|
||||
if outcome["sent"]:
|
||||
res.msg = "메일을 보냈습니다."
|
||||
return res
|
||||
reason = outcome.get("reason")
|
||||
if reason == "NOTHING_DUE":
|
||||
res.msg = "오늘 보낼 글이 없습니다."
|
||||
return res
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
res.msg = self._SEND_NOW_MSG.get(reason, "지금은 발송할 수 없습니다.")
|
||||
return res
|
||||
|
||||
async def _owner_user_id(self, place_id):
|
||||
def query(session):
|
||||
return session.execute(select(places.owner_user_id).where(places.place_id == place_id))
|
||||
@@ -282,6 +332,28 @@ class PostService:
|
||||
row = result.first() if result is not None else None
|
||||
return row[0] if row else None
|
||||
|
||||
async def _approve_and_publish(self, post_id, place_id) -> None:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[place_posts.DBType()], [lambda s: self.crud.approve(s, post_id)],
|
||||
)
|
||||
await self._enqueue_build(post_id, place_id)
|
||||
await self._try_social_share(post_id, place_id)
|
||||
|
||||
async def _try_social_share(self, post_id, place_id) -> None:
|
||||
"""쓰레드 연동 — 실패해도 미니블로그 승인은 이미 끝난 뒤라 예외를 밖으로 던지지
|
||||
않는다(2026-09-21, DECISIONS 7-1-2 개정)."""
|
||||
try:
|
||||
post = await DB_SESSION_MNG.execute_lambda(
|
||||
place_posts.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.crud.by_id(s, post_id),
|
||||
)
|
||||
owner_user_id = await self._owner_user_id(place_id)
|
||||
if post is None or owner_user_id is None or not post.body:
|
||||
return
|
||||
await social_service.publish_reused_text(owner_user_id, place_id, post.body)
|
||||
except Exception:
|
||||
LOG.w(f"[blog] post={post_id} 쓰레드 연동 실패 — 미니블로그 승인은 유지")
|
||||
|
||||
async def _enqueue_build(self, post_id, place_id) -> None:
|
||||
"""게재 = 그 사이트 하나를 다시 굽는 것. 전체 재굽기가 아니다(docs/PUBLISH_VERSION.md).
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from common.database.model.models import (
|
||||
place_facts,
|
||||
owner_social_accounts as Account,
|
||||
)
|
||||
from common.enums import SiteStatus, ErrorType, PUBLISHABLE_FACT_STATUSES
|
||||
from common.enums import SiteStatus, ErrorType, PUBLISHABLE_FACT_STATUSES, SocialProvider
|
||||
from crud.place_crud import PlaceCRUD
|
||||
from crud import social_crud as db
|
||||
from services import site_payload, social_account_service as accounts
|
||||
@@ -580,3 +580,49 @@ async def run_post(job):
|
||||
except Exception:
|
||||
await set_failure(post_id, "POST_RESULT_UNKNOWN", status="UNKNOWN")
|
||||
raise SocialOutcomeUnknown("POST_RESULT_UNKNOWN") from None
|
||||
|
||||
|
||||
async def publish_reused_text(user_id, place_id, body: str):
|
||||
"""미니블로그 승인 문구를 그대로 쓰레드에 낸다 — 승인 자체가 발화 동의라 별도 승인을
|
||||
또 묻지 않는다(2026-09-21, DECISIONS 7-1-2 개정: 미니블로그 문구를 그대로 재사용하는
|
||||
경우에 한정한 예외). 연동 안 돼 있거나 조건 미달이면 조용히 None을 돌려준다 — 호출부가
|
||||
실패로 취급하지 않는다."""
|
||||
if not posting_enabled():
|
||||
return None
|
||||
|
||||
async def run(s):
|
||||
account = await accounts.account(s, user_id, SocialProvider.THREADS.value)
|
||||
if not account or account.status != "linked":
|
||||
return None
|
||||
_place, site, url = await target(s, user_id, place_id)
|
||||
full_text = f"{body}\n\n{url}"
|
||||
row_id = (
|
||||
await s.execute(
|
||||
insert(Post)
|
||||
.values(
|
||||
place_id=place_id,
|
||||
user_id=user_id,
|
||||
site_version_id=site.current_version_id,
|
||||
provider=SocialProvider.THREADS.value,
|
||||
account_id=account.account_id,
|
||||
link_url=url,
|
||||
body=full_text,
|
||||
status="APPROVED",
|
||||
decided_at=datetime.now(timezone.utc),
|
||||
decided_via="mini_blog",
|
||||
)
|
||||
.on_conflict_do_nothing(
|
||||
index_elements=["place_id", "site_version_id"],
|
||||
index_where=text("deleted=false"),
|
||||
)
|
||||
.returning(Post.post_id)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if row_id:
|
||||
await db.enqueue(s, row_id, 9)
|
||||
return row_id
|
||||
|
||||
try:
|
||||
return await db.transaction(run)
|
||||
except HTTPException:
|
||||
return None
|
||||
Reference in new issue
Block a user