From 02a8ae4c62d97396ce6aa88915e67ae607ffe72b Mon Sep 17 00:00:00 2001 From: arnd-s <34441397+arnd-s@users.noreply.github.com> Date: Sun, 16 Jan 2022 03:59:02 +0100 Subject: [PATCH] [TwitterBridge] Use Twitter API V1.1 guest/activate for requesting new guest tokens (#2414) Instead of searching inside base html page for the guest token, this patch instead uses the Twitter API V1.1 to acquire guest tokens --- bridges/TwitterBridge.php | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/bridges/TwitterBridge.php b/bridges/TwitterBridge.php index a14e5062..1cc9d51d 100644 --- a/bridges/TwitterBridge.php +++ b/bridges/TwitterBridge.php @@ -545,7 +545,7 @@ EOD; $guestToken = null; if($guestTokenUses === null || !is_array($guestTokenUses) || count($guestTokenUses) != 2 || $guestTokenUses[0] <= 0 || (time() - $refresh) > self::GUEST_TOKEN_EXPIRY) { - $guestToken = $this->getGuestToken(); + $guestToken = $this->getGuestToken($apiKey); if ($guestToken === null) { if($guestTokenUses === null) { returnServerError('Could not parse guest token'); @@ -568,15 +568,20 @@ EOD; // Get a guest token. This is different to an API key, // and it seems to change more regularly than the API key. - private function getGuestToken() { - $pageContent = getContents('https://twitter.com', array(), array(), true); + private function getGuestToken($apiKey) { + $headers = array( + 'authorization: Bearer ' . $apiKey, + ); + $opts = array( + CURLOPT_POST => 1, + ); - $guestTokenRegex = '/gt=([0-9]*)/m'; - preg_match_all($guestTokenRegex, $pageContent['header'], $guestTokenMatches, PREG_SET_ORDER, 0); - if (!$guestTokenMatches) - preg_match_all($guestTokenRegex, $pageContent['content'], $guestTokenMatches, PREG_SET_ORDER, 0); - if (!$guestTokenMatches) return null; - $guestToken = $guestTokenMatches[0][1]; + try { + $pageContent = getContents('https://api.twitter.com/1.1/guest/activate.json', $headers, $opts, true); + $guestToken = json_decode($pageContent['content'])->guest_token; + } catch (Exception $e) { + $guestToken = null; + } return $guestToken; }