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\Object\Image;
46 use Friendica\Protocol\Activity;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Strings;
51 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
52 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
53 const BLUESKY_IMAGE_SIZE = [1000000, 500000, 100000, 50000];
55 function bluesky_install()
57 Hook::register('load_config', __FILE__, 'bluesky_load_config');
58 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
59 Hook::register('post_local', __FILE__, 'bluesky_post_local');
60 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
61 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
62 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
63 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
64 Hook::register('cron', __FILE__, 'bluesky_cron');
65 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
66 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
67 Hook::register('follow', __FILE__, 'bluesky_follow');
68 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
69 Hook::register('block', __FILE__, 'bluesky_block');
70 Hook::register('unblock', __FILE__, 'bluesky_unblock');
71 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
72 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
73 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
76 function bluesky_load_config(ConfigFileManager $loader)
78 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
81 function bluesky_check_item_notification(array &$notification_data)
83 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
86 $notification_data['profiles'][] = $did;
90 function bluesky_probe_detect(array &$hookData)
92 // Don't overwrite an existing result
93 if (isset($hookData['result'])) {
97 // Avoid a lookup for the wrong network
98 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
102 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
103 if (empty($pconfig['uid'])) {
107 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
108 $did = $hookData['uri'];
109 } elseif (preg_match('#^' . BLUESKY_HOST . '/profile/(.+)#', $hookData['uri'], $matches)) {
110 $did = bluesky_get_did($pconfig['uid'], $matches[1]);
118 $token = bluesky_get_token($pconfig['uid']);
123 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
128 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
130 // Preparing probe data. This differs slightly from the contact array
131 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
132 $hookData['result']['photo'] = $data->avatar ?? '';
133 $hookData['result']['header'] = $data->banner ?? '';
134 $hookData['result']['batch'] = '';
135 $hookData['result']['notify'] = '';
136 $hookData['result']['poll'] = '';
137 $hookData['result']['poco'] = '';
138 $hookData['result']['pubkey'] = '';
139 $hookData['result']['priority'] = 0;
140 $hookData['result']['guid'] = '';
143 function bluesky_item_by_link(array &$hookData)
145 // Don't overwrite an existing result
146 if (isset($hookData['item_id'])) {
150 $token = bluesky_get_token($hookData['uid']);
155 if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
159 $did = bluesky_get_did($hookData['uid'], $matches[1]);
164 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
166 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
168 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, 0);
169 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
171 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
172 if (!empty($item['id'])) {
173 $hookData['item_id'] = $item['id'];
178 function bluesky_support_follow(array &$data)
180 if ($data['protocol'] == Protocol::BLUESKY) {
181 $data['result'] = true;
185 function bluesky_support_probe(array &$data)
187 if ($data['protocol'] == Protocol::BLUESKY) {
188 $data['result'] = true;
192 function bluesky_follow(array &$hook_data)
194 $token = bluesky_get_token($hook_data['uid']);
199 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
200 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
201 if (empty($contact)) {
206 'subject' => $contact['url'],
207 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
208 '$type' => 'app.bsky.graph.follow'
212 'collection' => 'app.bsky.graph.follow',
213 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
217 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
218 if (!empty($activity->uri)) {
219 $hook_data['contact'] = $contact;
220 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
224 function bluesky_unfollow(array &$hook_data)
226 $token = bluesky_get_token($hook_data['uid']);
231 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
235 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
236 if (empty($data->viewer) || empty($data->viewer->following)) {
240 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
242 $hook_data['result'] = true;
245 function bluesky_block(array &$hook_data)
247 $token = bluesky_get_token($hook_data['uid']);
252 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
253 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
254 if (empty($contact)) {
259 'subject' => $contact['url'],
260 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
261 '$type' => 'app.bsky.graph.block'
265 'collection' => 'app.bsky.graph.block',
266 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
270 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
271 if (!empty($activity->uri)) {
272 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
273 if (!empty($cdata['user'])) {
274 Contact::remove($cdata['user']);
276 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
280 function bluesky_unblock(array &$hook_data)
282 $token = bluesky_get_token($hook_data['uid']);
287 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
291 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
292 if (empty($data->viewer) || empty($data->viewer->blocking)) {
296 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
298 $hook_data['result'] = true;
301 function bluesky_settings(array &$data)
303 if (!DI::userSession()->getLocalUserId()) {
307 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
308 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
309 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
310 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
311 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
312 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
313 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
314 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
316 $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.');
318 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
319 $html = Renderer::replaceMacros($t, [
320 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
321 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
322 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
323 '$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.')],
324 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
325 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
326 '$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'],
327 '$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.")],
332 'connector' => 'bluesky',
333 'title' => DI::l10n()->t('Bluesky Import/Export'),
334 'image' => 'images/bluesky.jpg',
335 'enabled' => $enabled,
340 function bluesky_settings_post(array &$b)
342 if (empty($_POST['bluesky-submit'])) {
346 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
347 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
348 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
350 $host = $_POST['bluesky_host'];
351 $handle = $_POST['bluesky_handle'];
353 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
354 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
355 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
356 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
357 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
358 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
360 if (!empty($host) && !empty($handle)) {
361 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
362 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
365 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
368 if (!empty($_POST['bluesky_password'])) {
369 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
373 function bluesky_jot_nets(array &$jotnets_fields)
375 if (!DI::userSession()->getLocalUserId()) {
379 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
380 $jotnets_fields[] = [
381 'type' => 'checkbox',
384 DI::l10n()->t('Post to Bluesky'),
385 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
391 function bluesky_cron()
393 $last = DI::keyValue()->get('bluesky_last_poll');
395 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
396 if (!$poll_interval) {
397 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
401 $next = $last + ($poll_interval * 60);
402 if ($next > time()) {
403 Logger::notice('poll interval not reached');
407 Logger::notice('cron_start');
409 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
410 if ($abandon_days < 1) {
414 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
416 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
417 foreach ($pconfigs as $pconfig) {
418 if ($abandon_days != 0) {
419 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
420 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
425 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
426 bluesky_get_token($pconfig['uid']);
428 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
429 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
431 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
432 $feeds = bluesky_get_feeds($pconfig['uid']);
433 foreach ($feeds as $feed) {
434 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
439 $last_clean = DI::keyValue()->get('bluesky_last_clean');
440 if (empty($last_clean) || ($last_clean + 86400 < time())) {
441 Logger::notice('Start contact cleanup');
442 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
443 while ($contact = DBA::fetch($contacts)) {
444 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
446 DBA::close($contacts);
447 DI::keyValue()->set('bluesky_last_clean', time());
448 Logger::notice('Contact cleanup done');
451 Logger::notice('cron_end');
453 DI::keyValue()->set('bluesky_last_poll', time());
456 function bluesky_hook_fork(array &$b)
458 if ($b['name'] != 'notifier_normal') {
464 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
465 DI::logger()->info('Editing is not supported by the addon');
466 $b['execute'] = false;
470 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
471 // Don't post if it isn't a reply to a bluesky post
472 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
473 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
474 $b['execute'] = false;
477 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
478 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
479 $b['execute'] = false;
484 function bluesky_post_local(array &$b)
490 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
494 if ($b['private'] || $b['parent']) {
498 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
499 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
501 // if API is used, default to the chosen settings
502 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
506 if (!$bluesky_enable) {
510 if (strlen($b['postopts'])) {
511 $b['postopts'] .= ',';
514 $b['postopts'] .= 'bluesky';
517 function bluesky_send(array &$b)
519 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
523 if ($b['gravity'] != Item::GRAVITY_PARENT) {
524 Logger::debug('Got comment', ['item' => $b]);
527 $uri = bluesky_get_uri_class($b['uri']);
529 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
532 bluesky_delete_post($b['uri'], $b['uid']);
536 $root = bluesky_get_uri_class($b['parent-uri']);
537 $parent = bluesky_get_uri_class($b['thr-parent']);
539 if (empty($root) || empty($parent)) {
540 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
544 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
545 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
546 bluesky_create_post($b, $root, $parent);
548 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
549 bluesky_create_activity($b, $parent);
552 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
556 bluesky_create_post($b);
559 function bluesky_create_activity(array $item, stdClass $parent = null)
562 $token = bluesky_get_token($uid);
567 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
569 if ($item['verb'] == Activity::LIKE) {
571 'subject' => $parent,
572 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
573 '$type' => 'app.bsky.feed.like'
577 'collection' => 'app.bsky.feed.like',
581 } elseif ($item['verb'] == Activity::ANNOUNCE) {
583 'subject' => $parent,
584 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
585 '$type' => 'app.bsky.feed.repost'
589 'collection' => 'app.bsky.feed.repost',
595 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
596 if (empty($activity)) {
599 Logger::debug('Activity done', ['return' => $activity]);
600 $uri = bluesky_get_uri($activity);
601 Item::update(['extid' => $uri], ['id' => $item['id']]);
602 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
605 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
608 $token = bluesky_get_token($uid);
613 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
614 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
615 $item['body'] = $urls['body'];
617 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
618 foreach ($msg['parts'] as $key => $part) {
620 $facets = bluesky_get_facets($part, $urls['urls']);
623 'text' => $facets['body'],
624 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
625 '$type' => 'app.bsky.feed.post'
628 if (!empty($facets['facets'])) {
629 $record['facets'] = $facets['facets'];
633 $record['reply'] = ['root' => $root, 'parent' => $parent];
636 if ($key == count($msg['parts']) - 1) {
637 $record = bluesky_add_embed($uid, $msg, $record);
638 if (empty($record)) {
639 if (Worker::getRetrial() < 3) {
647 'collection' => 'app.bsky.feed.post',
652 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
653 if (empty($parent)) {
659 Logger::debug('Posting done', ['return' => $parent]);
663 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
664 $uri = bluesky_get_uri($parent);
665 Item::update(['extid' => $uri], ['id' => $item['id']]);
666 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
671 function bluesky_get_urls(string $body): array
673 // Remove all hashtag and mention links
674 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
676 $body = BBCode::expandVideoLinks($body);
679 // Search for pure links
680 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
681 foreach ($matches as $match) {
682 $text = Strings::getStyledURL($match[1]);
683 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
684 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
685 $body = str_replace($match[0], $hash, $body);
689 // Search for links with descriptions
690 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
691 foreach ($matches as $match) {
692 if ($match[1] == $match[2]) {
693 $text = Strings::getStyledURL($match[1]);
697 if (mb_strlen($text) < 100) {
698 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
699 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
700 $body = str_replace($match[0], $hash, $body);
702 $text = Strings::getStyledURL($match[1]);
703 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
704 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
705 $body = str_replace($match[0], $text . ' ' . $hash, $body);
710 return ['body' => $body, 'urls' => $urls];
713 function bluesky_get_hash_for_url(string $text, int $linklength): string
715 if ($linklength <= 10) {
716 return '|' . hash('crc32', $text) . '|';
718 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
721 function bluesky_get_facets(string $body, array $urls): array
725 foreach ($urls as $url) {
726 $pos = strpos($body, $url['hash']);
727 if ($pos === false) {
731 $prefix = substr($body, 0, $pos);
736 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
738 $facet = new stdClass;
739 $facet->index = new stdClass;
740 $facet->index->byteEnd = $pos + strlen($url['text']);
741 $facet->index->byteStart = $pos;
743 $feature = new stdClass;
744 $feature->uri = $url['url'];
746 $feature->$type = 'app.bsky.richtext.facet#link';
748 $facet->features = [$feature];
752 return ['facets' => $facets, 'body' => $body];
755 function bluesky_add_embed(int $uid, array $msg, array $record): array
757 if (($msg['type'] != 'link') && !empty($msg['images'])) {
759 foreach ($msg['images'] as $image) {
760 if (count($images) == 4) {
763 $photo = Photo::selectFirst([], ['id' => $image['id']]);
764 $blob = bluesky_upload_blob($uid, $photo);
768 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
770 if (!empty($images)) {
771 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
773 } elseif ($msg['type'] == 'link') {
775 '$type' => 'app.bsky.embed.external',
777 'uri' => $msg['url'],
778 'title' => $msg['title'] ?? '',
779 'description' => $msg['description'] ?? '',
782 if (!empty($msg['image'])) {
783 $photo = Photo::createPhotoForExternalResource($msg['image']);
784 $blob = bluesky_upload_blob($uid, $photo);
786 $record['embed']['external']['thumb'] = $blob;
793 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
795 $retrial = Worker::getRetrial();
796 $content = Photo::getImageForPhoto($photo);
798 $picture = new Image($content, $photo['type']);
799 $height = $picture->getHeight();
800 $width = $picture->getWidth();
801 $size = strlen($content);
803 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
804 $new_height = $picture->getHeight();
805 $new_width = $picture->getWidth();
806 $content = $picture->asString();
807 $new_size = strlen($content);
809 Logger::info('Uploading', ['uid' => $uid, 'retrial' => $retrial, 'height' => $new_height, 'width' => $new_width, 'size' => $new_size, 'orig-height' => $height, 'orig-width' => $width, 'orig-size' => $size]);
811 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
813 Logger::info('Uploading failed', ['uid' => $uid, 'retrial' => $retrial, 'height' => $new_height, 'width' => $new_width, 'size' => $new_size, 'orig-height' => $height, 'orig-width' => $width, 'orig-size' => $size]);
817 Logger::debug('Uploaded blob', ['return' => $data, 'uid' => $uid, 'retrial' => $retrial, 'height' => $new_height, 'width' => $new_width, 'size' => $new_size, 'orig-height' => $height, 'orig-width' => $width, 'orig-size' => $size]);
821 function bluesky_delete_post(string $uri, int $uid)
823 $parts = bluesky_get_uri_parts($uri);
825 Logger::debug('No uri delected', ['uri' => $uri]);
828 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
829 Logger::debug('Deleted', ['parts' => $parts]);
832 function bluesky_fetch_timeline(int $uid)
834 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
839 if (empty($data->feed)) {
843 foreach (array_reverse($data->feed) as $entry) {
844 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
845 if (!empty($entry->reason)) {
846 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
850 // @todo Support paging
851 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
854 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
857 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
861 $contact = bluesky_get_contact($reason->by, $uid, $uid);
864 'network' => Protocol::BLUESKY,
867 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
868 'private' => Item::UNLISTED,
869 'verb' => Activity::POST,
870 'contact-id' => $contact['id'],
871 'author-name' => $contact['name'],
872 'author-link' => $contact['url'],
873 'author-avatar' => $contact['avatar'],
874 'verb' => Activity::ANNOUNCE,
875 'body' => Activity::ANNOUNCE,
876 'gravity' => Item::GRAVITY_ACTIVITY,
877 'object-type' => Activity\ObjectType::NOTE,
878 'thr-parent' => $uri,
881 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
885 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
886 $item['owner-name'] = $item['author-name'];
887 $item['owner-link'] = $item['author-link'];
888 $item['owner-avatar'] = $item['author-avatar'];
889 if (Item::insert($item)) {
890 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
891 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
895 function bluesky_fetch_notifications(int $uid)
897 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
898 if (empty($data->notifications)) {
901 foreach ($data->notifications as $notification) {
902 $uri = bluesky_get_uri($notification);
903 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
904 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
907 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
908 switch ($notification->reason) {
910 $item = bluesky_get_header($notification, $uri, $uid, $uid);
911 $item['gravity'] = Item::GRAVITY_ACTIVITY;
912 $item['body'] = $item['verb'] = Activity::LIKE;
913 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
914 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
915 if (!empty($item['thr-parent'])) {
916 $data = Item::insert($item);
917 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
919 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
924 $item = bluesky_get_header($notification, $uri, $uid, $uid);
925 $item['gravity'] = Item::GRAVITY_ACTIVITY;
926 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
927 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
928 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
929 if (!empty($item['thr-parent'])) {
930 $data = Item::insert($item);
931 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
933 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
938 $contact = bluesky_get_contact($notification->author, $uid, $uid);
939 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
943 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
944 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
948 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
949 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
953 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
954 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
958 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
964 function bluesky_fetch_feed(int $uid, string $feed)
966 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
971 if (empty($data->feed)) {
975 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
976 if (!empty($feeddata)) {
977 $feedurl = $feeddata->view->uri;
978 $feedname = $feeddata->view->displayName;
984 foreach (array_reverse($data->feed) as $entry) {
985 if (!Relay::isWantedLanguage($entry->post->record->text)) {
986 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
989 $id = bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
991 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
992 if (!empty($post['uri-id'])) {
993 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
994 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
996 Logger::notice('Post not found', ['id' => $id, 'entry' => $entry]);
999 if (!empty($entry->reason)) {
1000 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1005 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
1007 $uri = bluesky_get_uri($post);
1009 if ($id = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $uid])) {
1013 if ($id = Post::selectFirst(['id'], ['extid' => $uri, 'uid' => $uid])) {
1017 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1019 $item = bluesky_get_header($post, $uri, $uid, $uid);
1020 $item = bluesky_get_content($item, $post->record, $uri, $uid, $level);
1025 if (!empty($post->embed)) {
1026 $item = bluesky_add_media($post->embed, $item, $uid, $level);
1029 if (empty($item['post-reason'])) {
1030 $item['post-reason'] = $post_reason;
1033 return item::insert($item);
1036 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1038 $parts = bluesky_get_uri_parts($uri);
1039 if (empty($post->author)) {
1042 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1044 'network' => Protocol::BLUESKY,
1048 'guid' => $post->cid,
1049 'private' => Item::UNLISTED,
1050 'verb' => Activity::POST,
1051 'contact-id' => $contact['id'],
1052 'author-name' => $contact['name'],
1053 'author-link' => $contact['url'],
1054 'author-avatar' => $contact['avatar'],
1055 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1056 'source' => json_encode($post),
1059 $item['uri-id'] = ItemURI::getIdByURI($uri);
1060 $item['owner-name'] = $item['author-name'];
1061 $item['owner-link'] = $item['author-link'];
1062 $item['owner-avatar'] = $item['author-avatar'];
1064 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1065 $item['post-reason'] = Item::PR_FOLLOWER;
1071 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $level): array
1077 if (!empty($record->reply)) {
1078 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1079 if ($item['parent-uri'] != $uri) {
1080 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id'], $level);
1081 if (empty($item['parent-uri'])) {
1086 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1087 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1088 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], $level, $item['parent-uri']);
1089 if (empty($item['thr-parent'])) {
1095 $item['body'] = bluesky_get_text($record);
1096 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1100 function bluesky_get_text(stdClass $record): string
1102 $text = $record->text ?? '';
1104 if (empty($record->facets)) {
1109 foreach ($record->facets as $facet) {
1110 $facets[$facet->index->byteStart] = $facet;
1114 foreach ($facets as $facet) {
1115 $prefix = substr($text, 0, $facet->index->byteStart);
1116 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1117 $suffix = substr($text, $facet->index->byteEnd);
1121 foreach ($facet->features as $feature) {
1123 switch ($feature->$type) {
1124 case 'app.bsky.richtext.facet#link':
1125 $url = $feature->uri;
1128 case 'app.bsky.richtext.facet#mention':
1129 $contact = Contact::getByURL($feature->did, null, ['id']);
1130 if (!empty($contact['id'])) {
1131 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1132 if (substr($linktext, 0, 1) == '@') {
1134 $linktext = substr($linktext, 1);
1140 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1145 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1151 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1154 switch ($embed->$type) {
1155 case 'app.bsky.embed.images#view':
1156 foreach ($embed->images as $image) {
1158 'uri-id' => $item['uri-id'],
1159 'type' => Post\Media::IMAGE,
1160 'url' => $image->fullsize,
1161 'preview' => $image->thumb,
1162 'description' => $image->alt,
1164 Post\Media::insert($media);
1168 case 'app.bsky.embed.external#view':
1170 'uri-id' => $item['uri-id'],
1171 'type' => Post\Media::HTML,
1172 'url' => $embed->external->uri,
1173 'name' => $embed->external->title,
1174 'description' => $embed->external->description,
1176 Post\Media::insert($media);
1179 case 'app.bsky.embed.record#view':
1180 $uri = bluesky_get_uri($embed->record);
1181 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1182 if (empty($shared)) {
1183 if (empty($embed->record->value)) {
1184 Logger::info('Record has got no value', ['record' => $embed->record]);
1187 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1188 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1189 if (!empty($shared)) {
1190 if (!empty($embed->record->embeds)) {
1191 foreach ($embed->record->embeds as $single) {
1192 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1195 Item::insert($shared);
1198 if (!empty($shared['uri-id'])) {
1199 $item['quote-uri-id'] = $shared['uri-id'];
1203 case 'app.bsky.embed.recordWithMedia#view':
1204 $uri = bluesky_get_uri($embed->record->record);
1205 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1206 if (empty($shared)) {
1207 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1208 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1209 if (!empty($shared)) {
1210 if (!empty($embed->record->record->embeds)) {
1211 foreach ($embed->record->record->embeds as $single) {
1212 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1215 Item::insert($shared);
1218 if (!empty($shared['uri-id'])) {
1219 $item['quote-uri-id'] = $shared['uri-id'];
1222 if (!empty($embed->media)) {
1223 $item = bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1228 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1234 function bluesky_get_uri(stdClass $post): string
1236 if (empty($post->cid)) {
1237 Logger::info('Invalid URI', ['post' => $post]);
1240 return $post->uri . ':' . $post->cid;
1243 function bluesky_get_uri_class(string $uri): ?stdClass
1249 $elements = explode(':', $uri);
1250 if (empty($elements) || ($elements[0] != 'at')) {
1251 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1252 return bluesky_get_uri_class($post['extid'] ?? '');
1255 $class = new stdClass;
1257 $class->cid = array_pop($elements);
1258 $class->uri = implode(':', $elements);
1260 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1261 $class->uri .= ':' . $class->cid;
1268 function bluesky_get_uri_parts(string $uri): ?stdClass
1270 $class = bluesky_get_uri_class($uri);
1271 if (empty($class)) {
1275 $parts = explode('/', substr($class->uri, 5));
1277 $class = new stdClass;
1279 $class->repo = $parts[0];
1280 $class->collection = $parts[1];
1281 $class->rkey = $parts[2];
1286 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1288 $fetched_uri = bluesky_fetch_post($uri, $uid);
1289 if (!empty($fetched_uri)) {
1290 return $fetched_uri;
1293 if (++$level > 100) {
1294 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1295 // When the level is too deep we will fallback to the parent uri.
1296 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1300 $class = bluesky_get_uri_class($uri);
1301 $fetch_uri = $class->uri;
1303 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1304 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1306 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1310 Logger::debug('Reply count', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1313 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1318 return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1321 function bluesky_fetch_post(string $uri, int $uid): string
1323 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1324 Logger::debug('Post exists', ['uri' => $uri]);
1328 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1329 if (!empty($reply['uri'])) {
1330 Logger::debug('Post with extid exists', ['uri' => $uri]);
1331 return $reply['uri'];
1336 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1338 if (empty($thread->post)) {
1339 Logger::info('Invalid post', ['post' => $thread]);
1342 $uri = bluesky_get_uri($thread->post);
1344 $fetched_uri = bluesky_fetch_post($uri, $uid);
1345 if (empty($fetched_uri)) {
1346 Logger::debug('Process missing post', ['uri' => $uri]);
1347 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1348 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1349 if (!empty($item)) {
1350 $item['post-reason'] = Item::PR_FETCHED;
1352 if (!empty($cdata['public'])) {
1353 $item['causer-id'] = $cdata['public'];
1356 if (!empty($thread->post->embed)) {
1357 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1359 $id = Item::insert($item);
1361 Logger::info('Item has not not been stored', ['uri' => $uri]);
1364 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1366 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1370 Logger::debug('Post exists', ['uri' => $uri]);
1371 $uri = $fetched_uri;
1374 foreach ($thread->replies ?? [] as $reply) {
1375 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1376 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1382 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1384 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1385 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1387 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1389 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1391 $public_fields['uid'] = 0;
1392 $public_fields['rel'] = Contact::NOTHING;
1394 if (empty($contact)) {
1395 $cid = Contact::insert($public_fields);
1397 $cid = $contact['id'];
1398 Contact::update($public_fields, ['id' => $cid], true);
1402 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1404 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1405 if (!isset($fields['rel']) && isset($contact['rel'])) {
1406 $fields['rel'] = $contact['rel'];
1407 } elseif (!isset($fields['rel'])) {
1408 $fields['rel'] = Contact::NOTHING;
1412 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1413 if (empty($contact)) {
1414 $cid = Contact::insert($fields);
1416 $cid = $contact['id'];
1417 Contact::update($fields, ['id' => $cid], true);
1419 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1421 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1423 if (!empty($author->avatar)) {
1424 Contact::updateAvatar($cid, $author->avatar);
1427 return Contact::getById($cid);
1430 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1434 'network' => Protocol::BLUESKY,
1438 'readonly' => false,
1440 'baseurl' => BLUESKY_HOST,
1441 'url' => $author->did,
1442 'nurl' => $author->did,
1443 'alias' => BLUESKY_HOST . '/profile/' . $author->handle,
1444 'name' => $author->displayName ?? $author->handle,
1445 'nick' => $author->handle,
1446 'addr' => $author->handle,
1450 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1454 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1456 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1460 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1462 if (!empty($data->description)) {
1463 $fields['about'] = HTML::toBBCode($data->description);
1466 if (!empty($data->banner)) {
1467 $fields['header'] = $data->banner;
1470 if (!empty($data->viewer)) {
1471 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1472 $fields['rel'] = Contact::FRIEND;
1473 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1474 $fields['rel'] = Contact::SHARING;
1475 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1476 $fields['rel'] = Contact::FOLLOWER;
1478 $fields['rel'] = Contact::NOTHING;
1482 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1486 function bluesky_get_feeds(int $uid): array
1489 $preferences = bluesky_get_preferences($uid);
1490 foreach ($preferences->preferences as $preference) {
1491 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1492 return $preference->pinned ?? [];
1498 function bluesky_get_preferences(int $uid): stdClass
1500 $cachekey = 'bluesky:preferences:' . $uid;
1501 $data = DI::cache()->get($cachekey);
1502 if (!is_null($data)) {
1506 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1508 DI::cache()->set($cachekey, $data, Duration::HOUR);
1512 function bluesky_get_did(int $uid, string $handle): string
1514 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1518 Logger::debug('Got DID', ['return' => $data]);
1522 function bluesky_get_token(int $uid): string
1524 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1525 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1526 if (empty($token)) {
1530 if ($created + 300 < time()) {
1531 return bluesky_refresh_token($uid);
1536 function bluesky_refresh_token(int $uid): string
1538 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1540 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1545 Logger::debug('Refreshed token', ['return' => $data]);
1546 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1547 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1548 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1549 return $data->accessJwt;
1552 function bluesky_create_token(int $uid, string $password): string
1554 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1556 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1561 Logger::debug('Created token', ['return' => $data]);
1562 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1563 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1564 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1565 return $data->accessJwt;
1568 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1570 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1573 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1576 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1577 } catch (\Exception $e) {
1578 Logger::notice('Exception on post', ['exception' => $e]);
1582 if (!$curlResult->isSuccess()) {
1583 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1587 return json_decode($curlResult->getBody());
1590 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1592 if (!empty($parameters)) {
1593 $url .= '?' . http_build_query($parameters);
1596 return bluesky_get($uid, '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1599 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1602 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1603 } catch (\Exception $e) {
1604 Logger::notice('Exception on get', ['exception' => $e]);
1608 if (!$curlResult->isSuccess()) {
1609 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1613 return json_decode($curlResult->getBody());