|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Murdercode\LaravelShortcodePlus\Shortcodes; |
| 4 | + |
| 5 | +use GuzzleHttp\Client; |
| 6 | +use GuzzleHttp\Exception\GuzzleException; |
| 7 | +use GuzzleHttp\Exception\RequestException; |
| 8 | + |
| 9 | +class BlueskyShortcode |
| 10 | +{ |
| 11 | + public function register($shortcode): string |
| 12 | + { |
| 13 | + $url = $shortcode->url ?? ''; |
| 14 | + |
| 15 | + if (empty($url)) { |
| 16 | + return 'No bsky.app parameter url defined'; |
| 17 | + } |
| 18 | + |
| 19 | + if (str_contains($url, 'bsky.app') === false && str_contains($url, 'bsky.app') === false) { |
| 20 | + return 'No bsky.app URL defined'; |
| 21 | + } |
| 22 | + |
| 23 | + $html = self::getOembed($url) ?? null; |
| 24 | + |
| 25 | + if (!isset($html)) { |
| 26 | + return 'Cannot get bsky.app oEmbed'; |
| 27 | + } |
| 28 | + |
| 29 | + return view('shortcode-plus::bluesky', compact('html'))->render(); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Get oEmbed data from Twitter |
| 34 | + * Note: Twitter sometimes returns 404 for valid URLs, so we retry a few times |
| 35 | + * |
| 36 | + * @throws GuzzleException |
| 37 | + */ |
| 38 | + private static function getOembed(string $url): ?string |
| 39 | + { |
| 40 | + $maxAttempts = 3; |
| 41 | + $attempt = 0; |
| 42 | + $response = null; |
| 43 | + |
| 44 | + while ($attempt < $maxAttempts && $response === null) { |
| 45 | + try { |
| 46 | + $client = new Client; |
| 47 | + $res = $client->request('GET', 'https://embed.bsky.app/oembed', [ |
| 48 | + 'query' => [ |
| 49 | + 'url' => $url, |
| 50 | + ], |
| 51 | + ]); |
| 52 | + |
| 53 | + if ($res->getStatusCode() == 200) { |
| 54 | + $response = $res->getBody()->getContents(); |
| 55 | + } else { |
| 56 | + usleep(100000); |
| 57 | + $attempt++; |
| 58 | + } |
| 59 | + } catch (RequestException $e) { |
| 60 | + usleep(100000); |
| 61 | + $attempt++; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + if ($response === null) { |
| 66 | + return null; |
| 67 | + } |
| 68 | + |
| 69 | + $data = json_decode($response, true); |
| 70 | + |
| 71 | + return $data['html'] ?? null; |
| 72 | + } |
| 73 | +} |
0 commit comments