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\Model\Tag;
45 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
46 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
47 use Friendica\Object\Image;
48 use Friendica\Protocol\Activity;
49 use Friendica\Protocol\Relay;
50 use Friendica\Util\DateTimeFormat;
51 use Friendica\Util\Strings;
53 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
54 const BLUESKY_IMAGE_SIZE = [1000000, 500000, 100000, 50000];
56 const BLUEKSY_STATUS_UNKNOWN = 0;
57 const BLUEKSY_STATUS_TOKEN_OK = 1;
58 const BLUEKSY_STATUS_SUCCESS = 2;
59 const BLUEKSY_STATUS_API_FAIL = 10;
60 const BLUEKSY_STATUS_DID_FAIL = 11;
61 const BLUEKSY_STATUS_PDS_FAIL = 12;
62 const BLUEKSY_STATUS_TOKEN_FAIL = 13;
65 * (Currently) hard wired paths for Bluesky services
67 const BLUESKY_DIRECTORY = 'https://plc.directory'; // Path to the directory server service to fetch the PDS of a given DID
68 const BLUESKY_PDS = 'https://bsky.social'; // Path to the personal data server service (PDS) to fetch the DID for a given handle
69 const BLUESKY_WEB = 'https://bsky.app'; // Path to the web interface with the user profile and posts
71 function bluesky_install()
73 Hook::register('load_config', __FILE__, 'bluesky_load_config');
74 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
75 Hook::register('post_local', __FILE__, 'bluesky_post_local');
76 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
77 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
78 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
79 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
80 Hook::register('cron', __FILE__, 'bluesky_cron');
81 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
82 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
83 Hook::register('follow', __FILE__, 'bluesky_follow');
84 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
85 Hook::register('block', __FILE__, 'bluesky_block');
86 Hook::register('unblock', __FILE__, 'bluesky_unblock');
87 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
88 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
89 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
92 function bluesky_load_config(ConfigFileManager $loader)
94 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
97 function bluesky_check_item_notification(array &$notification_data)
99 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
102 $notification_data['profiles'][] = $did;
106 function bluesky_probe_detect(array &$hookData)
108 // Don't overwrite an existing result
109 if (isset($hookData['result'])) {
113 // Avoid a lookup for the wrong network
114 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
118 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
119 if (empty($pconfig['uid'])) {
123 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
124 $did = $hookData['uri'];
125 } elseif (preg_match('#^' . BLUESKY_WEB . '/profile/(.+)#', $hookData['uri'], $matches)) {
126 $did = bluesky_get_did($matches[1]);
134 $token = bluesky_get_token($pconfig['uid']);
139 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
144 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
146 $hookData['result']['baseurl'] = bluesky_get_pds($did);
148 // Preparing probe data. This differs slightly from the contact array
149 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
150 $hookData['result']['photo'] = $data->avatar ?? '';
151 $hookData['result']['header'] = $data->banner ?? '';
152 $hookData['result']['batch'] = '';
153 $hookData['result']['notify'] = '';
154 $hookData['result']['poll'] = '';
155 $hookData['result']['poco'] = '';
156 $hookData['result']['pubkey'] = '';
157 $hookData['result']['priority'] = 0;
158 $hookData['result']['guid'] = '';
161 function bluesky_item_by_link(array &$hookData)
163 // Don't overwrite an existing result
164 if (isset($hookData['item_id'])) {
168 $token = bluesky_get_token($hookData['uid']);
173 if (!preg_match('#^' . BLUESKY_WEB . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
177 $did = bluesky_get_did($matches[1]);
182 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
184 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
186 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], $hookData['uid'], 0, 0);
187 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
189 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
190 if (!empty($item['id'])) {
191 $hookData['item_id'] = $item['id'];
196 function bluesky_support_follow(array &$data)
198 if ($data['protocol'] == Protocol::BLUESKY) {
199 $data['result'] = true;
203 function bluesky_support_probe(array &$data)
205 if ($data['protocol'] == Protocol::BLUESKY) {
206 $data['result'] = true;
210 function bluesky_follow(array &$hook_data)
212 $token = bluesky_get_token($hook_data['uid']);
217 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
218 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
219 if (empty($contact)) {
224 'subject' => $contact['url'],
225 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
226 '$type' => 'app.bsky.graph.follow'
230 'collection' => 'app.bsky.graph.follow',
231 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
235 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
236 if (!empty($activity->uri)) {
237 $hook_data['contact'] = $contact;
238 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
242 function bluesky_unfollow(array &$hook_data)
244 $token = bluesky_get_token($hook_data['uid']);
249 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
253 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
254 if (empty($data->viewer) || empty($data->viewer->following)) {
258 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
260 $hook_data['result'] = true;
263 function bluesky_block(array &$hook_data)
265 $token = bluesky_get_token($hook_data['uid']);
270 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
271 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
272 if (empty($contact)) {
277 'subject' => $contact['url'],
278 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 '$type' => 'app.bsky.graph.block'
283 'collection' => 'app.bsky.graph.block',
284 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
288 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
289 if (!empty($activity->uri)) {
290 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
291 if (!empty($cdata['user'])) {
292 Contact::remove($cdata['user']);
294 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
298 function bluesky_unblock(array &$hook_data)
300 $token = bluesky_get_token($hook_data['uid']);
305 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
309 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
310 if (empty($data->viewer) || empty($data->viewer->blocking)) {
314 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
316 $hook_data['result'] = true;
319 function bluesky_settings(array &$data)
321 if (!DI::userSession()->getLocalUserId()) {
325 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
326 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
327 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
328 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
329 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
330 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
331 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
332 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
334 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
335 $html = Renderer::replaceMacros($t, [
336 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
337 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
338 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
339 '$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.')],
340 '$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'],
341 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
342 '$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'],
343 '$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.")],
344 '$status' => bluesky_get_status($handle, $did, $pds, $token),
348 'connector' => 'bluesky',
349 'title' => DI::l10n()->t('Bluesky Import/Export'),
350 'image' => 'images/bluesky.jpg',
351 'enabled' => $enabled,
356 function bluesky_get_status(string $handle = null, string $did = null, string $pds = null, string $token = null): string
358 if (empty($handle)) {
359 return DI::l10n()->t('You are not authenticated. Please enter your handle and the app password.');
362 $status = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'status') ?? BLUEKSY_STATUS_UNKNOWN;
364 // Fallback mechanism for connection that had been established before the introduction of the status
365 if ($status == BLUEKSY_STATUS_UNKNOWN) {
367 $status = BLUEKSY_STATUS_DID_FAIL;
368 } elseif (empty($pds)) {
369 $status = BLUEKSY_STATUS_PDS_FAIL;
370 } elseif (!empty($token)) {
371 $status = BLUEKSY_STATUS_TOKEN_OK;
373 $status = BLUEKSY_STATUS_TOKEN_FAIL;
378 case BLUEKSY_STATUS_TOKEN_OK:
379 return DI::l10n()->t("You are authenticated to Bluesky. For security reasons the password isn't stored.");
380 case BLUEKSY_STATUS_SUCCESS:
381 return DI::l10n()->t('The communication with the personal data server service (PDS) is established.');
382 case BLUEKSY_STATUS_API_FAIL;
383 return DI::l10n()->t('Communication issues with the personal data server service (PDS).');
384 case BLUEKSY_STATUS_DID_FAIL:
385 return DI::l10n()->t('The DID for the provided handle could not be detected. Please check if you entered the correct handle.');
386 case BLUEKSY_STATUS_PDS_FAIL:
387 return DI::l10n()->t('The personal data server service (PDS) could not be detected.');
388 case BLUEKSY_STATUS_TOKEN_FAIL:
389 return DI::l10n()->t('The authentication with the provided handle and password failed. Please check if you entered the correct password.');
395 function bluesky_settings_post(array &$b)
397 if (empty($_POST['bluesky-submit'])) {
401 $old_pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
402 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
403 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
405 $handle = trim($_POST['bluesky_handle'], ' @');
407 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
408 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
409 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
410 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
411 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
413 if (!empty($handle)) {
414 if (empty($old_did) || $old_handle != $handle) {
415 $did = bluesky_get_did(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle'));
417 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'status', BLUEKSY_STATUS_DID_FAIL);
419 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', $did);
421 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
423 if (!empty($did) && (empty($old_pds) || $old_handle != $handle)) {
424 $pds = bluesky_get_pds($did);
426 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'status', BLUEKSY_STATUS_PDS_FAIL);
428 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'pds', $pds);
430 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
433 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
434 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
435 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
436 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'refresh_token');
437 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'token_created');
438 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'status');
441 if (!empty($did) && !empty($pds) && !empty($_POST['bluesky_password'])) {
442 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
446 function bluesky_jot_nets(array &$jotnets_fields)
448 if (!DI::userSession()->getLocalUserId()) {
452 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
453 $jotnets_fields[] = [
454 'type' => 'checkbox',
457 DI::l10n()->t('Post to Bluesky'),
458 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
464 function bluesky_cron()
466 $last = (int)DI::keyValue()->get('bluesky_last_poll');
468 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
469 if (!$poll_interval) {
470 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
474 $next = $last + ($poll_interval * 60);
475 if ($next > time()) {
476 Logger::notice('poll interval not reached');
480 Logger::notice('cron_start');
482 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
483 if ($abandon_days < 1) {
487 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
489 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
490 foreach ($pconfigs as $pconfig) {
491 if ($abandon_days != 0) {
492 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
493 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
498 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
499 bluesky_get_token($pconfig['uid']);
501 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid'], $last);
502 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid'], $last);
504 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
505 $feeds = bluesky_get_feeds($pconfig['uid']);
506 foreach ($feeds as $feed) {
507 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed, $last);
512 $last_clean = DI::keyValue()->get('bluesky_last_clean');
513 if (empty($last_clean) || ($last_clean + 86400 < time())) {
514 Logger::notice('Start contact cleanup');
515 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
516 while ($contact = DBA::fetch($contacts)) {
517 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
519 DBA::close($contacts);
520 DI::keyValue()->set('bluesky_last_clean', time());
521 Logger::notice('Contact cleanup done');
524 Logger::notice('cron_end');
526 DI::keyValue()->set('bluesky_last_poll', time());
529 function bluesky_hook_fork(array &$b)
531 if ($b['name'] != 'notifier_normal') {
537 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
538 DI::logger()->info('Editing is not supported by the addon');
539 $b['execute'] = false;
543 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
544 // Don't post if it isn't a reply to a bluesky post
545 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
546 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
547 $b['execute'] = false;
550 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
551 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
552 $b['execute'] = false;
557 function bluesky_post_local(array &$b)
563 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
567 if ($b['private'] || $b['parent']) {
571 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
572 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
574 // if API is used, default to the chosen settings
575 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
579 if (!$bluesky_enable) {
583 if (strlen($b['postopts'])) {
584 $b['postopts'] .= ',';
587 $b['postopts'] .= 'bluesky';
590 function bluesky_send(array &$b)
592 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
596 if ($b['gravity'] != Item::GRAVITY_PARENT) {
597 Logger::debug('Got comment', ['item' => $b]);
600 $uri = bluesky_get_uri_class($b['uri']);
602 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
605 bluesky_delete_post($b['uri'], $b['uid']);
609 $root = bluesky_get_uri_class($b['parent-uri']);
610 $parent = bluesky_get_uri_class($b['thr-parent']);
612 if (empty($root) || empty($parent)) {
613 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
617 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
618 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
619 bluesky_create_post($b, $root, $parent);
621 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
622 bluesky_create_activity($b, $parent);
625 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
629 bluesky_create_post($b);
632 function bluesky_create_activity(array $item, stdClass $parent = null)
635 $token = bluesky_get_token($uid);
640 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
642 if ($item['verb'] == Activity::LIKE) {
644 'subject' => $parent,
645 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
646 '$type' => 'app.bsky.feed.like'
650 'collection' => 'app.bsky.feed.like',
654 } elseif ($item['verb'] == Activity::ANNOUNCE) {
656 'subject' => $parent,
657 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
658 '$type' => 'app.bsky.feed.repost'
662 'collection' => 'app.bsky.feed.repost',
668 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
669 if (empty($activity)) {
672 Logger::debug('Activity done', ['return' => $activity]);
673 $uri = bluesky_get_uri($activity);
674 Item::update(['extid' => $uri], ['id' => $item['id']]);
675 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
678 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
681 $token = bluesky_get_token($uid);
686 // Try to fetch the language from the post itself
687 if (!empty($item['language'])) {
688 $language = array_key_first(json_decode($item['language'], true));
693 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
694 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
695 $item['body'] = $urls['body'];
697 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
698 foreach ($msg['parts'] as $key => $part) {
700 $facets = bluesky_get_facets($part, $urls['urls']);
703 'text' => $facets['body'],
704 '$type' => 'app.bsky.feed.post',
705 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
708 if (!empty($language)) {
709 $record['langs'] = [$language];
712 if (!empty($facets['facets'])) {
713 $record['facets'] = $facets['facets'];
717 $record['reply'] = ['root' => $root, 'parent' => $parent];
720 if ($key == count($msg['parts']) - 1) {
721 $record = bluesky_add_embed($uid, $msg, $record);
722 if (empty($record)) {
723 if (Worker::getRetrial() < 3) {
731 'collection' => 'app.bsky.feed.post',
736 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
737 if (empty($parent)) {
743 Logger::debug('Posting done', ['return' => $parent]);
747 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
748 $uri = bluesky_get_uri($parent);
749 Item::update(['extid' => $uri], ['id' => $item['id']]);
750 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
755 function bluesky_get_urls(string $body): array
757 // Remove all hashtag and mention links
758 $body = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
760 $body = BBCode::expandVideoLinks($body);
763 // Search for hash tags
764 if (preg_match_all("/#\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
765 foreach ($matches as $match) {
766 $text = '#' . $match[2];
767 $urls[] = ['tag' => $match[2], 'text' => $text, 'hash' => $text];
768 $body = str_replace($match[0], $text, $body);
772 // Search for pure links
773 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
774 foreach ($matches as $match) {
775 $text = Strings::getStyledURL($match[1]);
776 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
777 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
778 $body = str_replace($match[0], $hash, $body);
782 // Search for links with descriptions
783 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
784 foreach ($matches as $match) {
785 if ($match[1] == $match[2]) {
786 $text = Strings::getStyledURL($match[1]);
790 if (mb_strlen($text) < 100) {
791 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
792 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
793 $body = str_replace($match[0], $hash, $body);
795 $text = Strings::getStyledURL($match[1]);
796 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
797 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
798 $body = str_replace($match[0], $text . ' ' . $hash, $body);
803 return ['body' => $body, 'urls' => $urls];
806 function bluesky_get_hash_for_url(string $text, int $linklength): string
808 if ($linklength <= 10) {
809 return '|' . hash('crc32', $text) . '|';
811 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
814 function bluesky_get_facets(string $body, array $urls): array
818 foreach ($urls as $url) {
819 $pos = strpos($body, $url['hash']);
820 if ($pos === false) {
824 $prefix = substr($body, 0, $pos);
829 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
831 $facet = new stdClass;
832 $facet->index = new stdClass;
833 $facet->index->byteEnd = $pos + strlen($url['text']);
834 $facet->index->byteStart = $pos;
836 $feature = new stdClass;
839 if (!empty($url['tag'])) {
840 $feature->tag = $url['tag'];
841 $feature->$type = 'app.bsky.richtext.facet#tag';
842 } elseif (!empty($url['url'])) {
843 $feature->uri = $url['url'];
844 $feature->$type = 'app.bsky.richtext.facet#link';
849 $facet->features = [$feature];
853 return ['facets' => $facets, 'body' => $body];
856 function bluesky_add_embed(int $uid, array $msg, array $record): array
858 if (($msg['type'] != 'link') && !empty($msg['images'])) {
860 foreach ($msg['images'] as $image) {
861 if (count($images) == 4) {
864 $photo = Photo::selectFirst([], ['id' => $image['id']]);
865 $blob = bluesky_upload_blob($uid, $photo);
869 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
871 if (!empty($images)) {
872 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
874 } elseif ($msg['type'] == 'link') {
876 '$type' => 'app.bsky.embed.external',
878 'uri' => $msg['url'],
879 'title' => $msg['title'] ?? '',
880 'description' => $msg['description'] ?? '',
883 if (!empty($msg['image'])) {
884 $photo = Photo::createPhotoForExternalResource($msg['image']);
885 $blob = bluesky_upload_blob($uid, $photo);
887 $record['embed']['external']['thumb'] = $blob;
894 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
896 $retrial = Worker::getRetrial();
897 $content = Photo::getImageForPhoto($photo);
899 $picture = new Image($content, $photo['type']);
900 $height = $picture->getHeight();
901 $width = $picture->getWidth();
902 $size = strlen($content);
904 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
905 $new_height = $picture->getHeight();
906 $new_width = $picture->getWidth();
907 $content = $picture->asString();
908 $new_size = strlen($content);
910 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]);
912 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
914 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]);
918 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]);
922 function bluesky_delete_post(string $uri, int $uid)
924 $parts = bluesky_get_uri_parts($uri);
926 Logger::debug('No uri delected', ['uri' => $uri]);
929 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
930 Logger::debug('Deleted', ['parts' => $parts]);
933 function bluesky_fetch_timeline(int $uid, int $last_poll)
935 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
940 if (empty($data->feed)) {
944 foreach (array_reverse($data->feed) as $entry) {
945 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0, $last_poll);
946 if (!empty($entry->reason)) {
947 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
951 // @todo Support paging
952 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
955 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
958 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
962 $contact = bluesky_get_contact($reason->by, $uid, $uid);
965 'network' => Protocol::BLUESKY,
968 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
969 'private' => Item::UNLISTED,
970 'verb' => Activity::POST,
971 'contact-id' => $contact['id'],
972 'author-name' => $contact['name'],
973 'author-link' => $contact['url'],
974 'author-avatar' => $contact['avatar'],
975 'verb' => Activity::ANNOUNCE,
976 'body' => Activity::ANNOUNCE,
977 'gravity' => Item::GRAVITY_ACTIVITY,
978 'object-type' => Activity\ObjectType::NOTE,
979 'thr-parent' => $uri,
982 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
986 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
987 $item['owner-name'] = $item['author-name'];
988 $item['owner-link'] = $item['author-link'];
989 $item['owner-avatar'] = $item['author-avatar'];
990 if (Item::insert($item)) {
991 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
992 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
996 function bluesky_fetch_notifications(int $uid, int $last_poll)
998 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
999 if (empty($data->notifications)) {
1002 foreach ($data->notifications as $notification) {
1003 $uri = bluesky_get_uri($notification);
1004 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
1005 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
1008 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
1009 switch ($notification->reason) {
1011 $item = bluesky_get_header($notification, $uri, $uid, $uid);
1012 $item['gravity'] = Item::GRAVITY_ACTIVITY;
1013 $item['body'] = $item['verb'] = Activity::LIKE;
1014 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
1015 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, $item['contact-id'], 0, $last_poll);
1016 if (!empty($item['thr-parent'])) {
1017 $data = Item::insert($item);
1018 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1020 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
1025 $item = bluesky_get_header($notification, $uri, $uid, $uid);
1026 $item['gravity'] = Item::GRAVITY_ACTIVITY;
1027 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
1028 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
1029 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, $item['contact-id'], 0, $last_poll);
1030 if (!empty($item['thr-parent'])) {
1031 $data = Item::insert($item);
1032 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1034 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
1039 $contact = bluesky_get_contact($notification->author, $uid, $uid);
1040 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
1044 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0, $last_poll);
1045 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1049 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0, $last_poll);
1050 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1054 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0, $last_poll);
1055 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1059 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
1065 function bluesky_fetch_feed(int $uid, string $feed, int $last_poll)
1067 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
1072 if (empty($data->feed)) {
1076 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
1077 if (!empty($feeddata)) {
1078 $feedurl = $feeddata->view->uri;
1079 $feedname = $feeddata->view->displayName;
1085 foreach (array_reverse($data->feed) as $entry) {
1086 $contact = bluesky_get_contact($entry->post->author, 0, $uid);
1087 $languages = $entry->post->record->langs ?? [];
1089 if (!Relay::isWantedLanguage($entry->post->record->text, 0, $contact['id'] ?? 0, $languages)) {
1090 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
1093 $id = bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0, $last_poll);
1095 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
1096 if (!empty($post['uri-id'])) {
1097 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
1098 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
1100 Logger::notice('Post not found', ['id' => $id, 'entry' => $entry]);
1103 if (!empty($entry->reason)) {
1104 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1109 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, int $level, int $last_poll): int
1111 $uri = bluesky_get_uri($post);
1113 if ($id = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $uid])) {
1117 if ($id = Post::selectFirst(['id'], ['extid' => $uri, 'uid' => $uid])) {
1121 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1123 $item = bluesky_get_header($post, $uri, $uid, $uid);
1124 $item = bluesky_get_content($item, $post->record, $uri, $uid, $uid, $level, $last_poll);
1129 if (!empty($post->embed)) {
1130 $item = bluesky_add_media($post->embed, $item, $uid, $level, $last_poll);
1133 if (empty($item['post-reason'])) {
1134 $item['post-reason'] = $post_reason;
1137 return Item::insert($item);
1140 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1142 $parts = bluesky_get_uri_parts($uri);
1143 if (empty($post->author)) {
1146 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1148 'network' => Protocol::BLUESKY,
1152 'guid' => $post->cid,
1153 'private' => Item::UNLISTED,
1154 'verb' => Activity::POST,
1155 'contact-id' => $contact['id'],
1156 'author-name' => $contact['name'],
1157 'author-link' => $contact['url'],
1158 'author-avatar' => $contact['avatar'],
1159 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1160 'source' => json_encode($post),
1163 $item['uri-id'] = ItemURI::getIdByURI($uri);
1164 $item['owner-name'] = $item['author-name'];
1165 $item['owner-link'] = $item['author-link'];
1166 $item['owner-avatar'] = $item['author-avatar'];
1168 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1169 $item['post-reason'] = Item::PR_FOLLOWER;
1175 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $fetch_uid, int $level, int $last_poll): array
1181 if (!empty($record->reply)) {
1182 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1183 if ($item['parent-uri'] != $uri) {
1184 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $fetch_uid, $item['contact-id'], $level, $last_poll);
1185 if (empty($item['parent-uri'])) {
1190 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1191 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1192 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $fetch_uid, $item['contact-id'], $level, $last_poll, $item['parent-uri']);
1193 if (empty($item['thr-parent'])) {
1199 $item['body'] = bluesky_get_text($record, $item['uri-id']);
1200 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1201 $item['transmitted-languages'] = $record->langs ?? [];
1203 if (($last_poll != 0) && strtotime($item['created']) > $last_poll) {
1204 $item['received'] = $item['created'];
1210 function bluesky_get_text(stdClass $record, int $uri_id): string
1212 $text = $record->text ?? '';
1214 if (empty($record->facets)) {
1219 foreach ($record->facets as $facet) {
1220 $facets[$facet->index->byteStart] = $facet;
1224 foreach ($facets as $facet) {
1225 $prefix = substr($text, 0, $facet->index->byteStart);
1226 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1227 $suffix = substr($text, $facet->index->byteEnd);
1231 foreach ($facet->features as $feature) {
1233 switch ($feature->$type) {
1234 case 'app.bsky.richtext.facet#link':
1235 $url = $feature->uri;
1238 case 'app.bsky.richtext.facet#mention':
1239 $contact = Contact::getByURL($feature->did, null, ['id']);
1240 if (!empty($contact['id'])) {
1241 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1242 if (substr($linktext, 0, 1) == '@') {
1244 $linktext = substr($linktext, 1);
1249 case 'app.bsky.richtext.facet#tag';
1250 Tag::store($uri_id, Tag::HASHTAG, $feature->tag);
1251 $url = DI::baseUrl() . '/search?tag=' . urlencode($feature->tag);
1252 $linktext = '#' . $feature->tag;
1256 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'feature' => $feature, 'record' => $record]);
1261 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1267 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level, int $last_poll): array
1270 switch ($embed->$type) {
1271 case 'app.bsky.embed.images#view':
1272 foreach ($embed->images as $image) {
1274 'uri-id' => $item['uri-id'],
1275 'type' => Post\Media::IMAGE,
1276 'url' => $image->fullsize,
1277 'preview' => $image->thumb,
1278 'description' => $image->alt,
1280 Post\Media::insert($media);
1284 case 'app.bsky.embed.external#view':
1286 'uri-id' => $item['uri-id'],
1287 'type' => Post\Media::HTML,
1288 'url' => $embed->external->uri,
1289 'name' => $embed->external->title,
1290 'description' => $embed->external->description,
1292 Post\Media::insert($media);
1295 case 'app.bsky.embed.record#view':
1296 $uri = bluesky_get_uri($embed->record);
1297 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1298 if (empty($shared)) {
1299 if (empty($embed->record->value)) {
1300 Logger::info('Record has got no value', ['record' => $embed->record]);
1303 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1304 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $fetch_uid, $level, $last_poll);
1305 if (!empty($shared)) {
1306 if (!empty($embed->record->embeds)) {
1307 foreach ($embed->record->embeds as $single) {
1308 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level, $last_poll);
1311 Item::insert($shared);
1314 if (!empty($shared['uri-id'])) {
1315 $item['quote-uri-id'] = $shared['uri-id'];
1319 case 'app.bsky.embed.recordWithMedia#view':
1320 $uri = bluesky_get_uri($embed->record->record);
1321 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1322 if (empty($shared)) {
1323 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1324 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $fetch_uid, $level, $last_poll);
1325 if (!empty($shared)) {
1326 if (!empty($embed->record->record->embeds)) {
1327 foreach ($embed->record->record->embeds as $single) {
1328 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level, $last_poll);
1331 Item::insert($shared);
1334 if (!empty($shared['uri-id'])) {
1335 $item['quote-uri-id'] = $shared['uri-id'];
1338 if (!empty($embed->media)) {
1339 $item = bluesky_add_media($embed->media, $item, $fetch_uid, $level, $last_poll);
1344 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1350 function bluesky_get_uri(stdClass $post): string
1352 if (empty($post->cid)) {
1353 Logger::info('Invalid URI', ['post' => $post]);
1356 return $post->uri . ':' . $post->cid;
1359 function bluesky_get_uri_class(string $uri): ?stdClass
1365 $elements = explode(':', $uri);
1366 if (empty($elements) || ($elements[0] != 'at')) {
1367 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1368 return bluesky_get_uri_class($post['extid'] ?? '');
1371 $class = new stdClass;
1373 $class->cid = array_pop($elements);
1374 $class->uri = implode(':', $elements);
1376 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1377 $class->uri .= ':' . $class->cid;
1384 function bluesky_get_uri_parts(string $uri): ?stdClass
1386 $class = bluesky_get_uri_class($uri);
1387 if (empty($class)) {
1391 $parts = explode('/', substr($class->uri, 5));
1393 $class = new stdClass;
1395 $class->repo = $parts[0];
1396 $class->collection = $parts[1];
1397 $class->rkey = $parts[2];
1402 function bluesky_fetch_missing_post(string $uri, int $uid, int $fetch_uid, int $causer, int $level, int $last_poll = 0, string $fallback = ''): string
1404 $fetched_uri = bluesky_fetch_post($uri, $uid);
1405 if (!empty($fetched_uri)) {
1406 return $fetched_uri;
1409 if (++$level > 100) {
1410 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1411 // When the level is too deep we will fallback to the parent uri.
1412 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1416 $class = bluesky_get_uri_class($uri);
1417 $fetch_uri = $class->uri;
1419 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1420 $data = bluesky_xrpc_get($fetch_uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1422 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1426 Logger::debug('Reply count', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1429 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1434 return bluesky_process_thread($data->thread, $uid, $fetch_uid, $cdata, $level, $last_poll);
1437 function bluesky_fetch_post(string $uri, int $uid): string
1439 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1440 Logger::debug('Post exists', ['uri' => $uri]);
1444 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1445 if (!empty($reply['uri'])) {
1446 Logger::debug('Post with extid exists', ['uri' => $uri]);
1447 return $reply['uri'];
1452 function bluesky_process_thread(stdClass $thread, int $uid, int $fetch_uid, array $cdata, int $level, int $last_poll): string
1454 if (empty($thread->post)) {
1455 Logger::info('Invalid post', ['post' => $thread]);
1458 $uri = bluesky_get_uri($thread->post);
1460 $fetched_uri = bluesky_fetch_post($uri, $uid);
1461 if (empty($fetched_uri)) {
1462 Logger::debug('Process missing post', ['uri' => $uri]);
1463 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1464 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $fetch_uid, $level, $last_poll);
1465 if (!empty($item)) {
1466 $item['post-reason'] = Item::PR_FETCHED;
1468 if (!empty($cdata['public'])) {
1469 $item['causer-id'] = $cdata['public'];
1472 if (!empty($thread->post->embed)) {
1473 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level, $last_poll);
1475 $id = Item::insert($item);
1477 Logger::info('Item has not not been stored', ['uri' => $uri]);
1480 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1482 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1486 Logger::debug('Post exists', ['uri' => $uri]);
1487 $uri = $fetched_uri;
1490 foreach ($thread->replies ?? [] as $reply) {
1491 $reply_uri = bluesky_process_thread($reply, $uid, $fetch_uid, $cdata, $level, $last_poll);
1492 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1498 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1500 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1501 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1503 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1505 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1507 $public_fields['uid'] = 0;
1508 $public_fields['rel'] = Contact::NOTHING;
1510 if (empty($contact)) {
1511 $cid = Contact::insert($public_fields);
1513 $cid = $contact['id'];
1514 Contact::update($public_fields, ['id' => $cid], true);
1518 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1520 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1521 if (!isset($fields['rel']) && isset($contact['rel'])) {
1522 $fields['rel'] = $contact['rel'];
1523 } elseif (!isset($fields['rel'])) {
1524 $fields['rel'] = Contact::NOTHING;
1528 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1529 if (empty($contact)) {
1530 $cid = Contact::insert($fields);
1532 $cid = $contact['id'];
1533 Contact::update($fields, ['id' => $cid], true);
1535 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1537 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1539 if (!empty($author->avatar)) {
1540 Contact::updateAvatar($cid, $author->avatar);
1543 return Contact::getById($cid);
1546 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1550 'network' => Protocol::BLUESKY,
1554 'readonly' => false,
1556 'url' => $author->did,
1557 'nurl' => $author->did,
1558 'alias' => BLUESKY_WEB . '/profile/' . $author->handle,
1559 'name' => $author->displayName ?? $author->handle,
1560 'nick' => $author->handle,
1561 'addr' => $author->handle,
1565 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1569 $fields['baseurl'] = bluesky_get_pds($author->did);
1570 if (!empty($fields['baseurl'])) {
1571 GServer::check($fields['baseurl'], Protocol::BLUESKY);
1572 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
1575 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1577 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1581 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1583 if (!empty($data->description)) {
1584 $fields['about'] = HTML::toBBCode($data->description);
1587 if (!empty($data->banner)) {
1588 $fields['header'] = $data->banner;
1591 if (!empty($data->viewer)) {
1592 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1593 $fields['rel'] = Contact::FRIEND;
1594 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1595 $fields['rel'] = Contact::SHARING;
1596 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1597 $fields['rel'] = Contact::FOLLOWER;
1599 $fields['rel'] = Contact::NOTHING;
1603 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1607 function bluesky_get_feeds(int $uid): array
1610 $preferences = bluesky_get_preferences($uid);
1611 foreach ($preferences->preferences as $preference) {
1612 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1613 return $preference->pinned ?? [];
1619 function bluesky_get_preferences(int $uid): stdClass
1621 $cachekey = 'bluesky:preferences:' . $uid;
1622 $data = DI::cache()->get($cachekey);
1623 if (!is_null($data)) {
1627 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1629 DI::cache()->set($cachekey, $data, Duration::HOUR);
1633 function bluesky_get_did(string $handle): string
1635 $data = bluesky_get(BLUESKY_PDS . '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1639 Logger::debug('Got DID', ['return' => $data]);
1643 function bluesky_get_user_pds(int $uid): string
1645 $pds = DI::pConfig()->get($uid, 'bluesky', 'pds');
1649 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1651 Logger::notice('Empty did for user', ['uid' => $uid]);
1654 $pds = bluesky_get_pds($did);
1655 DI::pConfig()->set($uid, 'bluesky', 'pds', $pds);
1659 function bluesky_get_pds(string $did): ?string
1661 $data = bluesky_get(BLUESKY_DIRECTORY . '/' . $did);
1662 if (empty($data) || empty($data->service)) {
1666 foreach ($data->service as $service) {
1667 if (($service->id == '#atproto_pds') && ($service->type == 'AtprotoPersonalDataServer') && !empty($service->serviceEndpoint)) {
1668 return $service->serviceEndpoint;
1675 function bluesky_get_token(int $uid): string
1677 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1678 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1679 if (empty($token)) {
1683 if ($created + 300 < time()) {
1684 return bluesky_refresh_token($uid);
1689 function bluesky_refresh_token(int $uid): string
1691 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1693 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1698 Logger::debug('Refreshed token', ['return' => $data]);
1699 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1700 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1701 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1702 return $data->accessJwt;
1705 function bluesky_create_token(int $uid, string $password): string
1707 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1709 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1711 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_TOKEN_FAIL);
1715 Logger::debug('Created token', ['return' => $data]);
1716 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1717 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1718 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1719 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_TOKEN_OK);
1720 return $data->accessJwt;
1723 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1725 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1728 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1731 $curlResult = DI::httpClient()->post(bluesky_get_user_pds($uid) . $url, $params, $headers);
1732 } catch (\Exception $e) {
1733 Logger::notice('Exception on post', ['exception' => $e]);
1734 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_API_FAIL);
1738 if (!$curlResult->isSuccess()) {
1739 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1740 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_API_FAIL);
1744 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_SUCCESS);
1745 return json_decode($curlResult->getBody());
1748 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1750 if (!empty($parameters)) {
1751 $url .= '?' . http_build_query($parameters);
1754 $data = bluesky_get(bluesky_get_user_pds($uid) . '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1755 DI::pConfig()->set($uid, 'bluesky', 'status', is_null($data) ? BLUEKSY_STATUS_API_FAIL : BLUEKSY_STATUS_SUCCESS);
1760 function bluesky_get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1763 $curlResult = DI::httpClient()->get($url, $accept_content, $opts);
1764 } catch (\Exception $e) {
1765 Logger::notice('Exception on get', ['exception' => $e]);
1769 if (!$curlResult->isSuccess()) {
1770 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1774 return json_decode($curlResult->getBody());