3 * Name: Bluesky Connector
4 * Description: Post to Bluesky
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 * - Probing for contacts
12 * Need more information:
13 * - only fetch new posts
14 * - detect contact relations
19 * Possible but less important:
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Content\Text\Plaintext;
29 use Friendica\Core\Config\Util\ConfigFileManager;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
42 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
43 use Friendica\Protocol\Activity;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Strings;
47 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
48 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
50 function bluesky_install()
52 Hook::register('load_config', __FILE__, 'bluesky_load_config');
53 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
54 Hook::register('post_local', __FILE__, 'bluesky_post_local');
55 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
56 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
57 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
58 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
59 Hook::register('cron', __FILE__, 'bluesky_cron');
60 // Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
61 // Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
62 // Hook::register('follow', __FILE__, 'bluesky_follow');
63 // Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
64 // Hook::register('block', __FILE__, 'bluesky_block');
65 // Hook::register('unblock', __FILE__, 'bluesky_unblock');
66 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
67 // Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
68 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
71 function bluesky_load_config(ConfigFileManager $loader)
73 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
76 function bluesky_check_item_notification(array &$notification_data)
78 $handle = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'handle');
79 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
81 if (!empty($handle) && !empty($did)) {
82 $notification_data['profiles'][] = $handle;
83 $notification_data['profiles'][] = $did;
87 function bluesky_item_by_link(array &$hookData)
89 // Don't overwrite an existing result
90 if (isset($hookData['item_id'])) {
94 $token = bluesky_get_token($hookData['uid']);
99 if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
103 $did = bluesky_get_did($hookData['uid'], $matches[1]);
108 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
110 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
112 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, true);
113 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
115 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
116 if (!empty($item['id'])) {
117 $hookData['item_id'] = $item['id'];
122 function bluesky_settings(array &$data)
124 if (!DI::userSession()->getLocalUserId()) {
128 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
129 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
130 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
131 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
132 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
133 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
134 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
136 $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.');
138 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
139 $html = Renderer::replaceMacros($t, [
140 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
141 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
142 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
143 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
144 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
145 '$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'],
146 '$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.")],
151 'connector' => 'bluesky',
152 'title' => DI::l10n()->t('Bluesky Import/Export'),
153 'image' => 'images/bluesky.jpg',
154 'enabled' => $enabled,
159 function bluesky_settings_post(array &$b)
161 if (empty($_POST['bluesky-submit'])) {
165 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
166 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
167 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
169 $host = $_POST['bluesky_host'];
170 $handle = $_POST['bluesky_handle'];
172 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
173 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
174 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
175 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
176 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
178 if (!empty($host) && !empty($handle)) {
179 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
180 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
183 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
186 if (!empty($_POST['bluesky_password'])) {
187 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
191 function bluesky_jot_nets(array &$jotnets_fields)
193 if (!DI::userSession()->getLocalUserId()) {
197 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
198 $jotnets_fields[] = [
199 'type' => 'checkbox',
202 DI::l10n()->t('Post to Bluesky'),
203 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
209 function bluesky_cron()
211 $last = DI::keyValue()->get('bluesky_last_poll');
213 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
214 if (!$poll_interval) {
215 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
219 $next = $last + ($poll_interval * 60);
220 if ($next > time()) {
221 Logger::notice('poll interval not reached');
225 Logger::notice('cron_start');
227 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
228 if ($abandon_days < 1) {
232 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
234 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
235 foreach ($pconfigs as $pconfig) {
236 if ($abandon_days != 0) {
237 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
238 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
243 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
244 bluesky_fetch_timeline($pconfig['uid']);
245 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
248 Logger::notice('cron_end');
250 DI::keyValue()->set('bluesky_last_poll', time());
253 function bluesky_hook_fork(array &$b)
255 if ($b['name'] != 'notifier_normal') {
261 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
262 DI::logger()->info('Editing is not supported by the addon');
263 $b['execute'] = false;
267 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
268 // Don't post if it isn't a reply to a bluesky post
269 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
270 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
271 $b['execute'] = false;
274 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
275 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
276 $b['execute'] = false;
281 function bluesky_post_local(array &$b)
287 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
291 if ($b['private'] || $b['parent']) {
295 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
296 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
298 // if API is used, default to the chosen settings
299 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
303 if (!$bluesky_enable) {
307 if (strlen($b['postopts'])) {
308 $b['postopts'] .= ',';
311 $b['postopts'] .= 'bluesky';
314 function bluesky_send(array &$b)
316 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
320 if ($b['gravity'] != Item::GRAVITY_PARENT) {
321 Logger::debug('Got comment', ['item' => $b]);
324 $uri = bluesky_get_uri_class($b['uri']);
326 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
329 bluesky_delete_post($b['uri'], $b['uid']);
333 $root = bluesky_get_uri_class($b['parent-uri']);
334 $parent = bluesky_get_uri_class($b['thr-parent']);
336 if (empty($root) || empty($parent)) {
337 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
341 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
342 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
343 bluesky_create_post($b, $root, $parent);
345 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
346 bluesky_create_activity($b, $parent);
349 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
353 bluesky_create_post($b);
356 function bluesky_create_activity(array $item, stdClass $parent = null)
359 $token = bluesky_get_token($uid);
364 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
366 if ($item['verb'] == Activity::LIKE) {
368 'subject' => $parent,
369 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
370 '$type' => 'app.bsky.feed.like'
374 'collection' => 'app.bsky.feed.like',
378 } elseif ($item['verb'] == Activity::ANNOUNCE) {
380 'subject' => $parent,
381 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
382 '$type' => 'app.bsky.feed.repost'
386 'collection' => 'app.bsky.feed.repost',
392 $activity = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
393 if (empty($activity)) {
396 Logger::debug('Activity done', ['return' => $activity]);
397 $uri = bluesky_get_uri($activity);
398 Item::update(['extid' => $uri], ['id' => $item['id']]);
399 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
402 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
405 $token = bluesky_get_token($uid);
410 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
411 $urls = bluesky_get_urls($item['body']);
413 $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
414 foreach ($msg['parts'] as $key => $part) {
416 $facets = bluesky_get_facets($part, $urls);
419 'text' => $facets['body'],
420 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
421 '$type' => 'app.bsky.feed.post'
424 if (!empty($facets['facets'])) {
425 $record['facets'] = $facets['facets'];
429 $record['reply'] = ['root' => $root, 'parent' => $parent];
432 if ($key == count($msg['parts']) - 1) {
433 $record = bluesky_add_embed($uid, $msg, $record);
437 'collection' => 'app.bsky.feed.post',
442 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
443 if (empty($parent)) {
446 Logger::debug('Posting done', ['return' => $parent]);
450 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
451 $uri = bluesky_get_uri($parent);
452 Item::update(['extid' => $uri], ['id' => $item['id']]);
453 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
458 function bluesky_get_urls(string $body): array
460 // Remove all hashtags and mentions
461 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
465 // Search for pure links
466 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
467 foreach ($matches[1] as $url) {
472 // Search for links with descriptions
473 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
474 foreach ($matches[1] as $url) {
481 function bluesky_get_facets(string $body, array $urls): array
485 foreach ($urls as $url) {
486 $pos = strpos($body, $url);
487 if ($pos === false) {
491 $prefix = substr($body, 0, $pos);
495 $linktext = Strings::getStyledURL($url);
496 $body = $prefix . $linktext . substr($body, $pos + strlen($url));
498 $facet = new stdClass;
499 $facet->index = new stdClass;
500 $facet->index->byteEnd = $pos + strlen($linktext);
501 $facet->index->byteStart = $pos;
503 $feature = new stdClass;
504 $feature->uri = $url;
506 $feature->$type = 'app.bsky.richtext.facet#link';
508 $facet->features = [$feature];
512 return ['facets' => $facets, 'body' => $body];
515 function bluesky_add_embed(int $uid, array $msg, array $record): array
517 if (($msg['type'] != 'link') && !empty($msg['images'])) {
519 foreach ($msg['images'] as $image) {
520 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
521 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
522 $blob = bluesky_upload_blob($uid, $photo);
523 if (!empty($blob) && count($images) < 4) {
524 $images[] = ['alt' => $image['description'], 'image' => $blob];
527 if (!empty($images)) {
528 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
530 } elseif ($msg['type'] == 'link') {
532 '$type' => 'app.bsky.embed.external',
534 'uri' => $msg['url'],
535 'title' => $msg['title'],
536 'description' => $msg['description'],
539 if (!empty($msg['image'])) {
540 $photo = Photo::createPhotoForExternalResource($msg['image']);
541 $blob = bluesky_upload_blob($uid, $photo);
543 $record['embed']['external']['thumb'] = $blob;
550 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
552 $content = Photo::getImageForPhoto($photo);
553 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
558 Logger::debug('Uploaded blob', ['return' => $data]);
562 function bluesky_delete_post(string $uri, int $uid)
564 $token = bluesky_get_token($uid);
565 $parts = bluesky_get_uri_parts($uri);
567 Logger::debug('No uri delected', ['uri' => $uri]);
570 bluesky_post($uid, '/xrpc/com.atproto.repo.deleteRecord', json_encode($parts), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
571 Logger::debug('Deleted', ['parts' => $parts]);
574 function bluesky_fetch_timeline(int $uid)
576 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
581 if (empty($data->feed)) {
585 foreach (array_reverse($data->feed) as $entry) {
586 bluesky_process_post($entry->post, $uid);
587 if (!empty($entry->reason)) {
588 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
592 // @todo Support paging
593 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
596 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
599 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
603 $contact = bluesky_get_contact($reason->by, $uid);
606 'network' => Protocol::BLUESKY,
609 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
610 'private' => Item::UNLISTED,
611 'verb' => Activity::POST,
612 'contact-id' => $contact['id'],
613 'author-name' => $contact['name'],
614 'author-link' => $contact['url'],
615 'author-avatar' => $contact['avatar'],
616 'verb' => Activity::ANNOUNCE,
617 'body' => Activity::ANNOUNCE,
618 'gravity' => Item::GRAVITY_ACTIVITY,
619 'object-type' => Activity\ObjectType::NOTE,
620 'thr-parent' => $uri,
623 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
627 $item['owner-name'] = $item['author-name'];
628 $item['owner-link'] = $item['author-link'];
629 $item['owner-avatar'] = $item['author-avatar'];
630 if (Item::insert($item)) {
631 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
632 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
636 function bluesky_process_post(stdClass $post, int $uid): int
638 $uri = bluesky_get_uri($post);
640 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
644 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid]);
646 $item = bluesky_get_header($post, $uri, $uid);
648 $item = bluesky_get_content($item, $post->record, $uid);
650 if (!empty($post->embed)) {
651 $item = bluesky_add_media($post->embed, $item);
653 return item::insert($item);
656 function bluesky_get_header(stdClass $post, string $uri, int $uid): array
658 $parts = bluesky_get_uri_parts($uri);
659 if (empty($post->author)) {
662 $contact = bluesky_get_contact($post->author, $uid);
664 'network' => Protocol::BLUESKY,
668 'guid' => $post->cid,
669 'private' => Item::UNLISTED,
670 'verb' => Activity::POST,
671 'contact-id' => $contact['id'],
672 'author-name' => $contact['name'],
673 'author-link' => $contact['url'],
674 'author-avatar' => $contact['avatar'],
675 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
678 $item['uri-id'] = ItemURI::getIdByURI($uri);
679 $item['owner-name'] = $item['author-name'];
680 $item['owner-link'] = $item['author-link'];
681 $item['owner-avatar'] = $item['author-avatar'];
686 function bluesky_get_content(array $item, stdClass $record, int $uid): array
688 if (!empty($record->reply)) {
689 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
690 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id']);
691 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
692 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id']);
695 $item['body'] = bluesky_get_text($record, $uid);
696 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
700 function bluesky_get_text(stdClass $record, int $uid): string
702 $text = $record->text;
704 if (empty($record->facets)) {
709 foreach ($record->facets as $facet) {
710 $facets[$facet->index->byteStart] = $facet;
714 foreach ($facets as $facet) {
715 $prefix = substr($text, 0, $facet->index->byteStart);
716 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
717 $suffix = substr($text, $facet->index->byteEnd);
721 foreach ($facet->features as $feature) {
722 if (!empty($feature->uri)) {
723 $url = $feature->uri;
725 if (!empty($feature->did)) {
726 $contact = Contact::selectFirst(['id'], ['nurl' => $feature->did, 'uid' => [0, $uid]]);
727 if (!empty($contact['id'])) {
728 $url = DI::baseUrl() . '/contact/' . $contact['id'];
729 if (substr($linktext, 0, 1) == '@') {
731 $linktext = substr($linktext, 1);
737 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
743 function bluesky_add_media(stdClass $embed, array $item): array
745 if (!empty($embed->images)) {
746 foreach ($embed->images as $image) {
748 'uri-id' => $item['uri-id'],
749 'type' => Post\Media::IMAGE,
750 'url' => $image->fullsize,
751 'preview' => $image->thumb,
752 'description' => $image->alt,
754 Post\Media::insert($media);
756 } elseif (!empty($embed->external)) {
758 'uri-id' => $item['uri-id'],
759 'type' => Post\Media::HTML,
760 'url' => $embed->external->uri,
761 'name' => $embed->external->title,
762 'description' => $embed->external->description,
764 Post\Media::insert($media);
765 } elseif (!empty($embed->record)) {
766 $uri = bluesky_get_uri($embed->record);
767 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
768 if (empty($shared)) {
769 $shared = bluesky_get_header($embed->record, $uri, 0);
770 if (!empty($shared)) {
771 $shared = bluesky_get_content($shared, $embed->record->value, $item['uid']);
773 if (!empty($embed->record->embeds)) {
774 foreach ($embed->record->embeds as $single) {
775 $shared = bluesky_add_media($single, $shared);
778 $id = Item::insert($shared);
779 $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
782 if (!empty($shared)) {
783 $item['quote-uri-id'] = $shared['uri-id'];
786 Logger::debug('Unsupported embed', ['embed' => $embed, 'item' => $item]);
791 function bluesky_get_uri(stdClass $post): string
793 return $post->uri . ':' . $post->cid;
796 function bluesky_get_uri_class(string $uri): ?stdClass
802 $elements = explode(':', $uri);
803 if (empty($elements) || ($elements[0] != 'at')) {
804 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
805 return bluesky_get_uri_class($post['extid'] ?? '');
808 $class = new stdClass;
810 $class->cid = array_pop($elements);
811 $class->uri = implode(':', $elements);
816 function bluesky_get_uri_parts(string $uri): ?stdClass
818 $class = bluesky_get_uri_class($uri);
823 $parts = explode('/', substr($class->uri, 5));
825 $class = new stdClass;
827 $class->repo = $parts[0];
828 $class->collection = $parts[1];
829 $class->rkey = $parts[2];
834 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, bool $original = false): string
836 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
837 Logger::debug('Post exists', ['uri' => $uri]);
841 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
842 if (!empty($reply['uri'])) {
843 return $reply['uri'];
846 Logger::debug('Fetch missing post', ['uri' => $uri]);
848 $class = bluesky_get_uri_class($uri);
849 $fetch_uri = $class->uri;
854 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getPosts?uris=' . urlencode($fetch_uri), HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
860 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
863 foreach ($data->posts as $post) {
864 $uri = bluesky_get_uri($post);
865 $item = bluesky_get_header($post, $uri, $uid);
866 $item = bluesky_get_content($item, $post->record, $uid);
868 $item['post-reason'] = Item::PR_FETCHED;
870 if (!empty($cdata['public'])) {
871 $item['causer-id'] = $cdata['public'];
874 if (!empty($post->embed)) {
875 $item = bluesky_add_media($post->embed, $item);
877 $id = Item::insert($item);
878 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
884 function bluesky_get_contact(stdClass $author, int $uid): array
886 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
889 'alias' => BLUESKY_HOST . '/profile/' . $author->handle,
890 'name' => $author->displayName,
891 'nick' => $author->handle,
892 'addr' => $author->handle,
895 $contact = Contact::selectFirst([], $condition);
897 if (empty($contact)) {
898 $cid = bluesky_insert_contact($author, $uid);
900 $cid = $contact['id'];
901 if ($fields['alias'] != $contact['alias'] || $fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
902 Contact::update($fields, ['id' => $cid]);
906 $condition['uid'] = 0;
908 $contact = Contact::selectFirst([], $condition);
909 if (empty($contact)) {
910 $pcid = bluesky_insert_contact($author, 0);
912 $pcid = $contact['id'];
913 if ($fields['alias'] != $contact['alias'] || $fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
914 Contact::update($fields, ['id' => $pcid]);
918 if (!empty($author->avatar)) {
919 Contact::updateAvatar($cid, $author->avatar);
922 if (empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
923 bluesky_update_contact($author, $uid, $cid, $pcid);
926 return Contact::getById($cid);
929 function bluesky_insert_contact(stdClass $author, int $uid)
933 'network' => Protocol::BLUESKY,
939 'url' => $author->did,
940 'nurl' => $author->did,
941 'alias' => BLUESKY_HOST . '/profile/' . $author->handle,
942 'name' => $author->displayName,
943 'nick' => $author->handle,
944 'addr' => $author->handle,
946 return Contact::insert($fields);
949 function bluesky_update_contact(stdClass $author, int $uid, int $cid, int $pcid)
951 $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
957 'alias' => BLUESKY_HOST . '/profile/' . $data->handle,
958 'name' => $data->displayName,
959 'nick' => $data->handle,
960 'addr' => $data->handle,
961 'updated' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL),
964 if (!empty($data->description)) {
965 $fields['about'] = HTML::toBBCode($data->description);
968 if (!empty($data->banner)) {
969 $fields['header'] = $data->banner;
972 Contact::update($fields, ['id' => $cid]);
973 Contact::update($fields, ['id' => $pcid]);
976 function bluesky_get_did(int $uid, string $handle): string
978 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . $handle);
982 Logger::debug('Got DID', ['return' => $data]);
986 function bluesky_get_token(int $uid): string
988 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
989 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
994 if ($created + 300 < time()) {
995 return bluesky_refresh_token($uid);
1000 function bluesky_refresh_token(int $uid): string
1002 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1004 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1009 Logger::debug('Refreshed token', ['return' => $data]);
1010 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1011 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1012 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1013 return $data->accessJwt;
1016 function bluesky_create_token(int $uid, string $password): string
1018 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1020 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1025 Logger::debug('Created token', ['return' => $data]);
1026 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1027 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1028 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1029 return $data->accessJwt;
1032 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1035 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1036 } catch (\Exception $e) {
1037 Logger::notice('Exception on post', ['exception' => $e]);
1041 if (!$curlResult->isSuccess()) {
1042 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1046 return json_decode($curlResult->getBody());
1049 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1052 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1053 } catch (\Exception $e) {
1054 Logger::notice('Exception on get', ['exception' => $e]);
1058 if (!$curlResult->isSuccess()) {
1059 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1063 return json_decode($curlResult->getBody());