Skip to content

Commit 5bd767b

Browse files
authored
[TikTokBridge] Use oEmbed for video metadata (#4514)
* [TikTokBridge] Use oEmbed for video metadata Fetches oEmbed-formatted metadata for videos through the TikTok API to provide post titles, thumbnails, and authors. This hasn't yet been tested, so it's possible it doesn't work. * [TikTokBridge] Add back view count parsing oops * [TikTokBridge] Prepend www to the oEmbed API endpoint URL The non-www URL resulted in a 301 redirect to the www URL, so this just skips that redirect, improving performance a bit and hopefully helping with the 400 errors. * [TikTokBridge] Retry failed OEmbed requests If an OEmbed request fails, retry a few times, waiting a bit in between each retry. This should fix the problem for the most part, since I think the problem was related to some sort of rate limit (it isn't mentioned in the docs, but it seems to only happen when sending large quantities of sequential requests).
1 parent 72e1998 commit 5bd767b

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed

bridges/TikTokBridge.php

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ class TikTokBridge extends BridgeAbstract
2121
'context' => 'By user', 'username' => '@tiktok'
2222
]
2323
];
24+
const OEMBED_RETRY_COUNT = 20;
25+
const OEMBED_RETRY_DELAY = 0.1;
2426

2527
const CACHE_TIMEOUT = 900; // 15 minutes
2628

@@ -42,16 +44,33 @@ public function collectData()
4244
$parsedUrl = parse_url($href);
4345
$url = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/' . ltrim($parsedUrl['path'], '/');
4446

45-
$image = $video->find('video', 0)->poster;
47+
// Sometimes the API fails to return data for a second, so try a few times
48+
$attempts = 0;
49+
do {
50+
try {
51+
// Fetch the video embed data from the OEmbed API
52+
$videoEmbedResponse = getContents('https://www.tiktok.com/oembed?url=' . $url);
53+
} catch (Exception $e) {
54+
$attempts++;
55+
sleep($OEMBED_RETRY_DELAY);
56+
continue;
57+
}
58+
break;
59+
} while($attempts < $OEMBED_RETRY_COUNT);
60+
$videoEmbedData = json_decode($videoEmbedResponse);
61+
62+
$title = $videoEmbedData->title;
63+
$image = $videoEmbedData->thumbnail_url;
4664
$views = $video->find('div[data-e2e=common-Video-Count]', 0)->plaintext;
4765

4866
$enclosures = [$image, $authorProfilePicture];
4967

5068
$item['uri'] = $url;
51-
$item['title'] = 'Video';
52-
$item['author'] = '@' . $author;
69+
$item['title'] = $title;
70+
$item['author'] = '@' . $videoEmbedData->author_unique_id;
5371
$item['enclosures'] = $enclosures;
5472
$item['content'] = <<<EOD
73+
<p>$title</p>
5574
<a href="{$url}"><img src="{$image}"/></a>
5675
<p>{$views} views<p><br/>
5776
EOD;

0 commit comments

Comments
 (0)