"""Meta 공식 Threads API.""" 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" # OAuth 토큰 엔드포인트는 **버전 접두어가 없고 토큰을 쿼리 파라미터로 받는다.** 데이터 엔드포인트(/me, /me/threads)와 규칙이 다르다 — 거기서만 Bearer 헤더가 통한다. OAUTH_BASE = "https://graph.threads.net" 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는 서버측 코드 교환이다. 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 {} # 플랫폼이 준 사유를 코드에 붙인다. detail = str(error.get("message") or "")[:160] subcode = error.get("error_subcode") or error.get("code") raise SocialError( f"THREADS_REJECTED_{res.status_code}" + (f"[{subcode}]" if subcode else "") + (f" {detail}" if detail else ""), reauth=error.get("code") == 190 or res.status_code == 401, ) return data async def exchange(code, verifier, *, client): short = _read( await client.post( f"{OAUTH_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"{OAUTH_BASE}/access_token", params={ "grant_type": "th_exchange_token", "client_secret": config.required("THREADS_APP_SECRET"), "access_token": 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"] # 그렇다고 검사를 통째로 버리지 않는다: 응답에 app_id 가 있으면(다른 플랫폼·향후 변경) 그때는 대조한다. app_id = debug.get("app_id") if ( not debug.get("is_valid") or (app_id is not None and str(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): # 갱신도 OAuth 엔드포인트다 — 버전 접두어 없이, 토큰은 쿼리 파라미터로. result = _read( await client.get( f"{OAUTH_BASE}/refresh_access_token", params={"grant_type": "th_refresh_token", "access_token": 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}"} # 컨테이너 생성은 아직 게시가 아니다. 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): permalink = None return {"id": post_id, "permalink": permalink}