3 * Name: Bluesky Connector
4 * Description: Post to Bluesky
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 * Currently technical issues in the core:
12 * At some point in time:
13 * - Sending Quote shares https://atproto.com/lexicons/app-bsky-embed#appbskyembedrecord and https://atproto.com/lexicons/app-bsky-embed#appbskyembedrecordwithmedia
15 * Possibly not possible:
16 * - only fetch new posts
18 * Currently not possible, due to limitations in Friendica
19 * - mute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphmuteactor
20 * - unmute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphunmuteactor
22 * Possibly interesting:
23 * - https://atproto.com/lexicons/com-atproto-label#comatprotolabelsubscribelabels
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Content\Text\Plaintext;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Config\Util\ConfigFileManager;
31 use Friendica\Core\Hook;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Renderer;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Photo;
42 use Friendica\Model\Post;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Relay;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Strings;
50 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
51 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
53 function bluesky_install()
55 Hook::register('load_config', __FILE__, 'bluesky_load_config');
56 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
57 Hook::register('post_local', __FILE__, 'bluesky_post_local');
58 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
59 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
60 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
61 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
62 Hook::register('cron', __FILE__, 'bluesky_cron');
63 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
64 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
65 Hook::register('follow', __FILE__, 'bluesky_follow');
66 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
67 Hook::register('block', __FILE__, 'bluesky_block');
68 Hook::register('unblock', __FILE__, 'bluesky_unblock');
69 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
70 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
71 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
74 function bluesky_load_config(ConfigFileManager $loader)
76 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
79 function bluesky_check_item_notification(array &$notification_data)
81 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
84 $notification_data['profiles'][] = $did;
88 function bluesky_probe_detect(array &$hookData)
90 // Don't overwrite an existing result
91 if (isset($hookData['result'])) {
95 // Avoid a lookup for the wrong network
96 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
100 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
101 if (empty($pconfig['uid'])) {
105 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
106 $did = $hookData['uri'];
107 } elseif (preg_match('#^' . BLUESKY_HOST . '/profile/(.+)#', $hookData['uri'], $matches)) {
108 $did = bluesky_get_did($pconfig['uid'], $matches[1]);
116 $token = bluesky_get_token($pconfig['uid']);
121 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
126 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
128 // Preparing probe data. This differs slightly from the contact array
129 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
130 $hookData['result']['photo'] = $data->avatar ?? '';
131 $hookData['result']['header'] = $data->banner ?? '';
132 $hookData['result']['batch'] = '';
133 $hookData['result']['notify'] = '';
134 $hookData['result']['poll'] = '';
135 $hookData['result']['poco'] = '';
136 $hookData['result']['pubkey'] = '';
137 $hookData['result']['priority'] = 0;
138 $hookData['result']['guid'] = '';
141 function bluesky_item_by_link(array &$hookData)
143 // Don't overwrite an existing result
144 if (isset($hookData['item_id'])) {
148 $token = bluesky_get_token($hookData['uid']);
153 if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
157 $did = bluesky_get_did($hookData['uid'], $matches[1]);
162 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
164 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
166 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, 0);
167 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
169 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
170 if (!empty($item['id'])) {
171 $hookData['item_id'] = $item['id'];
176 function bluesky_support_follow(array &$data)
178 if ($data['protocol'] == Protocol::BLUESKY) {
179 $data['result'] = true;
183 function bluesky_support_probe(array &$data)
185 if ($data['protocol'] == Protocol::BLUESKY) {
186 $data['result'] = true;
190 function bluesky_follow(array &$hook_data)
192 $token = bluesky_get_token($hook_data['uid']);
197 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
198 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
199 if (empty($contact)) {
204 'subject' => $contact['url'],
205 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
206 '$type' => 'app.bsky.graph.follow'
210 'collection' => 'app.bsky.graph.follow',
211 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
215 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
216 if (!empty($activity->uri)) {
217 $hook_data['contact'] = $contact;
218 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
222 function bluesky_unfollow(array &$hook_data)
224 $token = bluesky_get_token($hook_data['uid']);
229 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
233 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
234 if (empty($data->viewer) || empty($data->viewer->following)) {
238 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
240 $hook_data['result'] = true;
243 function bluesky_block(array &$hook_data)
245 $token = bluesky_get_token($hook_data['uid']);
250 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
251 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
252 if (empty($contact)) {
257 'subject' => $contact['url'],
258 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
259 '$type' => 'app.bsky.graph.block'
263 'collection' => 'app.bsky.graph.block',
264 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
268 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
269 if (!empty($activity->uri)) {
270 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
271 if (!empty($cdata['user'])) {
272 Contact::remove($cdata['user']);
274 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
278 function bluesky_unblock(array &$hook_data)
280 $token = bluesky_get_token($hook_data['uid']);
285 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
289 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
290 if (empty($data->viewer) || empty($data->viewer->blocking)) {
294 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
296 $hook_data['result'] = true;
299 function bluesky_settings(array &$data)
301 if (!DI::userSession()->getLocalUserId()) {
305 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
306 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
307 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
308 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
309 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
310 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
311 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
312 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
314 $status = $token ? DI::l10n()->t("You are authenticated to Bluesky. For security reasons the password isn't stored.") : DI::l10n()->t('You are not authenticated. Please enter the app password.');
316 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
317 $html = Renderer::replaceMacros($t, [
318 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
319 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
320 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
321 '$import_feeds' => ['bluesky_import_feeds', DI::l10n()->t('Import the pinned feeds'), $import_feeds, DI::l10n()->t('When activated, Posts will be imported from all the feeds that you pinned in Bluesky.')],
322 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
323 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
324 '$did' => ['bluesky_did', DI::l10n()->t('Bluesky DID'), $did, DI::l10n()->t('This is the unique identifier. It will be fetched automatically, when the handle is entered.'), '', 'readonly'],
325 '$password' => ['bluesky_password', DI::l10n()->t('Bluesky app password'), '', DI::l10n()->t("Please don't add your real password here, but instead create a specific app password in the Bluesky settings.")],
330 'connector' => 'bluesky',
331 'title' => DI::l10n()->t('Bluesky Import/Export'),
332 'image' => 'images/bluesky.jpg',
333 'enabled' => $enabled,
338 function bluesky_settings_post(array &$b)
340 if (empty($_POST['bluesky-submit'])) {
344 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
345 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
346 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
348 $host = $_POST['bluesky_host'];
349 $handle = $_POST['bluesky_handle'];
351 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
352 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
353 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
354 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
355 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
356 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
358 if (!empty($host) && !empty($handle)) {
359 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
360 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
363 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
366 if (!empty($_POST['bluesky_password'])) {
367 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
371 function bluesky_jot_nets(array &$jotnets_fields)
373 if (!DI::userSession()->getLocalUserId()) {
377 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
378 $jotnets_fields[] = [
379 'type' => 'checkbox',
382 DI::l10n()->t('Post to Bluesky'),
383 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
389 function bluesky_cron()
391 $last = DI::keyValue()->get('bluesky_last_poll');
393 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
394 if (!$poll_interval) {
395 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
399 $next = $last + ($poll_interval * 60);
400 if ($next > time()) {
401 Logger::notice('poll interval not reached');
405 Logger::notice('cron_start');
407 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
408 if ($abandon_days < 1) {
412 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
414 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
415 foreach ($pconfigs as $pconfig) {
416 if ($abandon_days != 0) {
417 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
418 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
423 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
424 bluesky_get_token($pconfig['uid']);
426 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
427 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
429 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
430 $feeds = bluesky_get_feeds($pconfig['uid']);
431 foreach ($feeds as $feed) {
432 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
437 $last_clean = DI::keyValue()->get('bluesky_last_clean');
438 if (empty($last_clean) || ($last_clean + 86400 < time())) {
439 Logger::notice('Start contact cleanup');
440 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
441 while ($contact = DBA::fetch($contacts)) {
442 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
444 DBA::close($contacts);
445 DI::keyValue()->set('bluesky_last_clean', time());
446 Logger::notice('Contact cleanup done');
449 Logger::notice('cron_end');
451 DI::keyValue()->set('bluesky_last_poll', time());
454 function bluesky_hook_fork(array &$b)
456 if ($b['name'] != 'notifier_normal') {
462 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
463 DI::logger()->info('Editing is not supported by the addon');
464 $b['execute'] = false;
468 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
469 // Don't post if it isn't a reply to a bluesky post
470 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
471 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
472 $b['execute'] = false;
475 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
476 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
477 $b['execute'] = false;
482 function bluesky_post_local(array &$b)
488 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
492 if ($b['private'] || $b['parent']) {
496 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
497 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
499 // if API is used, default to the chosen settings
500 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
504 if (!$bluesky_enable) {
508 if (strlen($b['postopts'])) {
509 $b['postopts'] .= ',';
512 $b['postopts'] .= 'bluesky';
515 function bluesky_send(array &$b)
517 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
521 if ($b['gravity'] != Item::GRAVITY_PARENT) {
522 Logger::debug('Got comment', ['item' => $b]);
525 $uri = bluesky_get_uri_class($b['uri']);
527 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
530 bluesky_delete_post($b['uri'], $b['uid']);
534 $root = bluesky_get_uri_class($b['parent-uri']);
535 $parent = bluesky_get_uri_class($b['thr-parent']);
537 if (empty($root) || empty($parent)) {
538 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
542 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
543 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
544 bluesky_create_post($b, $root, $parent);
546 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
547 bluesky_create_activity($b, $parent);
550 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
554 bluesky_create_post($b);
557 function bluesky_create_activity(array $item, stdClass $parent = null)
560 $token = bluesky_get_token($uid);
565 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
567 if ($item['verb'] == Activity::LIKE) {
569 'subject' => $parent,
570 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
571 '$type' => 'app.bsky.feed.like'
575 'collection' => 'app.bsky.feed.like',
579 } elseif ($item['verb'] == Activity::ANNOUNCE) {
581 'subject' => $parent,
582 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
583 '$type' => 'app.bsky.feed.repost'
587 'collection' => 'app.bsky.feed.repost',
593 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
594 if (empty($activity)) {
597 Logger::debug('Activity done', ['return' => $activity]);
598 $uri = bluesky_get_uri($activity);
599 Item::update(['extid' => $uri], ['id' => $item['id']]);
600 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
603 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
606 $token = bluesky_get_token($uid);
611 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
612 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
613 $item['body'] = $urls['body'];
615 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
616 foreach ($msg['parts'] as $key => $part) {
618 $facets = bluesky_get_facets($part, $urls['urls']);
621 'text' => $facets['body'],
622 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
623 '$type' => 'app.bsky.feed.post'
626 if (!empty($facets['facets'])) {
627 $record['facets'] = $facets['facets'];
631 $record['reply'] = ['root' => $root, 'parent' => $parent];
634 if ($key == count($msg['parts']) - 1) {
635 $record = bluesky_add_embed($uid, $msg, $record);
639 'collection' => 'app.bsky.feed.post',
644 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
645 if (empty($parent)) {
648 Logger::debug('Posting done', ['return' => $parent]);
652 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
653 $uri = bluesky_get_uri($parent);
654 Item::update(['extid' => $uri], ['id' => $item['id']]);
655 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
660 function bluesky_get_urls(string $body): array
662 // Remove all hashtag and mention links
663 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
667 // Search for pure links
668 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
669 foreach ($matches as $match) {
670 $text = Strings::getStyledURL($match[1]);
671 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
672 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
673 $body = str_replace($match[0], $hash, $body);
677 // Search for links with descriptions
678 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
679 foreach ($matches as $match) {
680 if ($match[1] == $match[2]) {
681 $text = Strings::getStyledURL($match[1]);
685 if (mb_strlen($text) < 100) {
686 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
687 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
688 $body = str_replace($match[0], $hash, $body);
690 $text = Strings::getStyledURL($match[1]);
691 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
692 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
693 $body = str_replace($match[0], $text . ' ' . $hash, $body);
698 return ['body' => $body, 'urls' => $urls];
701 function bluesky_get_hash_for_url(string $text, int $linklength): string
703 if ($linklength <= 10) {
704 return '|' . hash('crc32', $text) . '|';
706 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
709 function bluesky_get_facets(string $body, array $urls): array
713 foreach ($urls as $url) {
714 $pos = strpos($body, $url['hash']);
715 if ($pos === false) {
719 $prefix = substr($body, 0, $pos);
724 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
726 $facet = new stdClass;
727 $facet->index = new stdClass;
728 $facet->index->byteEnd = $pos + strlen($url['text']);
729 $facet->index->byteStart = $pos;
731 $feature = new stdClass;
732 $feature->uri = $url['url'];
734 $feature->$type = 'app.bsky.richtext.facet#link';
736 $facet->features = [$feature];
740 return ['facets' => $facets, 'body' => $body];
743 function bluesky_add_embed(int $uid, array $msg, array $record): array
745 if (($msg['type'] != 'link') && !empty($msg['images'])) {
747 foreach ($msg['images'] as $image) {
748 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
749 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
750 $blob = bluesky_upload_blob($uid, $photo);
751 if (!empty($blob) && count($images) < 4) {
752 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
755 if (!empty($images)) {
756 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
758 } elseif ($msg['type'] == 'link') {
760 '$type' => 'app.bsky.embed.external',
762 'uri' => $msg['url'],
763 'title' => $msg['title'],
764 'description' => $msg['description'],
767 if (!empty($msg['image'])) {
768 $photo = Photo::createPhotoForExternalResource($msg['image']);
769 $blob = bluesky_upload_blob($uid, $photo);
771 $record['embed']['external']['thumb'] = $blob;
778 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
780 $content = Photo::getImageForPhoto($photo);
781 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
786 Logger::debug('Uploaded blob', ['return' => $data]);
790 function bluesky_delete_post(string $uri, int $uid)
792 $parts = bluesky_get_uri_parts($uri);
794 Logger::debug('No uri delected', ['uri' => $uri]);
797 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
798 Logger::debug('Deleted', ['parts' => $parts]);
801 function bluesky_fetch_timeline(int $uid)
803 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
808 if (empty($data->feed)) {
812 foreach (array_reverse($data->feed) as $entry) {
813 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
814 if (!empty($entry->reason)) {
815 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
819 // @todo Support paging
820 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
823 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
826 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
830 $contact = bluesky_get_contact($reason->by, $uid, $uid);
833 'network' => Protocol::BLUESKY,
836 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
837 'private' => Item::UNLISTED,
838 'verb' => Activity::POST,
839 'contact-id' => $contact['id'],
840 'author-name' => $contact['name'],
841 'author-link' => $contact['url'],
842 'author-avatar' => $contact['avatar'],
843 'verb' => Activity::ANNOUNCE,
844 'body' => Activity::ANNOUNCE,
845 'gravity' => Item::GRAVITY_ACTIVITY,
846 'object-type' => Activity\ObjectType::NOTE,
847 'thr-parent' => $uri,
850 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
854 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
855 $item['owner-name'] = $item['author-name'];
856 $item['owner-link'] = $item['author-link'];
857 $item['owner-avatar'] = $item['author-avatar'];
858 if (Item::insert($item)) {
859 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
860 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
864 function bluesky_fetch_notifications(int $uid)
866 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
867 if (empty($data->notifications)) {
870 foreach ($data->notifications as $notification) {
871 $uri = bluesky_get_uri($notification);
872 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
873 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
876 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
877 switch ($notification->reason) {
879 $item = bluesky_get_header($notification, $uri, $uid, $uid);
880 $item['gravity'] = Item::GRAVITY_ACTIVITY;
881 $item['body'] = $item['verb'] = Activity::LIKE;
882 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
883 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
884 if (!empty($item['thr-parent'])) {
885 $data = Item::insert($item);
886 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
888 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $$item['thr-parent'], 'uri' => $uri]);
893 $item = bluesky_get_header($notification, $uri, $uid, $uid);
894 $item['gravity'] = Item::GRAVITY_ACTIVITY;
895 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
896 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
897 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
898 if (!empty($item['thr-parent'])) {
899 $data = Item::insert($item);
900 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
902 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $$item['thr-parent'], 'uri' => $uri]);
907 $contact = bluesky_get_contact($notification->author, $uid, $uid);
908 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
912 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
913 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
917 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
918 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
922 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
923 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
927 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
933 function bluesky_fetch_feed(int $uid, string $feed)
935 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
940 if (empty($data->feed)) {
944 foreach (array_reverse($data->feed) as $entry) {
945 if (!Relay::isWantedLanguage($entry->post->record->text)) {
946 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
949 bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
950 if (!empty($entry->reason)) {
951 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
956 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
958 $uri = bluesky_get_uri($post);
960 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
964 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
966 $item = bluesky_get_header($post, $uri, $uid, $uid);
967 $item = bluesky_get_content($item, $post->record, $uri, $uid, $level);
972 if (!empty($post->embed)) {
973 $item = bluesky_add_media($post->embed, $item, $uid, $level);
976 if (empty($item['post-reason'])) {
977 $item['post-reason'] = $post_reason;
980 return item::insert($item);
983 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
985 $parts = bluesky_get_uri_parts($uri);
986 if (empty($post->author)) {
989 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
991 'network' => Protocol::BLUESKY,
995 'guid' => $post->cid,
996 'private' => Item::UNLISTED,
997 'verb' => Activity::POST,
998 'contact-id' => $contact['id'],
999 'author-name' => $contact['name'],
1000 'author-link' => $contact['url'],
1001 'author-avatar' => $contact['avatar'],
1002 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1005 $item['uri-id'] = ItemURI::getIdByURI($uri);
1006 $item['owner-name'] = $item['author-name'];
1007 $item['owner-link'] = $item['author-link'];
1008 $item['owner-avatar'] = $item['author-avatar'];
1010 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1011 $item['post-reason'] = Item::PR_FOLLOWER;
1017 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $level): array
1023 if (!empty($record->reply)) {
1024 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1025 if ($item['parent-uri'] != $uri) {
1026 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id'], $level);
1027 if (empty($item['parent-uri'])) {
1032 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1033 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1034 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], $level, $item['parent-uri']);
1035 if (empty($item['thr-parent'])) {
1041 $item['body'] = bluesky_get_text($record);
1042 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1046 function bluesky_get_text(stdClass $record): string
1048 $text = $record->text;
1050 if (empty($record->facets)) {
1055 foreach ($record->facets as $facet) {
1056 $facets[$facet->index->byteStart] = $facet;
1060 foreach ($facets as $facet) {
1061 $prefix = substr($text, 0, $facet->index->byteStart);
1062 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1063 $suffix = substr($text, $facet->index->byteEnd);
1067 foreach ($facet->features as $feature) {
1069 switch ($feature->$type) {
1070 case 'app.bsky.richtext.facet#link':
1071 $url = $feature->uri;
1074 case 'app.bsky.richtext.facet#mention':
1075 $contact = Contact::getByURL($feature->did, null, ['id']);
1076 if (!empty($contact['id'])) {
1077 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1078 if (substr($linktext, 0, 1) == '@') {
1080 $linktext = substr($linktext, 1);
1086 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1091 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1097 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1100 switch ($embed->$type) {
1101 case 'app.bsky.embed.images#view':
1102 foreach ($embed->images as $image) {
1104 'uri-id' => $item['uri-id'],
1105 'type' => Post\Media::IMAGE,
1106 'url' => $image->fullsize,
1107 'preview' => $image->thumb,
1108 'description' => $image->alt,
1110 Post\Media::insert($media);
1114 case 'app.bsky.embed.external#view':
1116 'uri-id' => $item['uri-id'],
1117 'type' => Post\Media::HTML,
1118 'url' => $embed->external->uri,
1119 'name' => $embed->external->title,
1120 'description' => $embed->external->description,
1122 Post\Media::insert($media);
1125 case 'app.bsky.embed.record#view':
1126 $uri = bluesky_get_uri($embed->record);
1127 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1128 if (empty($shared)) {
1129 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1130 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1131 if (!empty($shared)) {
1132 if (!empty($embed->record->embeds)) {
1133 foreach ($embed->record->embeds as $single) {
1134 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1137 $id = Item::insert($shared);
1138 $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1141 if (!empty($shared)) {
1142 $item['quote-uri-id'] = $shared['uri-id'];
1146 case 'app.bsky.embed.recordWithMedia#view':
1147 $uri = bluesky_get_uri($embed->record->record);
1148 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1149 if (empty($shared)) {
1150 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1151 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1152 if (!empty($shared)) {
1153 if (!empty($embed->record->embeds)) {
1154 foreach ($embed->record->record->embeds as $single) {
1155 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1159 if (!empty($embed->media)) {
1160 bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1163 $id = Item::insert($shared);
1164 $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1167 if (!empty($shared)) {
1168 $item['quote-uri-id'] = $shared['uri-id'];
1173 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1179 function bluesky_get_uri(stdClass $post): string
1181 return $post->uri . ':' . $post->cid;
1184 function bluesky_get_uri_class(string $uri): ?stdClass
1190 $elements = explode(':', $uri);
1191 if (empty($elements) || ($elements[0] != 'at')) {
1192 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1193 return bluesky_get_uri_class($post['extid'] ?? '');
1196 $class = new stdClass;
1198 $class->cid = array_pop($elements);
1199 $class->uri = implode(':', $elements);
1201 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1202 $class->uri .= ':' . $class->cid;
1209 function bluesky_get_uri_parts(string $uri): ?stdClass
1211 $class = bluesky_get_uri_class($uri);
1212 if (empty($class)) {
1216 $parts = explode('/', substr($class->uri, 5));
1218 $class = new stdClass;
1220 $class->repo = $parts[0];
1221 $class->collection = $parts[1];
1222 $class->rkey = $parts[2];
1227 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1229 $fetched_uri = bluesky_fetch_post($uri, $uid);
1230 if (!empty($fetched_uri)) {
1231 return $fetched_uri;
1234 if (++$level > 100) {
1235 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1236 // When the level is too deep we will fallback to the parent uri.
1237 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1241 $class = bluesky_get_uri_class($uri);
1242 $fetch_uri = $class->uri;
1244 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1245 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1247 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1251 Logger::debug('Reply count', ['replies' => $data->thread->post->replyCount, 'level' => $level, 'uid' => $uid, 'uri' => $uri]);
1254 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1259 return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1262 function bluesky_fetch_post(string $uri, int $uid): string
1264 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1265 Logger::debug('Post exists', ['uri' => $uri]);
1269 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1270 if (!empty($reply['uri'])) {
1271 Logger::debug('Post with extid exists', ['uri' => $uri]);
1272 return $reply['uri'];
1277 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1279 $uri = bluesky_get_uri($thread->post);
1280 $fetched_uri = bluesky_fetch_post($uri, $uid);
1281 if (empty($fetched_uri)) {
1282 Logger::debug('Process missing post', ['uri' => $uri]);
1283 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1284 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1285 if (!empty($item)) {
1286 $item['post-reason'] = Item::PR_FETCHED;
1288 if (!empty($cdata['public'])) {
1289 $item['causer-id'] = $cdata['public'];
1292 if (!empty($thread->post->embed)) {
1293 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1295 $id = Item::insert($item);
1297 Logger::info('Item has not not been stored', ['uri' => $uri]);
1300 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1302 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1306 Logger::debug('Post exists', ['uri' => $uri]);
1307 $uri = $fetched_uri;
1310 foreach ($thread->replies ?? [] as $reply) {
1311 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1312 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1318 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1320 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1321 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1323 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1325 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1327 $public_fields['uid'] = 0;
1328 $public_fields['rel'] = Contact::NOTHING;
1330 if (empty($contact)) {
1331 $cid = Contact::insert($public_fields);
1333 $cid = $contact['id'];
1334 Contact::update($public_fields, ['id' => $cid], true);
1338 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1340 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1341 if (!isset($fields['rel']) && isset($contact['rel'])) {
1342 $fields['rel'] = $contact['rel'];
1343 } elseif (!isset($fields['rel'])) {
1344 $fields['rel'] = Contact::NOTHING;
1348 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1349 if (empty($contact)) {
1350 $cid = Contact::insert($fields);
1352 $cid = $contact['id'];
1353 Contact::update($fields, ['id' => $cid], true);
1355 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1357 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1359 if (!empty($author->avatar)) {
1360 Contact::updateAvatar($cid, $author->avatar);
1363 return Contact::getById($cid);
1366 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1370 'network' => Protocol::BLUESKY,
1374 'readonly' => false,
1376 'baseurl' => BLUESKY_HOST,
1377 'url' => $author->did,
1378 'nurl' => $author->did,
1379 'alias' => BLUESKY_HOST . '/profile/' . $author->handle,
1380 'name' => $author->displayName ?? $author->handle,
1381 'nick' => $author->handle,
1382 'addr' => $author->handle,
1386 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1390 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1392 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1396 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1398 if (!empty($data->description)) {
1399 $fields['about'] = HTML::toBBCode($data->description);
1402 if (!empty($data->banner)) {
1403 $fields['header'] = $data->banner;
1406 if (!empty($data->viewer)) {
1407 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1408 $fields['rel'] = Contact::FRIEND;
1409 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1410 $fields['rel'] = Contact::SHARING;
1411 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1412 $fields['rel'] = Contact::FOLLOWER;
1414 $fields['rel'] = Contact::NOTHING;
1418 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1422 function bluesky_get_feeds(int $uid): array
1425 $preferences = bluesky_get_preferences($uid);
1426 foreach ($preferences->preferences as $preference) {
1427 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1428 return $preference->pinned ?? [];
1434 function bluesky_get_preferences(int $uid): stdClass
1436 $cachekey = 'bluesky:preferences:' . $uid;
1437 $data = DI::cache()->get($cachekey);
1438 if (!is_null($data)) {
1442 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1444 DI::cache()->set($cachekey, $data, Duration::HOUR);
1448 function bluesky_get_did(int $uid, string $handle): string
1450 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1454 Logger::debug('Got DID', ['return' => $data]);
1458 function bluesky_get_token(int $uid): string
1460 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1461 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1462 if (empty($token)) {
1466 if ($created + 300 < time()) {
1467 return bluesky_refresh_token($uid);
1472 function bluesky_refresh_token(int $uid): string
1474 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1476 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1481 Logger::debug('Refreshed token', ['return' => $data]);
1482 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1483 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1484 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1485 return $data->accessJwt;
1488 function bluesky_create_token(int $uid, string $password): string
1490 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1492 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1497 Logger::debug('Created token', ['return' => $data]);
1498 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1499 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1500 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1501 return $data->accessJwt;
1504 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1506 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1509 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1512 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1513 } catch (\Exception $e) {
1514 Logger::notice('Exception on post', ['exception' => $e]);
1518 if (!$curlResult->isSuccess()) {
1519 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1523 return json_decode($curlResult->getBody());
1526 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1528 if (!empty($parameters)) {
1529 $url .= '?' . http_build_query($parameters);
1532 return bluesky_get($uid, '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1535 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1538 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1539 } catch (\Exception $e) {
1540 Logger::notice('Exception on get', ['exception' => $e]);
1544 if (!$curlResult->isSuccess()) {
1545 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1549 return json_decode($curlResult->getBody());