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\Model\User;
46 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
47 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
48 use Friendica\Object\Image;
49 use Friendica\Protocol\Activity;
50 use Friendica\Protocol\Relay;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Strings;
54 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
55 const BLUESKY_IMAGE_SIZE = [1000000, 500000, 100000, 50000];
57 const BLUEKSY_STATUS_UNKNOWN = 0;
58 const BLUEKSY_STATUS_TOKEN_OK = 1;
59 const BLUEKSY_STATUS_SUCCESS = 2;
60 const BLUEKSY_STATUS_API_FAIL = 10;
61 const BLUEKSY_STATUS_DID_FAIL = 11;
62 const BLUEKSY_STATUS_PDS_FAIL = 12;
63 const BLUEKSY_STATUS_TOKEN_FAIL = 13;
66 * (Currently) hard wired paths for Bluesky services
68 const BLUESKY_DIRECTORY = 'https://plc.directory'; // Path to the directory server service to fetch the PDS of a given DID
69 const BLUESKY_PDS = 'https://bsky.social'; // Path to the personal data server service (PDS) to fetch the DID for a given handle
70 const BLUESKY_WEB = 'https://bsky.app'; // Path to the web interface with the user profile and posts
72 function bluesky_install()
74 Hook::register('load_config', __FILE__, 'bluesky_load_config');
75 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
76 Hook::register('post_local', __FILE__, 'bluesky_post_local');
77 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
78 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
79 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
80 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
81 Hook::register('cron', __FILE__, 'bluesky_cron');
82 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
83 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
84 Hook::register('follow', __FILE__, 'bluesky_follow');
85 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
86 Hook::register('block', __FILE__, 'bluesky_block');
87 Hook::register('unblock', __FILE__, 'bluesky_unblock');
88 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
89 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
90 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
93 function bluesky_load_config(ConfigFileManager $loader)
95 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
98 function bluesky_check_item_notification(array &$notification_data)
100 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
103 $notification_data['profiles'][] = $did;
107 function bluesky_probe_detect(array &$hookData)
109 // Don't overwrite an existing result
110 if (isset($hookData['result'])) {
114 // Avoid a lookup for the wrong network
115 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
119 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
120 if (empty($pconfig['uid'])) {
124 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
125 $did = $hookData['uri'];
126 } elseif (preg_match('#^' . BLUESKY_WEB . '/profile/(.+)#', $hookData['uri'], $matches)) {
127 $did = bluesky_get_did($matches[1]);
135 $token = bluesky_get_token($pconfig['uid']);
140 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
145 $hookData['result'] = bluesky_get_contact_fields($data, 0, $pconfig['uid'], false);
147 $hookData['result']['baseurl'] = bluesky_get_pds($did);
149 // Preparing probe data. This differs slightly from the contact array
150 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
151 $hookData['result']['photo'] = $data->avatar ?? '';
152 $hookData['result']['header'] = $data->banner ?? '';
153 $hookData['result']['batch'] = '';
154 $hookData['result']['notify'] = '';
155 $hookData['result']['poll'] = '';
156 $hookData['result']['poco'] = '';
157 $hookData['result']['pubkey'] = '';
158 $hookData['result']['priority'] = 0;
159 $hookData['result']['guid'] = '';
162 function bluesky_item_by_link(array &$hookData)
164 // Don't overwrite an existing result
165 if (isset($hookData['item_id'])) {
169 $token = bluesky_get_token($hookData['uid']);
174 if (!preg_match('#^' . BLUESKY_WEB . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
178 $did = bluesky_get_did($matches[1]);
183 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
185 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
187 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], $hookData['uid'], Item::PR_FETCHED, 0, 0, 0);
188 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
190 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
191 if (!empty($item['id'])) {
192 $hookData['item_id'] = $item['id'];
197 function bluesky_support_follow(array &$data)
199 if ($data['protocol'] == Protocol::BLUESKY) {
200 $data['result'] = true;
204 function bluesky_support_probe(array &$data)
206 if ($data['protocol'] == Protocol::BLUESKY) {
207 $data['result'] = true;
211 function bluesky_follow(array &$hook_data)
213 $token = bluesky_get_token($hook_data['uid']);
218 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
219 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
220 if (empty($contact)) {
225 'subject' => $contact['url'],
226 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
227 '$type' => 'app.bsky.graph.follow'
231 'collection' => 'app.bsky.graph.follow',
232 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
236 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
237 if (!empty($activity->uri)) {
238 $hook_data['contact'] = $contact;
239 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
243 function bluesky_unfollow(array &$hook_data)
245 $token = bluesky_get_token($hook_data['uid']);
250 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
254 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
255 if (empty($data->viewer) || empty($data->viewer->following)) {
259 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
261 $hook_data['result'] = true;
264 function bluesky_block(array &$hook_data)
266 $token = bluesky_get_token($hook_data['uid']);
271 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
272 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
273 if (empty($contact)) {
278 'subject' => $contact['url'],
279 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
280 '$type' => 'app.bsky.graph.block'
284 'collection' => 'app.bsky.graph.block',
285 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
289 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
290 if (!empty($activity->uri)) {
291 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
292 if (!empty($cdata['user'])) {
293 Contact::remove($cdata['user']);
295 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
299 function bluesky_unblock(array &$hook_data)
301 $token = bluesky_get_token($hook_data['uid']);
306 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
310 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
311 if (empty($data->viewer) || empty($data->viewer->blocking)) {
315 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
317 $hook_data['result'] = true;
320 function bluesky_addon_admin(string &$o)
322 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/bluesky/');
324 $o = Renderer::replaceMacros($t, [
325 '$submit' => DI::l10n()->t('Save Settings'),
326 '$friendica_handles' => ['friendica_handles', DI::l10n()->t('Allow your users to use your hostname for their Bluesky handles'), DI::config()->get('bluesky', 'friendica_handles'), DI::l10n()->t('Before enabling this option, you have to download and configure the bluesky-handles repository on your system. See https://git.friendi.ca/heluecht/bluesky-handles')],
330 function bluesky_addon_admin_post()
332 DI::config()->set('bluesky', 'friendica_handles', (bool)$_POST['friendica_handles']);
335 function bluesky_settings(array &$data)
337 if (!DI::userSession()->getLocalUserId()) {
341 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
342 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
343 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
344 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
345 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
346 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
347 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
348 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
349 $custom_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'friendica_handle') ?? false;
351 if (DI::config()->get('bluesky', 'friendica_handles')) {
352 $self = User::getById(DI::userSession()->getLocalUserId(), ['nickname']);
353 $handle = $self['nickname'] . '.' . DI::baseUrl()->getHost();
354 $friendica_handle = ['bluesky_friendica_handle', DI::l10n()->t('Allow to use %s as your Bluesky handle.', $handle), $custom_handle, DI::l10n()->t('When enabled, you can use %s as your Bluesky handle. After you enabled this option, please go to https://bsky.app/settings and select to change your handle. Select that you have got your own domain. Then enter %s and select "No DNS Panel". Then select "Verify Text File".', $handle, $handle)];
356 $friendica_handle = [];
359 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
360 $html = Renderer::replaceMacros($t, [
361 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
362 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
363 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
364 '$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.')],
365 '$custom_handle' => $friendica_handle,
366 '$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'],
367 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
368 '$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'],
369 '$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.")],
370 '$status' => bluesky_get_status($handle, $did, $pds, $token),
374 'connector' => 'bluesky',
375 'title' => DI::l10n()->t('Bluesky Import/Export'),
376 'image' => 'images/bluesky.jpg',
377 'enabled' => $enabled,
382 function bluesky_get_status(string $handle = null, string $did = null, string $pds = null, string $token = null): string
384 if (empty($handle)) {
385 return DI::l10n()->t('You are not authenticated. Please enter your handle and the app password.');
388 $status = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'status') ?? BLUEKSY_STATUS_UNKNOWN;
390 // Fallback mechanism for connection that had been established before the introduction of the status
391 if ($status == BLUEKSY_STATUS_UNKNOWN) {
393 $status = BLUEKSY_STATUS_DID_FAIL;
394 } elseif (empty($pds)) {
395 $status = BLUEKSY_STATUS_PDS_FAIL;
396 } elseif (!empty($token)) {
397 $status = BLUEKSY_STATUS_TOKEN_OK;
399 $status = BLUEKSY_STATUS_TOKEN_FAIL;
404 case BLUEKSY_STATUS_TOKEN_OK:
405 return DI::l10n()->t("You are authenticated to Bluesky. For security reasons the password isn't stored.");
406 case BLUEKSY_STATUS_SUCCESS:
407 return DI::l10n()->t('The communication with the personal data server service (PDS) is established.');
408 case BLUEKSY_STATUS_API_FAIL;
409 return DI::l10n()->t('Communication issues with the personal data server service (PDS).');
410 case BLUEKSY_STATUS_DID_FAIL:
411 return DI::l10n()->t('The DID for the provided handle could not be detected. Please check if you entered the correct handle.');
412 case BLUEKSY_STATUS_PDS_FAIL:
413 return DI::l10n()->t('The personal data server service (PDS) could not be detected.');
414 case BLUEKSY_STATUS_TOKEN_FAIL:
415 return DI::l10n()->t('The authentication with the provided handle and password failed. Please check if you entered the correct password.');
421 function bluesky_settings_post(array &$b)
423 if (empty($_POST['bluesky-submit'])) {
427 $old_pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
428 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
429 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
431 $handle = trim($_POST['bluesky_handle'], ' @');
433 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
434 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
435 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
436 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
437 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
438 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'friendica_handle', intval($_POST['bluesky_friendica_handle']));
440 if (!empty($handle)) {
441 if (empty($old_did) || $old_handle != $handle) {
442 $did = bluesky_get_did(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle'));
444 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'status', BLUEKSY_STATUS_DID_FAIL);
446 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', $did);
448 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
450 if (!empty($did) && (empty($old_pds) || $old_handle != $handle)) {
451 $pds = bluesky_get_pds($did);
453 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'status', BLUEKSY_STATUS_PDS_FAIL);
455 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'pds', $pds);
457 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
460 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
461 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
462 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
463 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'refresh_token');
464 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'token_created');
465 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'status');
468 if (!empty($did) && !empty($pds) && !empty($_POST['bluesky_password'])) {
469 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
473 function bluesky_jot_nets(array &$jotnets_fields)
475 if (!DI::userSession()->getLocalUserId()) {
479 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
480 $jotnets_fields[] = [
481 'type' => 'checkbox',
484 DI::l10n()->t('Post to Bluesky'),
485 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
491 function bluesky_cron()
493 $last = (int)DI::keyValue()->get('bluesky_last_poll');
495 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
496 if (!$poll_interval) {
497 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
501 $next = $last + ($poll_interval * 60);
502 if ($next > time()) {
503 Logger::notice('poll interval not reached');
507 Logger::notice('cron_start');
509 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
510 if ($abandon_days < 1) {
514 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
516 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
517 foreach ($pconfigs as $pconfig) {
518 if ($abandon_days != 0) {
519 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
520 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
525 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
526 bluesky_get_token($pconfig['uid']);
528 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid'], $last);
529 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid'], $last);
531 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
532 $feeds = bluesky_get_feeds($pconfig['uid']);
533 foreach ($feeds as $feed) {
534 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed, $last);
539 $last_clean = DI::keyValue()->get('bluesky_last_clean');
540 if (empty($last_clean) || ($last_clean + 86400 < time())) {
541 Logger::notice('Start contact cleanup');
542 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
543 while ($contact = DBA::fetch($contacts)) {
544 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
546 DBA::close($contacts);
547 DI::keyValue()->set('bluesky_last_clean', time());
548 Logger::notice('Contact cleanup done');
551 Logger::notice('cron_end');
553 DI::keyValue()->set('bluesky_last_poll', time());
556 function bluesky_hook_fork(array &$b)
558 if ($b['name'] != 'notifier_normal') {
564 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
565 DI::logger()->info('Editing is not supported by the addon');
566 $b['execute'] = false;
570 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
571 // Don't post if it isn't a reply to a bluesky post
572 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
573 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
574 $b['execute'] = false;
577 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
578 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
579 $b['execute'] = false;
584 function bluesky_post_local(array &$b)
590 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
594 if ($b['private'] || $b['parent']) {
598 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
599 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
601 // if API is used, default to the chosen settings
602 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
606 if (!$bluesky_enable) {
610 if (strlen($b['postopts'])) {
611 $b['postopts'] .= ',';
614 $b['postopts'] .= 'bluesky';
617 function bluesky_send(array &$b)
619 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
623 if ($b['gravity'] != Item::GRAVITY_PARENT) {
624 Logger::debug('Got comment', ['item' => $b]);
627 $uri = bluesky_get_uri_class($b['uri']);
629 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
632 bluesky_delete_post($b['uri'], $b['uid']);
636 $root = bluesky_get_uri_class($b['parent-uri']);
637 $parent = bluesky_get_uri_class($b['thr-parent']);
639 if (empty($root) || empty($parent)) {
640 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
644 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
645 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
646 bluesky_create_post($b, $root, $parent);
648 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
649 bluesky_create_activity($b, $parent);
652 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
656 bluesky_create_post($b);
659 function bluesky_create_activity(array $item, stdClass $parent = null)
662 $token = bluesky_get_token($uid);
667 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
669 if ($item['verb'] == Activity::LIKE) {
671 'subject' => $parent,
672 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
673 '$type' => 'app.bsky.feed.like'
677 'collection' => 'app.bsky.feed.like',
681 } elseif ($item['verb'] == Activity::ANNOUNCE) {
683 'subject' => $parent,
684 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
685 '$type' => 'app.bsky.feed.repost'
689 'collection' => 'app.bsky.feed.repost',
695 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
696 if (empty($activity)) {
699 Logger::debug('Activity done', ['return' => $activity]);
700 $uri = bluesky_get_uri($activity);
701 Item::update(['extid' => $uri], ['id' => $item['id']]);
702 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
705 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
708 $token = bluesky_get_token($uid);
713 // Try to fetch the language from the post itself
714 if (!empty($item['language'])) {
715 $language = array_key_first(json_decode($item['language'], true));
720 $item['body'] = Post\Media::removeFromBody($item['body']);
722 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::ACTIVITY]) as $media) {
723 if (strpos($item['body'], $media['url']) === false) {
724 $item['body'] .= "\n[url]" . $media['url'] . "[/url]\n";
728 if (!empty($item['quote-uri-id'])) {
729 $quote = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $item['quote-uri-id']]);
730 if (!empty($quote)) {
731 if ((strpos($item['body'], $quote['plink'] ?: $quote['uri']) === false) && (strpos($item['body'], $quote['uri']) === false)) {
732 $item['body'] .= "\n[url]" . ($quote['plink'] ?: $quote['uri']) . "[/url]\n";
737 $urls = bluesky_get_urls($item['body']);
738 $item['body'] = $urls['body'];
740 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
741 foreach ($msg['parts'] as $key => $part) {
743 $facets = bluesky_get_facets($part, $urls['urls']);
746 'text' => $facets['body'],
747 '$type' => 'app.bsky.feed.post',
748 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
751 if (!empty($language)) {
752 $record['langs'] = [$language];
755 if (!empty($facets['facets'])) {
756 $record['facets'] = $facets['facets'];
760 $record['reply'] = ['root' => $root, 'parent' => $parent];
763 if ($key == count($msg['parts']) - 1) {
764 $record = bluesky_add_embed($uid, $msg, $record);
765 if (empty($record)) {
766 if (Worker::getRetrial() < 3) {
774 'collection' => 'app.bsky.feed.post',
775 'repo' => DI::pConfig()->get($uid, 'bluesky', 'did'),
779 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
780 if (empty($parent)) {
786 Logger::debug('Posting done', ['return' => $parent]);
790 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
791 $uri = bluesky_get_uri($parent);
792 Item::update(['extid' => $uri], ['id' => $item['id']]);
793 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
798 function bluesky_get_urls(string $body): array
800 // Remove all hashtag and mention links
801 $body = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
803 $body = BBCode::expandVideoLinks($body);
806 // Search for hash tags
807 if (preg_match_all("/#\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
808 foreach ($matches as $match) {
809 $text = '#' . $match[2];
810 $urls[strpos($body, $match[0])] = ['tag' => $match[2], 'text' => $text, 'hash' => $text];
811 $body = str_replace($match[0], $text, $body);
815 // Search for pure links
816 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
817 foreach ($matches as $match) {
818 $text = Strings::getStyledURL($match[1]);
819 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
820 $urls[strpos($body, $match[0])] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
821 $body = str_replace($match[0], $hash, $body);
825 // Search for links with descriptions
826 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
827 foreach ($matches as $match) {
828 if ($match[1] == $match[2]) {
829 $text = Strings::getStyledURL($match[1]);
833 if (mb_strlen($text) < 100) {
834 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
835 $urls[strpos($body, $match[0])] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
836 $body = str_replace($match[0], $hash, $body);
838 $text = Strings::getStyledURL($match[1]);
839 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
840 $urls[strpos($body, $match[0])] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
841 $body = str_replace($match[0], $text . ' ' . $hash, $body);
848 return ['body' => $body, 'urls' => $urls];
851 function bluesky_get_hash_for_url(string $text, int $linklength): string
853 if ($linklength <= 10) {
854 return '|' . hash('crc32', $text) . '|';
856 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
859 function bluesky_get_facets(string $body, array $urls): array
863 foreach ($urls as $url) {
864 $pos = strpos($body, $url['hash']);
865 if ($pos === false) {
869 $prefix = substr($body, 0, $pos);
874 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
876 $facet = new stdClass;
877 $facet->index = new stdClass;
878 $facet->index->byteEnd = $pos + strlen($url['text']);
879 $facet->index->byteStart = $pos;
881 $feature = new stdClass;
884 if (!empty($url['tag'])) {
885 $feature->tag = $url['tag'];
886 $feature->$type = 'app.bsky.richtext.facet#tag';
887 } elseif (!empty($url['url'])) {
888 $feature->uri = $url['url'];
889 $feature->$type = 'app.bsky.richtext.facet#link';
894 $facet->features = [$feature];
898 return ['facets' => $facets, 'body' => $body];
901 function bluesky_add_embed(int $uid, array $msg, array $record): array
903 if (($msg['type'] != 'link') && !empty($msg['images'])) {
905 foreach ($msg['images'] as $image) {
906 if (count($images) == 4) {
909 $photo = Photo::selectFirst([], ['id' => $image['id']]);
910 $blob = bluesky_upload_blob($uid, $photo);
914 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
916 if (!empty($images)) {
917 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
919 } elseif ($msg['type'] == 'link') {
921 '$type' => 'app.bsky.embed.external',
923 'uri' => $msg['url'],
924 'title' => $msg['title'] ?? '',
925 'description' => $msg['description'] ?? '',
928 if (!empty($msg['image'])) {
929 $photo = Photo::createPhotoForExternalResource($msg['image']);
930 $blob = bluesky_upload_blob($uid, $photo);
932 $record['embed']['external']['thumb'] = $blob;
939 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
941 $retrial = Worker::getRetrial();
942 $content = Photo::getImageForPhoto($photo);
944 $picture = new Image($content, $photo['type'], $photo['filename']);
945 $height = $picture->getHeight();
946 $width = $picture->getWidth();
947 $size = strlen($content);
949 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
950 $new_height = $picture->getHeight();
951 $new_width = $picture->getWidth();
952 $content = $picture->asString();
953 $new_size = strlen($content);
955 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]);
957 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
959 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]);
963 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]);
967 function bluesky_delete_post(string $uri, int $uid)
969 $parts = bluesky_get_uri_parts($uri);
971 Logger::debug('No uri delected', ['uri' => $uri]);
974 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
975 Logger::debug('Deleted', ['parts' => $parts]);
978 function bluesky_fetch_timeline(int $uid, int $last_poll)
980 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
985 if (empty($data->feed)) {
989 foreach (array_reverse($data->feed) as $entry) {
990 bluesky_process_post($entry->post, $uid, $uid, Item::PR_NONE, 0, 0, $last_poll);
991 if (!empty($entry->reason)) {
992 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
996 // @todo Support paging
997 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
1000 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
1003 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
1007 $contact = bluesky_get_contact($reason->by, $uid, $uid);
1010 'network' => Protocol::BLUESKY,
1013 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
1014 'private' => Item::UNLISTED,
1015 'verb' => Activity::POST,
1016 'contact-id' => $contact['id'],
1017 'author-name' => $contact['name'],
1018 'author-link' => $contact['url'],
1019 'author-avatar' => $contact['avatar'],
1020 'verb' => Activity::ANNOUNCE,
1021 'body' => Activity::ANNOUNCE,
1022 'gravity' => Item::GRAVITY_ACTIVITY,
1023 'object-type' => Activity\ObjectType::NOTE,
1024 'thr-parent' => $uri,
1027 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
1031 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
1032 $item['owner-name'] = $item['author-name'];
1033 $item['owner-link'] = $item['author-link'];
1034 $item['owner-avatar'] = $item['author-avatar'];
1035 if (Item::insert($item)) {
1036 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
1037 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
1041 function bluesky_fetch_notifications(int $uid, int $last_poll)
1043 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
1044 if (empty($data->notifications)) {
1047 foreach ($data->notifications as $notification) {
1048 $uri = bluesky_get_uri($notification);
1049 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
1050 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
1053 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
1054 switch ($notification->reason) {
1056 $item = bluesky_get_header($notification, $uri, $uid, $uid);
1057 $item['gravity'] = Item::GRAVITY_ACTIVITY;
1058 $item['body'] = $item['verb'] = Activity::LIKE;
1059 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
1060 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, Item::PR_FETCHED, $item['contact-id'], 0, $last_poll);
1061 if (!empty($item['thr-parent'])) {
1062 $data = Item::insert($item);
1063 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1065 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
1070 $item = bluesky_get_header($notification, $uri, $uid, $uid);
1071 $item['gravity'] = Item::GRAVITY_ACTIVITY;
1072 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
1073 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
1074 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, Item::PR_FETCHED, $item['contact-id'], 0, $last_poll);
1075 if (!empty($item['thr-parent'])) {
1076 $data = Item::insert($item);
1077 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
1079 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
1084 $contact = bluesky_get_contact($notification->author, $uid, $uid);
1085 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
1089 $contact = bluesky_get_contact($notification->author, 0, $uid);
1090 $result = bluesky_fetch_missing_post($uri, $uid, $uid, Item::PR_TO, $contact['id'], 0, $last_poll);
1091 Logger::debug('Got mention', ['uid' => $uid, 'nick' => $contact['nick'], 'result' => $result, 'uri' => $uri]);
1095 $contact = bluesky_get_contact($notification->author, 0, $uid);
1096 $result = bluesky_fetch_missing_post($uri, $uid, $uid, Item::PR_COMMENT, $contact['id'], 0, $last_poll);
1097 Logger::debug('Got reply', ['uid' => $uid, 'nick' => $contact['nick'], 'result' => $result, 'uri' => $uri]);
1101 $contact = bluesky_get_contact($notification->author, 0, $uid);
1102 $result = bluesky_fetch_missing_post($uri, $uid, $uid, Item::PR_PUSHED, $contact['id'], 0, $last_poll);
1103 Logger::debug('Got quote', ['uid' => $uid, 'nick' => $contact['nick'], 'result' => $result, 'uri' => $uri]);
1107 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
1113 function bluesky_fetch_feed(int $uid, string $feed, int $last_poll)
1115 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
1120 if (empty($data->feed)) {
1124 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
1125 if (!empty($feeddata)) {
1126 $feedurl = $feeddata->view->uri;
1127 $feedname = $feeddata->view->displayName;
1133 foreach (array_reverse($data->feed) as $entry) {
1134 $contact = bluesky_get_contact($entry->post->author, 0, $uid);
1135 $languages = $entry->post->record->langs ?? [];
1137 if (!Relay::isWantedLanguage($entry->post->record->text, 0, $contact['id'] ?? 0, $languages)) {
1138 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
1141 $uri_id = bluesky_process_post($entry->post, $uid, $uid, Item::PR_TAG, 0, 0, $last_poll);
1142 if (!empty($uri_id)) {
1143 $stored = Post\Category::storeFileByURIId($uri_id, $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
1144 Logger::debug('Stored tag subscription for user', ['uri-id' => $uri_id, 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
1146 Logger::notice('Post not found', ['entry' => $entry]);
1148 if (!empty($entry->reason)) {
1149 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1154 function bluesky_process_post(stdClass $post, int $uid, int $fetch_uid, int $post_reason, int $causer, int $level, int $last_poll): int
1156 $uri = bluesky_get_uri($post);
1158 if ($uri_id = bluesky_fetch_uri_id($uri, $uid)) {
1162 if (empty($post->record)) {
1163 Logger::debug('Invalid post', ['uri' => $uri]);
1167 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1169 $item = bluesky_get_header($post, $uri, $uid, $fetch_uid);
1170 $item = bluesky_get_content($item, $post->record, $uri, $uid, $fetch_uid, $level, $last_poll);
1175 if (!empty($post->embed)) {
1176 $item = bluesky_add_media($post->embed, $item, $uid, $level, $last_poll);
1179 if (empty($item['post-reason'])) {
1180 $item['post-reason'] = $post_reason;
1184 $item['causer-id'] = $causer;
1187 Item::insert($item);
1188 return bluesky_fetch_uri_id($uri, $uid);
1191 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1193 $parts = bluesky_get_uri_parts($uri);
1194 if (empty($post->author) || empty($post->cid) || empty($parts->rkey)) {
1197 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1199 'network' => Protocol::BLUESKY,
1203 'guid' => $post->cid,
1204 'private' => Item::UNLISTED,
1205 'verb' => Activity::POST,
1206 'contact-id' => $contact['id'],
1207 'author-name' => $contact['name'],
1208 'author-link' => $contact['url'],
1209 'author-avatar' => $contact['avatar'],
1210 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1211 'source' => json_encode($post),
1214 $item['uri-id'] = ItemURI::getIdByURI($uri);
1215 $item['owner-name'] = $item['author-name'];
1216 $item['owner-link'] = $item['author-link'];
1217 $item['owner-avatar'] = $item['author-avatar'];
1219 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1220 $item['post-reason'] = Item::PR_FOLLOWER;
1226 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $fetch_uid, int $level, int $last_poll): array
1232 if (!empty($record->reply)) {
1233 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1234 if ($item['parent-uri'] != $uri) {
1235 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $fetch_uid, Item::PR_FETCHED, $item['contact-id'], $level, $last_poll);
1236 if (empty($item['parent-uri'])) {
1241 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1242 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1243 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $fetch_uid, Item::PR_FETCHED, $item['contact-id'], $level, $last_poll, $item['parent-uri']);
1244 if (empty($item['thr-parent'])) {
1250 $item['body'] = bluesky_get_text($record, $item['uri-id']);
1251 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1252 $item['transmitted-languages'] = $record->langs ?? [];
1254 if (($last_poll != 0) && strtotime($item['created']) > $last_poll) {
1255 $item['received'] = $item['created'];
1261 function bluesky_get_text(stdClass $record, int $uri_id): string
1263 $text = $record->text ?? '';
1265 if (empty($record->facets)) {
1270 foreach ($record->facets as $facet) {
1271 $facets[$facet->index->byteStart] = $facet;
1275 foreach ($facets as $facet) {
1276 $prefix = substr($text, 0, $facet->index->byteStart);
1277 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1278 $suffix = substr($text, $facet->index->byteEnd);
1282 foreach ($facet->features as $feature) {
1284 switch ($feature->$type) {
1285 case 'app.bsky.richtext.facet#link':
1286 $url = $feature->uri;
1289 case 'app.bsky.richtext.facet#mention':
1290 $contact = Contact::getByURL($feature->did, null, ['id']);
1291 if (!empty($contact['id'])) {
1292 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1293 if (substr($linktext, 0, 1) == '@') {
1295 $linktext = substr($linktext, 1);
1300 case 'app.bsky.richtext.facet#tag';
1301 Tag::store($uri_id, Tag::HASHTAG, $feature->tag);
1302 $url = DI::baseUrl() . '/search?tag=' . urlencode($feature->tag);
1303 $linktext = '#' . $feature->tag;
1307 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'feature' => $feature, 'record' => $record]);
1312 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1318 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level, int $last_poll): array
1321 switch ($embed->$type) {
1322 case 'app.bsky.embed.images#view':
1323 foreach ($embed->images as $image) {
1325 'uri-id' => $item['uri-id'],
1326 'type' => Post\Media::IMAGE,
1327 'url' => $image->fullsize,
1328 'preview' => $image->thumb,
1329 'description' => $image->alt,
1331 Post\Media::insert($media);
1335 case 'app.bsky.embed.external#view':
1337 'uri-id' => $item['uri-id'],
1338 'type' => Post\Media::HTML,
1339 'url' => $embed->external->uri,
1340 'name' => $embed->external->title,
1341 'description' => $embed->external->description,
1343 Post\Media::insert($media);
1346 case 'app.bsky.embed.record#view':
1347 $original_uri = $uri = bluesky_get_uri($embed->record);
1348 $uri = bluesky_fetch_missing_post($uri, $item['uid'], $fetch_uid, Item::PR_FETCHED, $item['contact-id'], $level, $last_poll);
1350 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => [$item['uid'], 0]]);
1351 $uri_id = $shared['uri-id'] ?? 0;
1353 if (!empty($uri_id)) {
1354 $item['quote-uri-id'] = $uri_id;
1356 Logger::debug('Quoted post could not be fetched', ['original-uri' => $original_uri, 'uri' => $uri]);
1360 case 'app.bsky.embed.recordWithMedia#view':
1361 bluesky_add_media($embed->media, $item, $fetch_uid, $level, $last_poll);
1362 $original_uri = $uri = bluesky_get_uri($embed->record->record);
1363 $uri = bluesky_fetch_missing_post($uri, $item['uid'], $fetch_uid, Item::PR_FETCHED, $item['contact-id'], $level, $last_poll);
1365 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => [$item['uid'], 0]]);
1366 $uri_id = $shared['uri-id'] ?? 0;
1368 if (!empty($uri_id)) {
1369 $item['quote-uri-id'] = $uri_id;
1371 Logger::debug('Quoted post could not be fetched', ['original-uri' => $original_uri, 'uri' => $uri]);
1376 Logger::notice('Unhandled embed type', ['uri-id' => $item['uri-id'], 'type' => $embed->$type, 'embed' => $embed]);
1382 function bluesky_get_uri(stdClass $post): string
1384 if (empty($post->cid)) {
1385 Logger::info('Invalid URI', ['post' => $post]);
1388 return $post->uri . ':' . $post->cid;
1391 function bluesky_get_uri_class(string $uri): ?stdClass
1397 $elements = explode(':', $uri);
1398 if (empty($elements) || ($elements[0] != 'at')) {
1399 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1400 return bluesky_get_uri_class($post['extid'] ?? '');
1403 $class = new stdClass;
1405 $class->cid = array_pop($elements);
1406 $class->uri = implode(':', $elements);
1408 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1409 $class->uri .= ':' . $class->cid;
1416 function bluesky_get_uri_parts(string $uri): ?stdClass
1418 $class = bluesky_get_uri_class($uri);
1419 if (empty($class)) {
1423 $parts = explode('/', substr($class->uri, 5));
1425 $class = new stdClass;
1427 $class->repo = $parts[0];
1428 $class->collection = $parts[1];
1429 $class->rkey = $parts[2];
1434 function bluesky_fetch_missing_post(string $uri, int $uid, int $fetch_uid, int $post_reason, int $causer, int $level, int $last_poll, string $fallback = ''): string
1436 $fetched_uri = bluesky_fetch_post($uri, $uid);
1437 if (!empty($fetched_uri)) {
1438 return $fetched_uri;
1441 if (++$level > 100) {
1442 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1443 // When the level is too deep we will fallback to the parent uri.
1444 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1448 $class = bluesky_get_uri_class($uri);
1449 $fetch_uri = $class->uri;
1451 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1452 $data = bluesky_xrpc_get($fetch_uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1454 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1458 Logger::debug('Reply count', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1461 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1462 $causer = $cdata['public'] ?? 0;
1465 return bluesky_process_thread($data->thread, $uid, $fetch_uid, $post_reason, $causer, $level, $last_poll);
1468 function bluesky_fetch_post(string $uri, int $uid): string
1470 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1471 Logger::debug('Post exists', ['uri' => $uri]);
1475 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1476 if (!empty($reply['uri'])) {
1477 Logger::debug('Post with extid exists', ['uri' => $uri]);
1478 return $reply['uri'];
1483 function bluesky_fetch_uri_id(string $uri, int $uid): string
1485 $reply = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => [$uid, 0]]);
1486 if (!empty($reply['uri-id'])) {
1487 Logger::debug('Post with extid exists', ['uri' => $uri]);
1488 return $reply['uri-id'];
1490 $reply = Post::selectFirst(['uri-id'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1491 if (!empty($reply['uri-id'])) {
1492 Logger::debug('Post with extid exists', ['uri' => $uri]);
1493 return $reply['uri-id'];
1498 function bluesky_process_thread(stdClass $thread, int $uid, int $fetch_uid, int $post_reason, int $causer, int $level, int $last_poll): string
1500 if (empty($thread->post)) {
1501 Logger::info('Invalid post', ['post' => $thread]);
1504 $uri = bluesky_get_uri($thread->post);
1506 $fetched_uri = bluesky_fetch_post($uri, $uid);
1507 if (empty($fetched_uri)) {
1508 $uri_id = bluesky_process_post($thread->post, $uid, $fetch_uid, $post_reason, $causer, $level, $last_poll);
1510 Logger::debug('Post has been processed and stored', ['uri-id' => $uri_id, 'uri' => $uri]);
1513 Logger::info('Post has not not been stored', ['uri' => $uri]);
1517 Logger::debug('Post exists', ['uri' => $uri]);
1518 $uri = $fetched_uri;
1521 foreach ($thread->replies ?? [] as $reply) {
1522 $reply_uri = bluesky_process_thread($reply, $uid, $fetch_uid, Item::PR_FETCHED, $causer, $level, $last_poll);
1523 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1529 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1531 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1532 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1534 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1536 $public_fields = $fields = bluesky_get_contact_fields($author, $uid, $fetch_uid, $update);
1538 $public_fields['uid'] = 0;
1539 $public_fields['rel'] = Contact::NOTHING;
1541 if (empty($contact)) {
1542 $cid = Contact::insert($public_fields);
1544 $cid = $contact['id'];
1545 Contact::update($public_fields, ['id' => $cid], true);
1549 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1551 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1552 if (!isset($fields['rel']) && isset($contact['rel'])) {
1553 $fields['rel'] = $contact['rel'];
1554 } elseif (!isset($fields['rel'])) {
1555 $fields['rel'] = Contact::NOTHING;
1559 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1560 if (empty($contact)) {
1561 $cid = Contact::insert($fields);
1563 $cid = $contact['id'];
1564 Contact::update($fields, ['id' => $cid], true);
1566 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1568 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1570 if (!empty($author->avatar)) {
1571 Contact::updateAvatar($cid, $author->avatar);
1574 return Contact::getById($cid);
1577 function bluesky_get_contact_fields(stdClass $author, int $uid, int $fetch_uid, bool $update): array
1579 $nick = $author->handle ?? $author->did;
1580 $name = $author->displayName ?? $nick;
1583 'network' => Protocol::BLUESKY,
1587 'readonly' => false,
1589 'url' => $author->did,
1590 'nurl' => $author->did,
1591 'alias' => BLUESKY_WEB . '/profile/' . $nick,
1592 'name' => $name ?: $nick,
1598 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1602 $fields['baseurl'] = bluesky_get_pds($author->did);
1603 if (!empty($fields['baseurl'])) {
1604 GServer::check($fields['baseurl'], Protocol::BLUESKY);
1605 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
1608 $data = bluesky_xrpc_get($fetch_uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1610 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1614 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1616 if (!empty($data->description)) {
1617 $fields['about'] = HTML::toBBCode($data->description);
1620 if (!empty($data->banner)) {
1621 $fields['header'] = $data->banner;
1624 if (!empty($data->viewer)) {
1625 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1626 $fields['rel'] = Contact::FRIEND;
1627 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1628 $fields['rel'] = Contact::SHARING;
1629 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1630 $fields['rel'] = Contact::FOLLOWER;
1632 $fields['rel'] = Contact::NOTHING;
1636 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1640 function bluesky_get_feeds(int $uid): array
1643 $preferences = bluesky_get_preferences($uid);
1644 foreach ($preferences->preferences as $preference) {
1645 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1646 return $preference->pinned ?? [];
1652 function bluesky_get_preferences(int $uid): stdClass
1654 $cachekey = 'bluesky:preferences:' . $uid;
1655 $data = DI::cache()->get($cachekey);
1656 if (!is_null($data)) {
1660 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1662 DI::cache()->set($cachekey, $data, Duration::HOUR);
1666 function bluesky_get_did_by_wellknown(string $handle): string
1668 $curlResult = DI::httpClient()->get('http://' . $handle . '/.well-known/atproto-did');
1669 if ($curlResult->isSuccess() && substr($curlResult->getBodyString(), 0, 4) == 'did:') {
1670 $did = $curlResult->getBodyString();
1671 if (!bluesky_valid_did($did, $handle)) {
1672 Logger::notice('Invalid DID', ['handle' => $handle, 'did' => $did]);
1675 Logger::debug('Got DID by wellknown', ['handle' => $handle, 'did' => $did]);
1681 function bluesky_get_did_by_dns(string $handle): string
1683 $records = @dns_get_record('_atproto.' . $handle . '.', DNS_TXT);
1684 if (empty($records)) {
1687 foreach ($records as $record) {
1688 if (!empty($record['txt']) && substr($record['txt'], 0, 4) == 'did=') {
1689 $did = substr($record['txt'], 4);
1690 if (!bluesky_valid_did($did, $handle)) {
1691 Logger::notice('Invalid DID', ['handle' => $handle, 'did' => $did]);
1694 Logger::debug('Got DID by DNS', ['handle' => $handle, 'did' => $did]);
1701 function bluesky_get_did(string $handle): string
1703 // Deactivated at the moment, since it isn't reliable by now
1704 //$did = bluesky_get_did_by_dns($handle);
1709 //$did = bluesky_get_did_by_wellknown($handle);
1714 $data = bluesky_get(BLUESKY_PDS . '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1715 if (empty($data) || empty($data->did)) {
1718 Logger::debug('Got DID by PDS call', ['handle' => $handle, 'did' => $data->did]);
1722 function bluesky_get_user_pds(int $uid): string
1724 $pds = DI::pConfig()->get($uid, 'bluesky', 'pds');
1728 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1730 Logger::notice('Empty did for user', ['uid' => $uid]);
1733 $pds = bluesky_get_pds($did);
1734 DI::pConfig()->set($uid, 'bluesky', 'pds', $pds);
1738 function bluesky_get_pds(string $did): ?string
1740 $data = bluesky_get(BLUESKY_DIRECTORY . '/' . $did);
1741 if (empty($data) || empty($data->service)) {
1745 foreach ($data->service as $service) {
1746 if (($service->id == '#atproto_pds') && ($service->type == 'AtprotoPersonalDataServer') && !empty($service->serviceEndpoint)) {
1747 return $service->serviceEndpoint;
1754 function bluesky_valid_did(string $did, string $handle): bool
1756 $data = bluesky_get(BLUESKY_DIRECTORY . '/' . $did);
1757 if (empty($data) || empty($data->alsoKnownAs)) {
1761 return in_array('at://' . $handle, $data->alsoKnownAs);
1764 function bluesky_get_token(int $uid): string
1766 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1767 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1768 if (empty($token)) {
1772 if ($created + 300 < time()) {
1773 return bluesky_refresh_token($uid);
1778 function bluesky_refresh_token(int $uid): string
1780 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1782 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1787 Logger::debug('Refreshed token', ['return' => $data]);
1788 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1789 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1790 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1791 return $data->accessJwt;
1794 function bluesky_create_token(int $uid, string $password): string
1796 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1798 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1800 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_TOKEN_FAIL);
1804 Logger::debug('Created token', ['return' => $data]);
1805 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1806 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1807 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1808 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_TOKEN_OK);
1809 return $data->accessJwt;
1812 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1814 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1817 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1820 $curlResult = DI::httpClient()->post(bluesky_get_user_pds($uid) . $url, $params, $headers);
1821 } catch (\Exception $e) {
1822 Logger::notice('Exception on post', ['exception' => $e]);
1823 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_API_FAIL);
1827 if (!$curlResult->isSuccess()) {
1828 Logger::notice('API Error', ['error' => json_decode($curlResult->getBodyString()) ?: $curlResult->getBodyString()]);
1829 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_API_FAIL);
1833 DI::pConfig()->set($uid, 'bluesky', 'status', BLUEKSY_STATUS_SUCCESS);
1834 return json_decode($curlResult->getBodyString());
1837 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1839 if (!empty($parameters)) {
1840 $url .= '?' . http_build_query($parameters);
1843 $data = bluesky_get(bluesky_get_user_pds($uid) . '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1844 DI::pConfig()->set($uid, 'bluesky', 'status', is_null($data) ? BLUEKSY_STATUS_API_FAIL : BLUEKSY_STATUS_SUCCESS);
1848 function bluesky_get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1851 $curlResult = DI::httpClient()->get($url, $accept_content, $opts);
1852 } catch (\Exception $e) {
1853 Logger::notice('Exception on get', ['exception' => $e]);
1857 if (!$curlResult->isSuccess()) {
1858 Logger::notice('API Error', ['error' => json_decode($curlResult->getBodyString()) ?: $curlResult->getBodyString()]);
1862 return json_decode($curlResult->getBodyString());