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\System;
36 use Friendica\Core\Worker;
37 use Friendica\Database\DBA;
39 use Friendica\Model\Contact;
40 use Friendica\Model\Item;
41 use Friendica\Model\ItemURI;
42 use Friendica\Model\Photo;
43 use Friendica\Model\Post;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
46 use Friendica\Object\Image;
47 use Friendica\Protocol\Activity;
48 use Friendica\Protocol\Relay;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\Strings;
52 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
53 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
54 const BLUESKY_IMAGE_SIZE = [1000000, 500000, 100000, 50000];
56 function bluesky_install()
58 Hook::register('load_config', __FILE__, 'bluesky_load_config');
59 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
60 Hook::register('post_local', __FILE__, 'bluesky_post_local');
61 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
62 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
63 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
64 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
65 Hook::register('cron', __FILE__, 'bluesky_cron');
66 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
67 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
68 Hook::register('follow', __FILE__, 'bluesky_follow');
69 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
70 Hook::register('block', __FILE__, 'bluesky_block');
71 Hook::register('unblock', __FILE__, 'bluesky_unblock');
72 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
73 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
74 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
77 function bluesky_load_config(ConfigFileManager $loader)
79 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
82 function bluesky_check_item_notification(array &$notification_data)
84 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
87 $notification_data['profiles'][] = $did;
91 function bluesky_probe_detect(array &$hookData)
93 // Don't overwrite an existing result
94 if (isset($hookData['result'])) {
98 // Avoid a lookup for the wrong network
99 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
103 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
104 if (empty($pconfig['uid'])) {
108 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
109 $did = $hookData['uri'];
110 } elseif (preg_match('#^' . BLUESKY_HOST . '/profile/(.+)#', $hookData['uri'], $matches)) {
111 $did = bluesky_get_did($pconfig['uid'], $matches[1]);
119 $token = bluesky_get_token($pconfig['uid']);
124 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
129 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
131 // Preparing probe data. This differs slightly from the contact array
132 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
133 $hookData['result']['photo'] = $data->avatar ?? '';
134 $hookData['result']['header'] = $data->banner ?? '';
135 $hookData['result']['batch'] = '';
136 $hookData['result']['notify'] = '';
137 $hookData['result']['poll'] = '';
138 $hookData['result']['poco'] = '';
139 $hookData['result']['pubkey'] = '';
140 $hookData['result']['priority'] = 0;
141 $hookData['result']['guid'] = '';
144 function bluesky_item_by_link(array &$hookData)
146 // Don't overwrite an existing result
147 if (isset($hookData['item_id'])) {
151 $token = bluesky_get_token($hookData['uid']);
156 if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
160 $did = bluesky_get_did($hookData['uid'], $matches[1]);
165 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
167 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
169 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, 0);
170 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
172 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
173 if (!empty($item['id'])) {
174 $hookData['item_id'] = $item['id'];
179 function bluesky_support_follow(array &$data)
181 if ($data['protocol'] == Protocol::BLUESKY) {
182 $data['result'] = true;
186 function bluesky_support_probe(array &$data)
188 if ($data['protocol'] == Protocol::BLUESKY) {
189 $data['result'] = true;
193 function bluesky_follow(array &$hook_data)
195 $token = bluesky_get_token($hook_data['uid']);
200 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
201 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
202 if (empty($contact)) {
207 'subject' => $contact['url'],
208 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
209 '$type' => 'app.bsky.graph.follow'
213 'collection' => 'app.bsky.graph.follow',
214 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
218 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
219 if (!empty($activity->uri)) {
220 $hook_data['contact'] = $contact;
221 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
225 function bluesky_unfollow(array &$hook_data)
227 $token = bluesky_get_token($hook_data['uid']);
232 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
236 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
237 if (empty($data->viewer) || empty($data->viewer->following)) {
241 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
243 $hook_data['result'] = true;
246 function bluesky_block(array &$hook_data)
248 $token = bluesky_get_token($hook_data['uid']);
253 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
254 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
255 if (empty($contact)) {
260 'subject' => $contact['url'],
261 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
262 '$type' => 'app.bsky.graph.block'
266 'collection' => 'app.bsky.graph.block',
267 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
271 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
272 if (!empty($activity->uri)) {
273 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
274 if (!empty($cdata['user'])) {
275 Contact::remove($cdata['user']);
277 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
281 function bluesky_unblock(array &$hook_data)
283 $token = bluesky_get_token($hook_data['uid']);
288 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
292 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
293 if (empty($data->viewer) || empty($data->viewer->blocking)) {
297 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
299 $hook_data['result'] = true;
302 function bluesky_settings(array &$data)
304 if (!DI::userSession()->getLocalUserId()) {
308 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
309 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
310 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
311 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
312 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
313 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
314 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
315 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
317 $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.');
319 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
320 $html = Renderer::replaceMacros($t, [
321 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
322 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
323 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
324 '$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.')],
325 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
326 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
327 '$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'],
328 '$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.")],
333 'connector' => 'bluesky',
334 'title' => DI::l10n()->t('Bluesky Import/Export'),
335 'image' => 'images/bluesky.jpg',
336 'enabled' => $enabled,
341 function bluesky_settings_post(array &$b)
343 if (empty($_POST['bluesky-submit'])) {
347 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
348 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
349 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
351 $host = $_POST['bluesky_host'];
352 $handle = $_POST['bluesky_handle'];
354 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
355 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
356 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
357 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
358 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
359 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
361 if (!empty($host) && !empty($handle)) {
362 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
363 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
366 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
369 if (!empty($_POST['bluesky_password'])) {
370 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
374 function bluesky_jot_nets(array &$jotnets_fields)
376 if (!DI::userSession()->getLocalUserId()) {
380 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
381 $jotnets_fields[] = [
382 'type' => 'checkbox',
385 DI::l10n()->t('Post to Bluesky'),
386 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
392 function bluesky_cron()
394 $last = DI::keyValue()->get('bluesky_last_poll');
396 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
397 if (!$poll_interval) {
398 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
402 $next = $last + ($poll_interval * 60);
403 if ($next > time()) {
404 Logger::notice('poll interval not reached');
408 Logger::notice('cron_start');
410 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
411 if ($abandon_days < 1) {
415 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
417 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
418 foreach ($pconfigs as $pconfig) {
419 if ($abandon_days != 0) {
420 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
421 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
426 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
427 bluesky_get_token($pconfig['uid']);
429 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
430 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
432 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
433 $feeds = bluesky_get_feeds($pconfig['uid']);
434 foreach ($feeds as $feed) {
435 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
440 $last_clean = DI::keyValue()->get('bluesky_last_clean');
441 if (empty($last_clean) || ($last_clean + 86400 < time())) {
442 Logger::notice('Start contact cleanup');
443 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
444 while ($contact = DBA::fetch($contacts)) {
445 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
447 DBA::close($contacts);
448 DI::keyValue()->set('bluesky_last_clean', time());
449 Logger::notice('Contact cleanup done');
452 Logger::notice('cron_end');
454 DI::keyValue()->set('bluesky_last_poll', time());
457 function bluesky_hook_fork(array &$b)
459 if ($b['name'] != 'notifier_normal') {
465 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
466 DI::logger()->info('Editing is not supported by the addon');
467 $b['execute'] = false;
471 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
472 // Don't post if it isn't a reply to a bluesky post
473 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
474 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
475 $b['execute'] = false;
478 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
479 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
480 $b['execute'] = false;
485 function bluesky_post_local(array &$b)
491 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
495 if ($b['private'] || $b['parent']) {
499 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
500 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
502 // if API is used, default to the chosen settings
503 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
507 if (!$bluesky_enable) {
511 if (strlen($b['postopts'])) {
512 $b['postopts'] .= ',';
515 $b['postopts'] .= 'bluesky';
518 function bluesky_send(array &$b)
520 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
524 if ($b['gravity'] != Item::GRAVITY_PARENT) {
525 Logger::debug('Got comment', ['item' => $b]);
528 $uri = bluesky_get_uri_class($b['uri']);
530 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
533 bluesky_delete_post($b['uri'], $b['uid']);
537 $root = bluesky_get_uri_class($b['parent-uri']);
538 $parent = bluesky_get_uri_class($b['thr-parent']);
540 if (empty($root) || empty($parent)) {
541 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
545 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
546 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
547 bluesky_create_post($b, $root, $parent);
549 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
550 bluesky_create_activity($b, $parent);
553 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
557 bluesky_create_post($b);
560 function bluesky_create_activity(array $item, stdClass $parent = null)
563 $token = bluesky_get_token($uid);
568 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
570 if ($item['verb'] == Activity::LIKE) {
572 'subject' => $parent,
573 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
574 '$type' => 'app.bsky.feed.like'
578 'collection' => 'app.bsky.feed.like',
582 } elseif ($item['verb'] == Activity::ANNOUNCE) {
584 'subject' => $parent,
585 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
586 '$type' => 'app.bsky.feed.repost'
590 'collection' => 'app.bsky.feed.repost',
596 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
597 if (empty($activity)) {
600 Logger::debug('Activity done', ['return' => $activity]);
601 $uri = bluesky_get_uri($activity);
602 Item::update(['extid' => $uri], ['id' => $item['id']]);
603 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
606 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
609 $token = bluesky_get_token($uid);
614 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
615 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
616 $item['body'] = $urls['body'];
618 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
619 foreach ($msg['parts'] as $key => $part) {
621 $facets = bluesky_get_facets($part, $urls['urls']);
624 'text' => $facets['body'],
625 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
626 '$type' => 'app.bsky.feed.post'
629 if (!empty($facets['facets'])) {
630 $record['facets'] = $facets['facets'];
634 $record['reply'] = ['root' => $root, 'parent' => $parent];
637 if ($key == count($msg['parts']) - 1) {
638 $record = bluesky_add_embed($uid, $msg, $record);
639 if (empty($record)) {
640 if (Worker::getRetrial() < 3) {
648 'collection' => 'app.bsky.feed.post',
653 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
654 if (empty($parent)) {
660 Logger::debug('Posting done', ['return' => $parent]);
664 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
665 $uri = bluesky_get_uri($parent);
666 Item::update(['extid' => $uri], ['id' => $item['id']]);
667 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
672 function bluesky_get_urls(string $body): array
674 // Remove all hashtag and mention links
675 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
677 $body = BBCode::expandVideoLinks($body);
680 // Search for pure links
681 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
682 foreach ($matches as $match) {
683 $text = Strings::getStyledURL($match[1]);
684 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
685 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
686 $body = str_replace($match[0], $hash, $body);
690 // Search for links with descriptions
691 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
692 foreach ($matches as $match) {
693 if ($match[1] == $match[2]) {
694 $text = Strings::getStyledURL($match[1]);
698 if (mb_strlen($text) < 100) {
699 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
700 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
701 $body = str_replace($match[0], $hash, $body);
703 $text = Strings::getStyledURL($match[1]);
704 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
705 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
706 $body = str_replace($match[0], $text . ' ' . $hash, $body);
711 return ['body' => $body, 'urls' => $urls];
714 function bluesky_get_hash_for_url(string $text, int $linklength): string
716 if ($linklength <= 10) {
717 return '|' . hash('crc32', $text) . '|';
719 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
722 function bluesky_get_facets(string $body, array $urls): array
726 foreach ($urls as $url) {
727 $pos = strpos($body, $url['hash']);
728 if ($pos === false) {
732 $prefix = substr($body, 0, $pos);
737 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
739 $facet = new stdClass;
740 $facet->index = new stdClass;
741 $facet->index->byteEnd = $pos + strlen($url['text']);
742 $facet->index->byteStart = $pos;
744 $feature = new stdClass;
745 $feature->uri = $url['url'];
747 $feature->$type = 'app.bsky.richtext.facet#link';
749 $facet->features = [$feature];
753 return ['facets' => $facets, 'body' => $body];
756 function bluesky_add_embed(int $uid, array $msg, array $record): array
758 if (($msg['type'] != 'link') && !empty($msg['images'])) {
760 foreach ($msg['images'] as $image) {
761 if (count($images) == 4) {
764 $photo = Photo::selectFirst([], ['id' => $image['id']]);
765 $blob = bluesky_upload_blob($uid, $photo);
769 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
771 if (!empty($images)) {
772 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
774 } elseif ($msg['type'] == 'link') {
776 '$type' => 'app.bsky.embed.external',
778 'uri' => $msg['url'],
779 'title' => $msg['title'] ?? '',
780 'description' => $msg['description'] ?? '',
783 if (!empty($msg['image'])) {
784 $photo = Photo::createPhotoForExternalResource($msg['image']);
785 $blob = bluesky_upload_blob($uid, $photo);
787 $record['embed']['external']['thumb'] = $blob;
794 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
796 $retrial = Worker::getRetrial();
797 $content = Photo::getImageForPhoto($photo);
799 $picture = new Image($content, $photo['type']);
800 $height = $picture->getHeight();
801 $width = $picture->getWidth();
802 $size = strlen($content);
804 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
805 $new_height = $picture->getHeight();
806 $new_width = $picture->getWidth();
807 $content = $picture->asString();
808 $new_size = strlen($content);
810 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]);
812 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
814 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]);
818 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]);
822 function bluesky_delete_post(string $uri, int $uid)
824 $parts = bluesky_get_uri_parts($uri);
826 Logger::debug('No uri delected', ['uri' => $uri]);
829 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
830 Logger::debug('Deleted', ['parts' => $parts]);
833 function bluesky_fetch_timeline(int $uid)
835 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
840 if (empty($data->feed)) {
844 foreach (array_reverse($data->feed) as $entry) {
845 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
846 if (!empty($entry->reason)) {
847 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
851 // @todo Support paging
852 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
855 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
858 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
862 $contact = bluesky_get_contact($reason->by, $uid, $uid);
865 'network' => Protocol::BLUESKY,
868 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
869 'private' => Item::UNLISTED,
870 'verb' => Activity::POST,
871 'contact-id' => $contact['id'],
872 'author-name' => $contact['name'],
873 'author-link' => $contact['url'],
874 'author-avatar' => $contact['avatar'],
875 'verb' => Activity::ANNOUNCE,
876 'body' => Activity::ANNOUNCE,
877 'gravity' => Item::GRAVITY_ACTIVITY,
878 'object-type' => Activity\ObjectType::NOTE,
879 'thr-parent' => $uri,
882 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
886 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
887 $item['owner-name'] = $item['author-name'];
888 $item['owner-link'] = $item['author-link'];
889 $item['owner-avatar'] = $item['author-avatar'];
890 if (Item::insert($item)) {
891 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
892 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
896 function bluesky_fetch_notifications(int $uid)
898 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
899 if (empty($data->notifications)) {
902 foreach ($data->notifications as $notification) {
903 $uri = bluesky_get_uri($notification);
904 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
905 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
908 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
909 switch ($notification->reason) {
911 $item = bluesky_get_header($notification, $uri, $uid, $uid);
912 $item['gravity'] = Item::GRAVITY_ACTIVITY;
913 $item['body'] = $item['verb'] = Activity::LIKE;
914 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
915 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
916 if (!empty($item['thr-parent'])) {
917 $data = Item::insert($item);
918 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
920 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
925 $item = bluesky_get_header($notification, $uri, $uid, $uid);
926 $item['gravity'] = Item::GRAVITY_ACTIVITY;
927 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
928 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
929 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
930 if (!empty($item['thr-parent'])) {
931 $data = Item::insert($item);
932 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
934 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
939 $contact = bluesky_get_contact($notification->author, $uid, $uid);
940 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
944 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
945 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
949 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
950 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
954 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
955 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
959 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
965 function bluesky_fetch_feed(int $uid, string $feed)
967 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
972 if (empty($data->feed)) {
976 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
977 if (!empty($feeddata)) {
978 $feedurl = $feeddata->view->uri;
979 $feedname = $feeddata->view->displayName;
985 foreach (array_reverse($data->feed) as $entry) {
986 if (!Relay::isWantedLanguage($entry->post->record->text)) {
987 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
990 $id = bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
992 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
993 if (!empty($post['uri-id'])) {
994 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
995 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
997 Logger::notice('Post not found', ['id' => $id, 'entry' => $entry]);
1000 if (!empty($entry->reason)) {
1001 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1006 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
1008 $uri = bluesky_get_uri($post);
1010 if ($id = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $uid])) {
1014 if ($id = Post::selectFirst(['id'], ['extid' => $uri, 'uid' => $uid])) {
1018 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1020 $item = bluesky_get_header($post, $uri, $uid, $uid);
1021 $item = bluesky_get_content($item, $post->record, $uri, $uid, $level);
1026 if (!empty($post->embed)) {
1027 $item = bluesky_add_media($post->embed, $item, $uid, $level);
1030 if (empty($item['post-reason'])) {
1031 $item['post-reason'] = $post_reason;
1034 return item::insert($item);
1037 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1039 $parts = bluesky_get_uri_parts($uri);
1040 if (empty($post->author)) {
1043 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1045 'network' => Protocol::BLUESKY,
1049 'guid' => $post->cid,
1050 'private' => Item::UNLISTED,
1051 'verb' => Activity::POST,
1052 'contact-id' => $contact['id'],
1053 'author-name' => $contact['name'],
1054 'author-link' => $contact['url'],
1055 'author-avatar' => $contact['avatar'],
1056 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1057 'source' => json_encode($post),
1060 $item['uri-id'] = ItemURI::getIdByURI($uri);
1061 $item['owner-name'] = $item['author-name'];
1062 $item['owner-link'] = $item['author-link'];
1063 $item['owner-avatar'] = $item['author-avatar'];
1065 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1066 $item['post-reason'] = Item::PR_FOLLOWER;
1072 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $level): array
1078 if (!empty($record->reply)) {
1079 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1080 if ($item['parent-uri'] != $uri) {
1081 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id'], $level);
1082 if (empty($item['parent-uri'])) {
1087 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1088 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1089 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], $level, $item['parent-uri']);
1090 if (empty($item['thr-parent'])) {
1096 $item['body'] = bluesky_get_text($record);
1097 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1101 function bluesky_get_text(stdClass $record): string
1103 $text = $record->text ?? '';
1105 if (empty($record->facets)) {
1110 foreach ($record->facets as $facet) {
1111 $facets[$facet->index->byteStart] = $facet;
1115 foreach ($facets as $facet) {
1116 $prefix = substr($text, 0, $facet->index->byteStart);
1117 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1118 $suffix = substr($text, $facet->index->byteEnd);
1122 foreach ($facet->features as $feature) {
1124 switch ($feature->$type) {
1125 case 'app.bsky.richtext.facet#link':
1126 $url = $feature->uri;
1129 case 'app.bsky.richtext.facet#mention':
1130 $contact = Contact::getByURL($feature->did, null, ['id']);
1131 if (!empty($contact['id'])) {
1132 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1133 if (substr($linktext, 0, 1) == '@') {
1135 $linktext = substr($linktext, 1);
1141 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1146 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1152 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1155 switch ($embed->$type) {
1156 case 'app.bsky.embed.images#view':
1157 foreach ($embed->images as $image) {
1159 'uri-id' => $item['uri-id'],
1160 'type' => Post\Media::IMAGE,
1161 'url' => $image->fullsize,
1162 'preview' => $image->thumb,
1163 'description' => $image->alt,
1165 Post\Media::insert($media);
1169 case 'app.bsky.embed.external#view':
1171 'uri-id' => $item['uri-id'],
1172 'type' => Post\Media::HTML,
1173 'url' => $embed->external->uri,
1174 'name' => $embed->external->title,
1175 'description' => $embed->external->description,
1177 Post\Media::insert($media);
1180 case 'app.bsky.embed.record#view':
1181 $uri = bluesky_get_uri($embed->record);
1182 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1183 if (empty($shared)) {
1184 if (empty($embed->record->value)) {
1185 Logger::info('Record has got no value', ['record' => $embed->record]);
1188 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1189 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1190 if (!empty($shared)) {
1191 if (!empty($embed->record->embeds)) {
1192 foreach ($embed->record->embeds as $single) {
1193 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1196 Item::insert($shared);
1199 if (!empty($shared['uri-id'])) {
1200 $item['quote-uri-id'] = $shared['uri-id'];
1204 case 'app.bsky.embed.recordWithMedia#view':
1205 $uri = bluesky_get_uri($embed->record->record);
1206 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1207 if (empty($shared)) {
1208 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1209 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1210 if (!empty($shared)) {
1211 if (!empty($embed->record->record->embeds)) {
1212 foreach ($embed->record->record->embeds as $single) {
1213 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1216 Item::insert($shared);
1219 if (!empty($shared['uri-id'])) {
1220 $item['quote-uri-id'] = $shared['uri-id'];
1223 if (!empty($embed->media)) {
1224 $item = bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1229 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1235 function bluesky_get_uri(stdClass $post): string
1237 if (empty($post->cid)) {
1238 Logger::info('Invalid URI', ['post' => $post, 'callstack' => System::callstack(10, 0, true)]);
1241 return $post->uri . ':' . $post->cid;
1244 function bluesky_get_uri_class(string $uri): ?stdClass
1250 $elements = explode(':', $uri);
1251 if (empty($elements) || ($elements[0] != 'at')) {
1252 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1253 return bluesky_get_uri_class($post['extid'] ?? '');
1256 $class = new stdClass;
1258 $class->cid = array_pop($elements);
1259 $class->uri = implode(':', $elements);
1261 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1262 $class->uri .= ':' . $class->cid;
1269 function bluesky_get_uri_parts(string $uri): ?stdClass
1271 $class = bluesky_get_uri_class($uri);
1272 if (empty($class)) {
1276 $parts = explode('/', substr($class->uri, 5));
1278 $class = new stdClass;
1280 $class->repo = $parts[0];
1281 $class->collection = $parts[1];
1282 $class->rkey = $parts[2];
1287 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1289 $fetched_uri = bluesky_fetch_post($uri, $uid);
1290 if (!empty($fetched_uri)) {
1291 return $fetched_uri;
1294 if (++$level > 100) {
1295 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1296 // When the level is too deep we will fallback to the parent uri.
1297 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1301 $class = bluesky_get_uri_class($uri);
1302 $fetch_uri = $class->uri;
1304 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1305 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1307 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1311 Logger::debug('Reply count', ['replies' => $data->thread->post->replyCount, 'level' => $level, 'uid' => $uid, 'uri' => $uri]);
1314 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1319 return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1322 function bluesky_fetch_post(string $uri, int $uid): string
1324 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1325 Logger::debug('Post exists', ['uri' => $uri]);
1329 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1330 if (!empty($reply['uri'])) {
1331 Logger::debug('Post with extid exists', ['uri' => $uri]);
1332 return $reply['uri'];
1337 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1339 if (empty($thread->post)) {
1340 Logger::info('Invalid post', ['post' => $thread, 'callstack' => System::callstack(10, 0, true)]);
1343 $uri = bluesky_get_uri($thread->post);
1345 $fetched_uri = bluesky_fetch_post($uri, $uid);
1346 if (empty($fetched_uri)) {
1347 Logger::debug('Process missing post', ['uri' => $uri]);
1348 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1349 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1350 if (!empty($item)) {
1351 $item['post-reason'] = Item::PR_FETCHED;
1353 if (!empty($cdata['public'])) {
1354 $item['causer-id'] = $cdata['public'];
1357 if (!empty($thread->post->embed)) {
1358 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1360 $id = Item::insert($item);
1362 Logger::info('Item has not not been stored', ['uri' => $uri]);
1365 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1367 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1371 Logger::debug('Post exists', ['uri' => $uri]);
1372 $uri = $fetched_uri;
1375 foreach ($thread->replies ?? [] as $reply) {
1376 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1377 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1383 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1385 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1386 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1388 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1390 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1392 $public_fields['uid'] = 0;
1393 $public_fields['rel'] = Contact::NOTHING;
1395 if (empty($contact)) {
1396 $cid = Contact::insert($public_fields);
1398 $cid = $contact['id'];
1399 Contact::update($public_fields, ['id' => $cid], true);
1403 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1405 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1406 if (!isset($fields['rel']) && isset($contact['rel'])) {
1407 $fields['rel'] = $contact['rel'];
1408 } elseif (!isset($fields['rel'])) {
1409 $fields['rel'] = Contact::NOTHING;
1413 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1414 if (empty($contact)) {
1415 $cid = Contact::insert($fields);
1417 $cid = $contact['id'];
1418 Contact::update($fields, ['id' => $cid], true);
1420 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1422 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1424 if (!empty($author->avatar)) {
1425 Contact::updateAvatar($cid, $author->avatar);
1428 return Contact::getById($cid);
1431 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1435 'network' => Protocol::BLUESKY,
1439 'readonly' => false,
1441 'baseurl' => BLUESKY_HOST,
1442 'url' => $author->did,
1443 'nurl' => $author->did,
1444 'alias' => BLUESKY_HOST . '/profile/' . $author->handle,
1445 'name' => $author->displayName ?? $author->handle,
1446 'nick' => $author->handle,
1447 'addr' => $author->handle,
1451 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1455 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1457 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1461 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1463 if (!empty($data->description)) {
1464 $fields['about'] = HTML::toBBCode($data->description);
1467 if (!empty($data->banner)) {
1468 $fields['header'] = $data->banner;
1471 if (!empty($data->viewer)) {
1472 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1473 $fields['rel'] = Contact::FRIEND;
1474 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1475 $fields['rel'] = Contact::SHARING;
1476 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1477 $fields['rel'] = Contact::FOLLOWER;
1479 $fields['rel'] = Contact::NOTHING;
1483 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1487 function bluesky_get_feeds(int $uid): array
1490 $preferences = bluesky_get_preferences($uid);
1491 foreach ($preferences->preferences as $preference) {
1492 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1493 return $preference->pinned ?? [];
1499 function bluesky_get_preferences(int $uid): stdClass
1501 $cachekey = 'bluesky:preferences:' . $uid;
1502 $data = DI::cache()->get($cachekey);
1503 if (!is_null($data)) {
1507 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1509 DI::cache()->set($cachekey, $data, Duration::HOUR);
1513 function bluesky_get_did(int $uid, string $handle): string
1515 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1519 Logger::debug('Got DID', ['return' => $data]);
1523 function bluesky_get_token(int $uid): string
1525 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1526 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1527 if (empty($token)) {
1531 if ($created + 300 < time()) {
1532 return bluesky_refresh_token($uid);
1537 function bluesky_refresh_token(int $uid): string
1539 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1541 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1546 Logger::debug('Refreshed token', ['return' => $data]);
1547 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1548 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1549 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1550 return $data->accessJwt;
1553 function bluesky_create_token(int $uid, string $password): string
1555 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1557 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1562 Logger::debug('Created token', ['return' => $data]);
1563 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1564 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1565 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1566 return $data->accessJwt;
1569 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1571 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1574 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1577 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1578 } catch (\Exception $e) {
1579 Logger::notice('Exception on post', ['exception' => $e]);
1583 if (!$curlResult->isSuccess()) {
1584 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1588 return json_decode($curlResult->getBody());
1591 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1593 if (!empty($parameters)) {
1594 $url .= '?' . http_build_query($parameters);
1597 return bluesky_get($uid, '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1600 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1603 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1604 } catch (\Exception $e) {
1605 Logger::notice('Exception on get', ['exception' => $e]);
1609 if (!$curlResult->isSuccess()) {
1610 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1614 return json_decode($curlResult->getBody());