"""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}