From 6f6373932db079588cfb310add89bfda70eb4ae9 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 7 Oct 2024 00:26:09 +0800 Subject: [PATCH] fix(twitter): gt cookie --- lib/routes/twitter/api/web-api/utils.ts | 28 +++++++++++++++++++------ lib/routes/twitter/media.ts | 2 +- lib/routes/twitter/user.ts | 2 +- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/lib/routes/twitter/api/web-api/utils.ts b/lib/routes/twitter/api/web-api/utils.ts index 9f5f14b85..3b790d709 100644 --- a/lib/routes/twitter/api/web-api/utils.ts +++ b/lib/routes/twitter/api/web-api/utils.ts @@ -24,9 +24,19 @@ const token2Cookie = (token) => uri: proxy.proxyUri, }) : new CookieAgent({ cookies: { jar } }); - await ofetch('https://x.com', { - dispatcher: agent, - }); + if (token) { + await ofetch('https://x.com', { + dispatcher: agent, + }); + } else { + const data = await ofetch('https://x.com/narendramodi?mx=2', { + dispatcher: agent, + }); + const gt = data.match(/document\.cookie="gt=(\d+)/)?.[1]; + if (gt) { + jar.setCookieSync(`gt=${gt}`, 'https://x.com'); + } + } return JSON.stringify(jar.serializeSync()); } catch { // ignore @@ -72,7 +82,7 @@ export const twitterGot = async ( const requestUrl = `${url}?${queryString.stringify(params)}`; - let cookie: string | Record | null | undefined = auth?.token ? await token2Cookie(auth.token) : null; + let cookie: string | Record | null | undefined = await token2Cookie(auth?.token); if (!cookie && auth) { cookie = await login({ username: auth.username, @@ -129,11 +139,17 @@ export const twitterGot = async ( 'content-type': 'application/json', dnt: '1', pragma: 'no-cache', - referer: 'https://x.com/narendramodi', + referer: 'https://x.com/', 'x-twitter-active-user': 'yes', - 'x-twitter-auth-type': 'OAuth2Session', 'x-twitter-client-language': 'en', 'x-csrf-token': jsonCookie.ct0, + ...(auth?.token + ? { + 'x-twitter-auth-type': 'OAuth2Session', + } + : { + 'x-guest-token': jsonCookie.gt, + }), }, dispatcher: dispatchers?.agent, onResponse: async ({ response }) => { diff --git a/lib/routes/twitter/media.ts b/lib/routes/twitter/media.ts index b07d1a479..a8f87abca 100644 --- a/lib/routes/twitter/media.ts +++ b/lib/routes/twitter/media.ts @@ -52,7 +52,7 @@ async function handler(ctx) { try { data = await api.getUserMedia(id, params); } catch (error) { - logger.debug(error); + logger.error(error); } const profileImageUrl = userInfo?.profile_image_url || userInfo?.profile_image_url_https; diff --git a/lib/routes/twitter/user.ts b/lib/routes/twitter/user.ts index a3055bfe7..c4b20fc58 100644 --- a/lib/routes/twitter/user.ts +++ b/lib/routes/twitter/user.ts @@ -66,7 +66,7 @@ async function handler(ctx) { data = utils.excludeRetweet(data); } } catch (error) { - logger.debug(error); + logger.error(error); } const profileImageUrl = userInfo?.profile_image_url || userInfo?.profile_image_url_https;