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\GServer;
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_IMAGE_SIZE = [1000000, 500000, 100000, 50000];
56 * (Currently) hard wired paths for Bluesky services
58 const BLUESKY_DIRECTORY = 'https://plc.directory'; // Path to the directory server service to fetch the PDS of a given DID
59 const BLUESKY_PDS = 'https://bsky.social'; // Path to the personal data server service (PDS) to fetch the DID for a given handle
60 const BLUESKY_WEB = 'https://bsky.app'; // Path to the web interface with the user profile and posts
62 function bluesky_install()
64 Hook::register('load_config', __FILE__, 'bluesky_load_config');
65 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
66 Hook::register('post_local', __FILE__, 'bluesky_post_local');
67 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
68 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
69 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
70 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
71 Hook::register('cron', __FILE__, 'bluesky_cron');
72 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
73 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
74 Hook::register('follow', __FILE__, 'bluesky_follow');
75 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
76 Hook::register('block', __FILE__, 'bluesky_block');
77 Hook::register('unblock', __FILE__, 'bluesky_unblock');
78 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
79 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
80 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
83 function bluesky_load_config(ConfigFileManager $loader)
85 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
88 function bluesky_check_item_notification(array &$notification_data)
90 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
93 $notification_data['profiles'][] = $did;
97 function bluesky_probe_detect(array &$hookData)
99 // Don't overwrite an existing result
100 if (isset($hookData['result'])) {
104 // Avoid a lookup for the wrong network
105 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
109 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
110 if (empty($pconfig['uid'])) {
114 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
115 $did = $hookData['uri'];
116 } elseif (preg_match('#^' . BLUESKY_WEB . '/profile/(.+)#', $hookData['uri'], $matches)) {
117 $did = bluesky_get_did($matches[1]);
125 $token = bluesky_get_token($pconfig['uid']);
130 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
135 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
137 $hookData['result']['baseurl'] = bluesky_get_pds($did);
139 // Preparing probe data. This differs slightly from the contact array
140 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
141 $hookData['result']['photo'] = $data->avatar ?? '';
142 $hookData['result']['header'] = $data->banner ?? '';
143 $hookData['result']['batch'] = '';
144 $hookData['result']['notify'] = '';
145 $hookData['result']['poll'] = '';
146 $hookData['result']['poco'] = '';
147 $hookData['result']['pubkey'] = '';
148 $hookData['result']['priority'] = 0;
149 $hookData['result']['guid'] = '';
152 function bluesky_item_by_link(array &$hookData)
154 // Don't overwrite an existing result
155 if (isset($hookData['item_id'])) {
159 $token = bluesky_get_token($hookData['uid']);
164 if (!preg_match('#^' . BLUESKY_WEB . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
168 $did = bluesky_get_did($matches[1]);
173 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
175 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
177 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, 0);
178 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
180 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
181 if (!empty($item['id'])) {
182 $hookData['item_id'] = $item['id'];
187 function bluesky_support_follow(array &$data)
189 if ($data['protocol'] == Protocol::BLUESKY) {
190 $data['result'] = true;
194 function bluesky_support_probe(array &$data)
196 if ($data['protocol'] == Protocol::BLUESKY) {
197 $data['result'] = true;
201 function bluesky_follow(array &$hook_data)
203 $token = bluesky_get_token($hook_data['uid']);
208 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
209 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
210 if (empty($contact)) {
215 'subject' => $contact['url'],
216 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
217 '$type' => 'app.bsky.graph.follow'
221 'collection' => 'app.bsky.graph.follow',
222 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
226 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
227 if (!empty($activity->uri)) {
228 $hook_data['contact'] = $contact;
229 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
233 function bluesky_unfollow(array &$hook_data)
235 $token = bluesky_get_token($hook_data['uid']);
240 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
244 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
245 if (empty($data->viewer) || empty($data->viewer->following)) {
249 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
251 $hook_data['result'] = true;
254 function bluesky_block(array &$hook_data)
256 $token = bluesky_get_token($hook_data['uid']);
261 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
262 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
263 if (empty($contact)) {
268 'subject' => $contact['url'],
269 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
270 '$type' => 'app.bsky.graph.block'
274 'collection' => 'app.bsky.graph.block',
275 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
279 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
280 if (!empty($activity->uri)) {
281 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
282 if (!empty($cdata['user'])) {
283 Contact::remove($cdata['user']);
285 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
289 function bluesky_unblock(array &$hook_data)
291 $token = bluesky_get_token($hook_data['uid']);
296 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
300 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
301 if (empty($data->viewer) || empty($data->viewer->blocking)) {
305 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
307 $hook_data['result'] = true;
310 function bluesky_settings(array &$data)
312 if (!DI::userSession()->getLocalUserId()) {
316 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
317 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
318 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
319 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
320 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
321 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
322 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
323 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
325 $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.');
327 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
328 $html = Renderer::replaceMacros($t, [
329 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
330 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
331 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
332 '$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.')],
333 '$pds' => ['bluesky_pds', DI::l10n()->t('Personal Data Server'), $pds, DI::l10n()->t('The personal data server (PDS) is the system that hosts your profile.'), '', 'readonly'],
334 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
335 '$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'],
336 '$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.")],
341 'connector' => 'bluesky',
342 'title' => DI::l10n()->t('Bluesky Import/Export'),
343 'image' => 'images/bluesky.jpg',
344 'enabled' => $enabled,
349 function bluesky_settings_post(array &$b)
351 if (empty($_POST['bluesky-submit'])) {
355 $old_pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
356 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
357 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
359 $handle = $_POST['bluesky_handle'];
361 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
362 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
363 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
364 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
365 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
367 if (!empty($host) && !empty($handle)) {
368 if (empty($old_did) || $old_handle != $handle) {
369 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
371 if (empty($old_pds) || $old_handle != $handle) {
372 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'pds', bluesky_get_pds(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did')));
375 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
376 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
379 if (!empty($_POST['bluesky_password'])) {
380 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
384 function bluesky_jot_nets(array &$jotnets_fields)
386 if (!DI::userSession()->getLocalUserId()) {
390 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
391 $jotnets_fields[] = [
392 'type' => 'checkbox',
395 DI::l10n()->t('Post to Bluesky'),
396 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
402 function bluesky_cron()
404 $last = DI::keyValue()->get('bluesky_last_poll');
406 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
407 if (!$poll_interval) {
408 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
412 $next = $last + ($poll_interval * 60);
413 if ($next > time()) {
414 Logger::notice('poll interval not reached');
418 Logger::notice('cron_start');
420 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
421 if ($abandon_days < 1) {
425 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
427 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
428 foreach ($pconfigs as $pconfig) {
429 if ($abandon_days != 0) {
430 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
431 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
436 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
437 bluesky_get_token($pconfig['uid']);
439 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
440 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
442 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
443 $feeds = bluesky_get_feeds($pconfig['uid']);
444 foreach ($feeds as $feed) {
445 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
450 $last_clean = DI::keyValue()->get('bluesky_last_clean');
451 if (empty($last_clean) || ($last_clean + 86400 < time())) {
452 Logger::notice('Start contact cleanup');
453 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
454 while ($contact = DBA::fetch($contacts)) {
455 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
457 DBA::close($contacts);
458 DI::keyValue()->set('bluesky_last_clean', time());
459 Logger::notice('Contact cleanup done');
462 Logger::notice('cron_end');
464 DI::keyValue()->set('bluesky_last_poll', time());
467 function bluesky_hook_fork(array &$b)
469 if ($b['name'] != 'notifier_normal') {
475 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
476 DI::logger()->info('Editing is not supported by the addon');
477 $b['execute'] = false;
481 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
482 // Don't post if it isn't a reply to a bluesky post
483 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
484 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
485 $b['execute'] = false;
488 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
489 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
490 $b['execute'] = false;
495 function bluesky_post_local(array &$b)
501 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
505 if ($b['private'] || $b['parent']) {
509 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
510 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
512 // if API is used, default to the chosen settings
513 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
517 if (!$bluesky_enable) {
521 if (strlen($b['postopts'])) {
522 $b['postopts'] .= ',';
525 $b['postopts'] .= 'bluesky';
528 function bluesky_send(array &$b)
530 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
534 if ($b['gravity'] != Item::GRAVITY_PARENT) {
535 Logger::debug('Got comment', ['item' => $b]);
538 $uri = bluesky_get_uri_class($b['uri']);
540 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
543 bluesky_delete_post($b['uri'], $b['uid']);
547 $root = bluesky_get_uri_class($b['parent-uri']);
548 $parent = bluesky_get_uri_class($b['thr-parent']);
550 if (empty($root) || empty($parent)) {
551 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
555 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
556 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
557 bluesky_create_post($b, $root, $parent);
559 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
560 bluesky_create_activity($b, $parent);
563 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
567 bluesky_create_post($b);
570 function bluesky_create_activity(array $item, stdClass $parent = null)
573 $token = bluesky_get_token($uid);
578 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
580 if ($item['verb'] == Activity::LIKE) {
582 'subject' => $parent,
583 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
584 '$type' => 'app.bsky.feed.like'
588 'collection' => 'app.bsky.feed.like',
592 } elseif ($item['verb'] == Activity::ANNOUNCE) {
594 'subject' => $parent,
595 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
596 '$type' => 'app.bsky.feed.repost'
600 'collection' => 'app.bsky.feed.repost',
606 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
607 if (empty($activity)) {
610 Logger::debug('Activity done', ['return' => $activity]);
611 $uri = bluesky_get_uri($activity);
612 Item::update(['extid' => $uri], ['id' => $item['id']]);
613 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
616 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
619 $token = bluesky_get_token($uid);
624 // Try to fetch the language from the post itself
625 if (!empty($item['language'])) {
626 $language = array_key_first(json_decode($item['language'], true));
631 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
632 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
633 $item['body'] = $urls['body'];
635 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
636 foreach ($msg['parts'] as $key => $part) {
638 $facets = bluesky_get_facets($part, $urls['urls']);
641 'text' => $facets['body'],
642 '$type' => 'app.bsky.feed.post',
643 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
646 if (!empty($language)) {
647 $record['langs'] = [$language];
650 if (!empty($facets['facets'])) {
651 $record['facets'] = $facets['facets'];
655 $record['reply'] = ['root' => $root, 'parent' => $parent];
658 if ($key == count($msg['parts']) - 1) {
659 $record = bluesky_add_embed($uid, $msg, $record);
660 if (empty($record)) {
661 if (Worker::getRetrial() < 3) {
669 'collection' => 'app.bsky.feed.post',
674 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
675 if (empty($parent)) {
681 Logger::debug('Posting done', ['return' => $parent]);
685 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
686 $uri = bluesky_get_uri($parent);
687 Item::update(['extid' => $uri], ['id' => $item['id']]);
688 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
693 function bluesky_get_urls(string $body): array
695 // Remove all hashtag and mention links
696 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
698 $body = BBCode::expandVideoLinks($body);
701 // Search for pure links
702 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
703 foreach ($matches as $match) {
704 $text = Strings::getStyledURL($match[1]);
705 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
706 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
707 $body = str_replace($match[0], $hash, $body);
711 // Search for links with descriptions
712 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
713 foreach ($matches as $match) {
714 if ($match[1] == $match[2]) {
715 $text = Strings::getStyledURL($match[1]);
719 if (mb_strlen($text) < 100) {
720 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
721 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
722 $body = str_replace($match[0], $hash, $body);
724 $text = Strings::getStyledURL($match[1]);
725 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
726 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
727 $body = str_replace($match[0], $text . ' ' . $hash, $body);
732 return ['body' => $body, 'urls' => $urls];
735 function bluesky_get_hash_for_url(string $text, int $linklength): string
737 if ($linklength <= 10) {
738 return '|' . hash('crc32', $text) . '|';
740 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
743 function bluesky_get_facets(string $body, array $urls): array
747 foreach ($urls as $url) {
748 $pos = strpos($body, $url['hash']);
749 if ($pos === false) {
753 $prefix = substr($body, 0, $pos);
758 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
760 $facet = new stdClass;
761 $facet->index = new stdClass;
762 $facet->index->byteEnd = $pos + strlen($url['text']);
763 $facet->index->byteStart = $pos;
765 $feature = new stdClass;
766 $feature->uri = $url['url'];
768 $feature->$type = 'app.bsky.richtext.facet#link';
770 $facet->features = [$feature];
774 return ['facets' => $facets, 'body' => $body];
777 function bluesky_add_embed(int $uid, array $msg, array $record): array
779 if (($msg['type'] != 'link') && !empty($msg['images'])) {
781 foreach ($msg['images'] as $image) {
782 if (count($images) == 4) {
785 $photo = Photo::selectFirst([], ['id' => $image['id']]);
786 $blob = bluesky_upload_blob($uid, $photo);
790 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
792 if (!empty($images)) {
793 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
795 } elseif ($msg['type'] == 'link') {
797 '$type' => 'app.bsky.embed.external',
799 'uri' => $msg['url'],
800 'title' => $msg['title'] ?? '',
801 'description' => $msg['description'] ?? '',
804 if (!empty($msg['image'])) {
805 $photo = Photo::createPhotoForExternalResource($msg['image']);
806 $blob = bluesky_upload_blob($uid, $photo);
808 $record['embed']['external']['thumb'] = $blob;
815 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
817 $retrial = Worker::getRetrial();
818 $content = Photo::getImageForPhoto($photo);
820 $picture = new Image($content, $photo['type']);
821 $height = $picture->getHeight();
822 $width = $picture->getWidth();
823 $size = strlen($content);
825 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
826 $new_height = $picture->getHeight();
827 $new_width = $picture->getWidth();
828 $content = $picture->asString();
829 $new_size = strlen($content);
831 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]);
833 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
835 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]);
839 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]);
843 function bluesky_delete_post(string $uri, int $uid)
845 $parts = bluesky_get_uri_parts($uri);
847 Logger::debug('No uri delected', ['uri' => $uri]);
850 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
851 Logger::debug('Deleted', ['parts' => $parts]);
854 function bluesky_fetch_timeline(int $uid)
856 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
861 if (empty($data->feed)) {
865 foreach (array_reverse($data->feed) as $entry) {
866 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
867 if (!empty($entry->reason)) {
868 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
872 // @todo Support paging
873 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
876 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
879 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
883 $contact = bluesky_get_contact($reason->by, $uid, $uid);
886 'network' => Protocol::BLUESKY,
889 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
890 'private' => Item::UNLISTED,
891 'verb' => Activity::POST,
892 'contact-id' => $contact['id'],
893 'author-name' => $contact['name'],
894 'author-link' => $contact['url'],
895 'author-avatar' => $contact['avatar'],
896 'verb' => Activity::ANNOUNCE,
897 'body' => Activity::ANNOUNCE,
898 'gravity' => Item::GRAVITY_ACTIVITY,
899 'object-type' => Activity\ObjectType::NOTE,
900 'thr-parent' => $uri,
903 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
907 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
908 $item['owner-name'] = $item['author-name'];
909 $item['owner-link'] = $item['author-link'];
910 $item['owner-avatar'] = $item['author-avatar'];
911 if (Item::insert($item)) {
912 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
913 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
917 function bluesky_fetch_notifications(int $uid)
919 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
920 if (empty($data->notifications)) {
923 foreach ($data->notifications as $notification) {
924 $uri = bluesky_get_uri($notification);
925 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
926 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
929 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
930 switch ($notification->reason) {
932 $item = bluesky_get_header($notification, $uri, $uid, $uid);
933 $item['gravity'] = Item::GRAVITY_ACTIVITY;
934 $item['body'] = $item['verb'] = Activity::LIKE;
935 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
936 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
937 if (!empty($item['thr-parent'])) {
938 $data = Item::insert($item);
939 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
941 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
946 $item = bluesky_get_header($notification, $uri, $uid, $uid);
947 $item['gravity'] = Item::GRAVITY_ACTIVITY;
948 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
949 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
950 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
951 if (!empty($item['thr-parent'])) {
952 $data = Item::insert($item);
953 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
955 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
960 $contact = bluesky_get_contact($notification->author, $uid, $uid);
961 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
965 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
966 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
970 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
971 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
975 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
976 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
980 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
986 function bluesky_fetch_feed(int $uid, string $feed)
988 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
993 if (empty($data->feed)) {
997 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
998 if (!empty($feeddata)) {
999 $feedurl = $feeddata->view->uri;
1000 $feedname = $feeddata->view->displayName;
1006 foreach (array_reverse($data->feed) as $entry) {
1007 $contact = bluesky_get_contact($entry->post->author, 0, $uid);
1008 $languages = $entry->post->record->langs ?? [];
1010 if (!Relay::isWantedLanguage($entry->post->record->text, 0, $contact['id'] ?? 0, $languages)) {
1011 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
1014 $id = bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
1016 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
1017 if (!empty($post['uri-id'])) {
1018 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
1019 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
1021 Logger::notice('Post not found', ['id' => $id, 'entry' => $entry]);
1024 if (!empty($entry->reason)) {
1025 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1030 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
1032 $uri = bluesky_get_uri($post);
1034 if ($id = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $uid])) {
1038 if ($id = Post::selectFirst(['id'], ['extid' => $uri, 'uid' => $uid])) {
1042 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1044 $item = bluesky_get_header($post, $uri, $uid, $uid);
1045 $item = bluesky_get_content($item, $post->record, $uri, $uid, $level);
1050 if (!empty($post->embed)) {
1051 $item = bluesky_add_media($post->embed, $item, $uid, $level);
1054 if (empty($item['post-reason'])) {
1055 $item['post-reason'] = $post_reason;
1058 return item::insert($item);
1061 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1063 $parts = bluesky_get_uri_parts($uri);
1064 if (empty($post->author)) {
1067 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1069 'network' => Protocol::BLUESKY,
1073 'guid' => $post->cid,
1074 'private' => Item::UNLISTED,
1075 'verb' => Activity::POST,
1076 'contact-id' => $contact['id'],
1077 'author-name' => $contact['name'],
1078 'author-link' => $contact['url'],
1079 'author-avatar' => $contact['avatar'],
1080 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1081 'source' => json_encode($post),
1084 $item['uri-id'] = ItemURI::getIdByURI($uri);
1085 $item['owner-name'] = $item['author-name'];
1086 $item['owner-link'] = $item['author-link'];
1087 $item['owner-avatar'] = $item['author-avatar'];
1089 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1090 $item['post-reason'] = Item::PR_FOLLOWER;
1096 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $level): array
1102 if (!empty($record->reply)) {
1103 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1104 if ($item['parent-uri'] != $uri) {
1105 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id'], $level);
1106 if (empty($item['parent-uri'])) {
1111 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1112 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1113 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], $level, $item['parent-uri']);
1114 if (empty($item['thr-parent'])) {
1120 $item['body'] = bluesky_get_text($record);
1121 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1122 $item['transmitted-languages'] = $record->langs ?? [];
1126 function bluesky_get_text(stdClass $record): string
1128 $text = $record->text ?? '';
1130 if (empty($record->facets)) {
1135 foreach ($record->facets as $facet) {
1136 $facets[$facet->index->byteStart] = $facet;
1140 foreach ($facets as $facet) {
1141 $prefix = substr($text, 0, $facet->index->byteStart);
1142 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1143 $suffix = substr($text, $facet->index->byteEnd);
1147 foreach ($facet->features as $feature) {
1149 switch ($feature->$type) {
1150 case 'app.bsky.richtext.facet#link':
1151 $url = $feature->uri;
1154 case 'app.bsky.richtext.facet#mention':
1155 $contact = Contact::getByURL($feature->did, null, ['id']);
1156 if (!empty($contact['id'])) {
1157 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1158 if (substr($linktext, 0, 1) == '@') {
1160 $linktext = substr($linktext, 1);
1166 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1171 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1177 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1180 switch ($embed->$type) {
1181 case 'app.bsky.embed.images#view':
1182 foreach ($embed->images as $image) {
1184 'uri-id' => $item['uri-id'],
1185 'type' => Post\Media::IMAGE,
1186 'url' => $image->fullsize,
1187 'preview' => $image->thumb,
1188 'description' => $image->alt,
1190 Post\Media::insert($media);
1194 case 'app.bsky.embed.external#view':
1196 'uri-id' => $item['uri-id'],
1197 'type' => Post\Media::HTML,
1198 'url' => $embed->external->uri,
1199 'name' => $embed->external->title,
1200 'description' => $embed->external->description,
1202 Post\Media::insert($media);
1205 case 'app.bsky.embed.record#view':
1206 $uri = bluesky_get_uri($embed->record);
1207 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1208 if (empty($shared)) {
1209 if (empty($embed->record->value)) {
1210 Logger::info('Record has got no value', ['record' => $embed->record]);
1213 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1214 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1215 if (!empty($shared)) {
1216 if (!empty($embed->record->embeds)) {
1217 foreach ($embed->record->embeds as $single) {
1218 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1221 Item::insert($shared);
1224 if (!empty($shared['uri-id'])) {
1225 $item['quote-uri-id'] = $shared['uri-id'];
1229 case 'app.bsky.embed.recordWithMedia#view':
1230 $uri = bluesky_get_uri($embed->record->record);
1231 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1232 if (empty($shared)) {
1233 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1234 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1235 if (!empty($shared)) {
1236 if (!empty($embed->record->record->embeds)) {
1237 foreach ($embed->record->record->embeds as $single) {
1238 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1241 Item::insert($shared);
1244 if (!empty($shared['uri-id'])) {
1245 $item['quote-uri-id'] = $shared['uri-id'];
1248 if (!empty($embed->media)) {
1249 $item = bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1254 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1260 function bluesky_get_uri(stdClass $post): string
1262 if (empty($post->cid)) {
1263 Logger::info('Invalid URI', ['post' => $post]);
1266 return $post->uri . ':' . $post->cid;
1269 function bluesky_get_uri_class(string $uri): ?stdClass
1275 $elements = explode(':', $uri);
1276 if (empty($elements) || ($elements[0] != 'at')) {
1277 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1278 return bluesky_get_uri_class($post['extid'] ?? '');
1281 $class = new stdClass;
1283 $class->cid = array_pop($elements);
1284 $class->uri = implode(':', $elements);
1286 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1287 $class->uri .= ':' . $class->cid;
1294 function bluesky_get_uri_parts(string $uri): ?stdClass
1296 $class = bluesky_get_uri_class($uri);
1297 if (empty($class)) {
1301 $parts = explode('/', substr($class->uri, 5));
1303 $class = new stdClass;
1305 $class->repo = $parts[0];
1306 $class->collection = $parts[1];
1307 $class->rkey = $parts[2];
1312 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1314 $fetched_uri = bluesky_fetch_post($uri, $uid);
1315 if (!empty($fetched_uri)) {
1316 return $fetched_uri;
1319 if (++$level > 100) {
1320 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1321 // When the level is too deep we will fallback to the parent uri.
1322 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1326 $class = bluesky_get_uri_class($uri);
1327 $fetch_uri = $class->uri;
1329 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1330 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1332 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1336 Logger::debug('Reply count', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1339 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1344 return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1347 function bluesky_fetch_post(string $uri, int $uid): string
1349 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1350 Logger::debug('Post exists', ['uri' => $uri]);
1354 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1355 if (!empty($reply['uri'])) {
1356 Logger::debug('Post with extid exists', ['uri' => $uri]);
1357 return $reply['uri'];
1362 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1364 if (empty($thread->post)) {
1365 Logger::info('Invalid post', ['post' => $thread]);
1368 $uri = bluesky_get_uri($thread->post);
1370 $fetched_uri = bluesky_fetch_post($uri, $uid);
1371 if (empty($fetched_uri)) {
1372 Logger::debug('Process missing post', ['uri' => $uri]);
1373 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1374 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1375 if (!empty($item)) {
1376 $item['post-reason'] = Item::PR_FETCHED;
1378 if (!empty($cdata['public'])) {
1379 $item['causer-id'] = $cdata['public'];
1382 if (!empty($thread->post->embed)) {
1383 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1385 $id = Item::insert($item);
1387 Logger::info('Item has not not been stored', ['uri' => $uri]);
1390 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1392 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1396 Logger::debug('Post exists', ['uri' => $uri]);
1397 $uri = $fetched_uri;
1400 foreach ($thread->replies ?? [] as $reply) {
1401 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1402 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1408 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1410 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1411 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1413 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1415 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1417 $public_fields['uid'] = 0;
1418 $public_fields['rel'] = Contact::NOTHING;
1420 if (empty($contact)) {
1421 $cid = Contact::insert($public_fields);
1423 $cid = $contact['id'];
1424 Contact::update($public_fields, ['id' => $cid], true);
1428 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1430 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1431 if (!isset($fields['rel']) && isset($contact['rel'])) {
1432 $fields['rel'] = $contact['rel'];
1433 } elseif (!isset($fields['rel'])) {
1434 $fields['rel'] = Contact::NOTHING;
1438 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1439 if (empty($contact)) {
1440 $cid = Contact::insert($fields);
1442 $cid = $contact['id'];
1443 Contact::update($fields, ['id' => $cid], true);
1445 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1447 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1449 if (!empty($author->avatar)) {
1450 Contact::updateAvatar($cid, $author->avatar);
1453 return Contact::getById($cid);
1456 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1460 'network' => Protocol::BLUESKY,
1464 'readonly' => false,
1466 'url' => $author->did,
1467 'nurl' => $author->did,
1468 'alias' => BLUESKY_WEB . '/profile/' . $author->handle,
1469 'name' => $author->displayName ?? $author->handle,
1470 'nick' => $author->handle,
1471 'addr' => $author->handle,
1475 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1479 $fields['baseurl'] = bluesky_get_pds($author->did);
1480 if (!empty($fields['baseurl'])) {
1481 GServer::check($fields['baseurl'], Protocol::BLUESKY);
1482 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
1485 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1487 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1491 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1493 if (!empty($data->description)) {
1494 $fields['about'] = HTML::toBBCode($data->description);
1497 if (!empty($data->banner)) {
1498 $fields['header'] = $data->banner;
1501 if (!empty($data->viewer)) {
1502 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1503 $fields['rel'] = Contact::FRIEND;
1504 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1505 $fields['rel'] = Contact::SHARING;
1506 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1507 $fields['rel'] = Contact::FOLLOWER;
1509 $fields['rel'] = Contact::NOTHING;
1513 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1517 function bluesky_get_feeds(int $uid): array
1520 $preferences = bluesky_get_preferences($uid);
1521 foreach ($preferences->preferences as $preference) {
1522 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1523 return $preference->pinned ?? [];
1529 function bluesky_get_preferences(int $uid): stdClass
1531 $cachekey = 'bluesky:preferences:' . $uid;
1532 $data = DI::cache()->get($cachekey);
1533 if (!is_null($data)) {
1537 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1539 DI::cache()->set($cachekey, $data, Duration::HOUR);
1543 function bluesky_get_did(string $handle): string
1545 $data = bluesky_get(BLUESKY_PDS . '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1549 Logger::debug('Got DID', ['return' => $data]);
1553 function bluesky_get_user_pds(int $uid): string
1555 $pds = DI::pConfig()->get($uid, 'bluesky', 'pds');
1559 $pds = bluesky_get_pds(DI::pConfig()->get($uid, 'bluesky', 'did'));
1560 DI::pConfig()->set($uid, 'bluesky', 'pds', $pds);
1564 function bluesky_get_pds(string $did): ?string
1566 $data = bluesky_get(BLUESKY_DIRECTORY . '/' . $did);
1567 if (empty($data) || empty($data->service)) {
1571 foreach ($data->service as $service) {
1572 if (($service->id == '#atproto_pds') && ($service->type == 'AtprotoPersonalDataServer') && !empty($service->serviceEndpoint)) {
1573 return $service->serviceEndpoint;
1580 function bluesky_get_token(int $uid): string
1582 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1583 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1584 if (empty($token)) {
1588 if ($created + 300 < time()) {
1589 return bluesky_refresh_token($uid);
1594 function bluesky_refresh_token(int $uid): string
1596 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1598 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1603 Logger::debug('Refreshed token', ['return' => $data]);
1604 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1605 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1606 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1607 return $data->accessJwt;
1610 function bluesky_create_token(int $uid, string $password): string
1612 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1614 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1619 Logger::debug('Created token', ['return' => $data]);
1620 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1621 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1622 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1623 return $data->accessJwt;
1626 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1628 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1631 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1634 $curlResult = DI::httpClient()->post(bluesky_get_user_pds($uid) . $url, $params, $headers);
1635 } catch (\Exception $e) {
1636 Logger::notice('Exception on post', ['exception' => $e]);
1640 if (!$curlResult->isSuccess()) {
1641 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1645 return json_decode($curlResult->getBody());
1648 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1650 if (!empty($parameters)) {
1651 $url .= '?' . http_build_query($parameters);
1654 return bluesky_get(bluesky_get_user_pds($uid) . '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1657 function bluesky_get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1660 $curlResult = DI::httpClient()->get($url, $accept_content, $opts);
1661 } catch (\Exception $e) {
1662 Logger::notice('Exception on get', ['exception' => $e]);
1666 if (!$curlResult->isSuccess()) {
1667 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1671 return json_decode($curlResult->getBody());