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];
57 * (Currently) hard wired paths for Bluesky services
59 const BLUESKY_DIRECTORY = 'https://plc.directory'; // Path to the directory server service to fetch the PDS of a given DID
60 const BLUESKY_PDS = 'https://bsky.social'; // Path to the personal data server service (PDS) to fetch the DID for a given handle
61 const BLUESKY_WEB = 'https://bsky.app'; // Path to the web interface with the user profile and posts
63 function bluesky_install()
65 Hook::register('load_config', __FILE__, 'bluesky_load_config');
66 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
67 Hook::register('post_local', __FILE__, 'bluesky_post_local');
68 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
69 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
70 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
71 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
72 Hook::register('cron', __FILE__, 'bluesky_cron');
73 Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
74 Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
75 Hook::register('follow', __FILE__, 'bluesky_follow');
76 Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
77 Hook::register('block', __FILE__, 'bluesky_block');
78 Hook::register('unblock', __FILE__, 'bluesky_unblock');
79 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
80 Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
81 Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
84 function bluesky_load_config(ConfigFileManager $loader)
86 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
89 function bluesky_check_item_notification(array &$notification_data)
91 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
94 $notification_data['profiles'][] = $did;
98 function bluesky_probe_detect(array &$hookData)
100 // Don't overwrite an existing result
101 if (isset($hookData['result'])) {
105 // Avoid a lookup for the wrong network
106 if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
110 $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
111 if (empty($pconfig['uid'])) {
115 if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
116 $did = $hookData['uri'];
117 } elseif (preg_match('#^' . BLUESKY_WEB . '/profile/(.+)#', $hookData['uri'], $matches)) {
118 $did = bluesky_get_did($matches[1]);
126 $token = bluesky_get_token($pconfig['uid']);
131 $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
136 $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
138 $hookData['result']['baseurl'] = bluesky_get_pds($did);
140 // Preparing probe data. This differs slightly from the contact array
141 $hookData['result']['about'] = HTML::toBBCode($data->description ?? '');
142 $hookData['result']['photo'] = $data->avatar ?? '';
143 $hookData['result']['header'] = $data->banner ?? '';
144 $hookData['result']['batch'] = '';
145 $hookData['result']['notify'] = '';
146 $hookData['result']['poll'] = '';
147 $hookData['result']['poco'] = '';
148 $hookData['result']['pubkey'] = '';
149 $hookData['result']['priority'] = 0;
150 $hookData['result']['guid'] = '';
153 function bluesky_item_by_link(array &$hookData)
155 // Don't overwrite an existing result
156 if (isset($hookData['item_id'])) {
160 $token = bluesky_get_token($hookData['uid']);
165 if (!preg_match('#^' . BLUESKY_WEB . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
169 $did = bluesky_get_did($matches[1]);
174 Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
176 $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
178 $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], $hookData['uid'], 0, 0);
179 Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
181 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
182 if (!empty($item['id'])) {
183 $hookData['item_id'] = $item['id'];
188 function bluesky_support_follow(array &$data)
190 if ($data['protocol'] == Protocol::BLUESKY) {
191 $data['result'] = true;
195 function bluesky_support_probe(array &$data)
197 if ($data['protocol'] == Protocol::BLUESKY) {
198 $data['result'] = true;
202 function bluesky_follow(array &$hook_data)
204 $token = bluesky_get_token($hook_data['uid']);
209 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
210 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
211 if (empty($contact)) {
216 'subject' => $contact['url'],
217 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
218 '$type' => 'app.bsky.graph.follow'
222 'collection' => 'app.bsky.graph.follow',
223 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
227 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
228 if (!empty($activity->uri)) {
229 $hook_data['contact'] = $contact;
230 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
234 function bluesky_unfollow(array &$hook_data)
236 $token = bluesky_get_token($hook_data['uid']);
241 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
245 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
246 if (empty($data->viewer) || empty($data->viewer->following)) {
250 bluesky_delete_post($data->viewer->following, $hook_data['uid']);
252 $hook_data['result'] = true;
255 function bluesky_block(array &$hook_data)
257 $token = bluesky_get_token($hook_data['uid']);
262 Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
263 $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
264 if (empty($contact)) {
269 'subject' => $contact['url'],
270 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
271 '$type' => 'app.bsky.graph.block'
275 'collection' => 'app.bsky.graph.block',
276 'repo' => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
280 $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
281 if (!empty($activity->uri)) {
282 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
283 if (!empty($cdata['user'])) {
284 Contact::remove($cdata['user']);
286 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
290 function bluesky_unblock(array &$hook_data)
292 $token = bluesky_get_token($hook_data['uid']);
297 if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
301 $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
302 if (empty($data->viewer) || empty($data->viewer->blocking)) {
306 bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
308 $hook_data['result'] = true;
311 function bluesky_settings(array &$data)
313 if (!DI::userSession()->getLocalUserId()) {
317 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
318 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
319 $pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
320 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
321 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
322 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
323 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
324 $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
326 $status = $token ? DI::l10n()->t("You are authenticated to Bluesky. For security reasons the password isn't stored.") : DI::l10n()->t('You are not authenticated. Please enter the app password.');
328 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
329 $html = Renderer::replaceMacros($t, [
330 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
331 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
332 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
333 '$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.')],
334 '$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'],
335 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
336 '$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'],
337 '$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.")],
342 'connector' => 'bluesky',
343 'title' => DI::l10n()->t('Bluesky Import/Export'),
344 'image' => 'images/bluesky.jpg',
345 'enabled' => $enabled,
350 function bluesky_settings_post(array &$b)
352 if (empty($_POST['bluesky-submit'])) {
356 $old_pds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
357 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
358 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
360 $handle = $_POST['bluesky_handle'];
362 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
363 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
364 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
365 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
366 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds', intval($_POST['bluesky_import_feeds']));
368 if (!empty($host) && !empty($handle)) {
369 if (empty($old_did) || $old_handle != $handle) {
370 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
372 if (empty($old_pds) || $old_handle != $handle) {
373 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'pds', bluesky_get_pds(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did')));
376 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
377 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'pds');
380 if (!empty($_POST['bluesky_password'])) {
381 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
385 function bluesky_jot_nets(array &$jotnets_fields)
387 if (!DI::userSession()->getLocalUserId()) {
391 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
392 $jotnets_fields[] = [
393 'type' => 'checkbox',
396 DI::l10n()->t('Post to Bluesky'),
397 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
403 function bluesky_cron()
405 $last = DI::keyValue()->get('bluesky_last_poll');
407 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
408 if (!$poll_interval) {
409 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
413 $next = $last + ($poll_interval * 60);
414 if ($next > time()) {
415 Logger::notice('poll interval not reached');
419 Logger::notice('cron_start');
421 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
422 if ($abandon_days < 1) {
426 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
428 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
429 foreach ($pconfigs as $pconfig) {
430 if ($abandon_days != 0) {
431 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
432 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
437 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
438 bluesky_get_token($pconfig['uid']);
440 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
441 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
443 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
444 $feeds = bluesky_get_feeds($pconfig['uid']);
445 foreach ($feeds as $feed) {
446 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
451 $last_clean = DI::keyValue()->get('bluesky_last_clean');
452 if (empty($last_clean) || ($last_clean + 86400 < time())) {
453 Logger::notice('Start contact cleanup');
454 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
455 while ($contact = DBA::fetch($contacts)) {
456 Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
458 DBA::close($contacts);
459 DI::keyValue()->set('bluesky_last_clean', time());
460 Logger::notice('Contact cleanup done');
463 Logger::notice('cron_end');
465 DI::keyValue()->set('bluesky_last_poll', time());
468 function bluesky_hook_fork(array &$b)
470 if ($b['name'] != 'notifier_normal') {
476 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
477 DI::logger()->info('Editing is not supported by the addon');
478 $b['execute'] = false;
482 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
483 // Don't post if it isn't a reply to a bluesky post
484 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
485 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
486 $b['execute'] = false;
489 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
490 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
491 $b['execute'] = false;
496 function bluesky_post_local(array &$b)
502 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
506 if ($b['private'] || $b['parent']) {
510 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
511 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
513 // if API is used, default to the chosen settings
514 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
518 if (!$bluesky_enable) {
522 if (strlen($b['postopts'])) {
523 $b['postopts'] .= ',';
526 $b['postopts'] .= 'bluesky';
529 function bluesky_send(array &$b)
531 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
535 if ($b['gravity'] != Item::GRAVITY_PARENT) {
536 Logger::debug('Got comment', ['item' => $b]);
539 $uri = bluesky_get_uri_class($b['uri']);
541 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
544 bluesky_delete_post($b['uri'], $b['uid']);
548 $root = bluesky_get_uri_class($b['parent-uri']);
549 $parent = bluesky_get_uri_class($b['thr-parent']);
551 if (empty($root) || empty($parent)) {
552 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
556 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
557 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
558 bluesky_create_post($b, $root, $parent);
560 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
561 bluesky_create_activity($b, $parent);
564 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
568 bluesky_create_post($b);
571 function bluesky_create_activity(array $item, stdClass $parent = null)
574 $token = bluesky_get_token($uid);
579 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
581 if ($item['verb'] == Activity::LIKE) {
583 'subject' => $parent,
584 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
585 '$type' => 'app.bsky.feed.like'
589 'collection' => 'app.bsky.feed.like',
593 } elseif ($item['verb'] == Activity::ANNOUNCE) {
595 'subject' => $parent,
596 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
597 '$type' => 'app.bsky.feed.repost'
601 'collection' => 'app.bsky.feed.repost',
607 $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
608 if (empty($activity)) {
611 Logger::debug('Activity done', ['return' => $activity]);
612 $uri = bluesky_get_uri($activity);
613 Item::update(['extid' => $uri], ['id' => $item['id']]);
614 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
617 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
620 $token = bluesky_get_token($uid);
625 // Try to fetch the language from the post itself
626 if (!empty($item['language'])) {
627 $language = array_key_first(json_decode($item['language'], true));
632 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
633 $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
634 $item['body'] = $urls['body'];
636 $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
637 foreach ($msg['parts'] as $key => $part) {
639 $facets = bluesky_get_facets($part, $urls['urls']);
642 'text' => $facets['body'],
643 '$type' => 'app.bsky.feed.post',
644 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
647 if (!empty($language)) {
648 $record['langs'] = [$language];
651 if (!empty($facets['facets'])) {
652 $record['facets'] = $facets['facets'];
656 $record['reply'] = ['root' => $root, 'parent' => $parent];
659 if ($key == count($msg['parts']) - 1) {
660 $record = bluesky_add_embed($uid, $msg, $record);
661 if (empty($record)) {
662 if (Worker::getRetrial() < 3) {
670 'collection' => 'app.bsky.feed.post',
675 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
676 if (empty($parent)) {
682 Logger::debug('Posting done', ['return' => $parent]);
686 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
687 $uri = bluesky_get_uri($parent);
688 Item::update(['extid' => $uri], ['id' => $item['id']]);
689 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
694 function bluesky_get_urls(string $body): array
696 // Remove all hashtag and mention links
697 $body = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
699 $body = BBCode::expandVideoLinks($body);
702 // Search for hash tags
703 if (preg_match_all("/#\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
704 foreach ($matches as $match) {
705 $text = '#' . $match[2];
706 $urls[] = ['tag' => $match[2], 'text' => $text, 'hash' => $text];
707 $body = str_replace($match[0], $text, $body);
711 // Search for pure links
712 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
713 foreach ($matches as $match) {
714 $text = Strings::getStyledURL($match[1]);
715 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
716 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
717 $body = str_replace($match[0], $hash, $body);
721 // Search for links with descriptions
722 if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
723 foreach ($matches as $match) {
724 if ($match[1] == $match[2]) {
725 $text = Strings::getStyledURL($match[1]);
729 if (mb_strlen($text) < 100) {
730 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
731 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
732 $body = str_replace($match[0], $hash, $body);
734 $text = Strings::getStyledURL($match[1]);
735 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
736 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
737 $body = str_replace($match[0], $text . ' ' . $hash, $body);
742 return ['body' => $body, 'urls' => $urls];
745 function bluesky_get_hash_for_url(string $text, int $linklength): string
747 if ($linklength <= 10) {
748 return '|' . hash('crc32', $text) . '|';
750 return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
753 function bluesky_get_facets(string $body, array $urls): array
757 foreach ($urls as $url) {
758 $pos = strpos($body, $url['hash']);
759 if ($pos === false) {
763 $prefix = substr($body, 0, $pos);
768 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
770 $facet = new stdClass;
771 $facet->index = new stdClass;
772 $facet->index->byteEnd = $pos + strlen($url['text']);
773 $facet->index->byteStart = $pos;
775 $feature = new stdClass;
778 if (!empty($url['tag'])) {
779 $feature->tag = $url['tag'];
780 $feature->$type = 'app.bsky.richtext.facet#tag';
781 } elseif (!empty($url['url'])) {
782 $feature->uri = $url['url'];
783 $feature->$type = 'app.bsky.richtext.facet#link';
788 $facet->features = [$feature];
792 return ['facets' => $facets, 'body' => $body];
795 function bluesky_add_embed(int $uid, array $msg, array $record): array
797 if (($msg['type'] != 'link') && !empty($msg['images'])) {
799 foreach ($msg['images'] as $image) {
800 if (count($images) == 4) {
803 $photo = Photo::selectFirst([], ['id' => $image['id']]);
804 $blob = bluesky_upload_blob($uid, $photo);
808 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
810 if (!empty($images)) {
811 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
813 } elseif ($msg['type'] == 'link') {
815 '$type' => 'app.bsky.embed.external',
817 'uri' => $msg['url'],
818 'title' => $msg['title'] ?? '',
819 'description' => $msg['description'] ?? '',
822 if (!empty($msg['image'])) {
823 $photo = Photo::createPhotoForExternalResource($msg['image']);
824 $blob = bluesky_upload_blob($uid, $photo);
826 $record['embed']['external']['thumb'] = $blob;
833 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
835 $retrial = Worker::getRetrial();
836 $content = Photo::getImageForPhoto($photo);
838 $picture = new Image($content, $photo['type']);
839 $height = $picture->getHeight();
840 $width = $picture->getWidth();
841 $size = strlen($content);
843 $picture = Photo::resizeToFileSize($picture, BLUESKY_IMAGE_SIZE[$retrial]);
844 $new_height = $picture->getHeight();
845 $new_width = $picture->getWidth();
846 $content = $picture->asString();
847 $new_size = strlen($content);
849 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]);
851 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
853 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]);
857 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]);
861 function bluesky_delete_post(string $uri, int $uid)
863 $parts = bluesky_get_uri_parts($uri);
865 Logger::debug('No uri delected', ['uri' => $uri]);
868 bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
869 Logger::debug('Deleted', ['parts' => $parts]);
872 function bluesky_fetch_timeline(int $uid)
874 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
879 if (empty($data->feed)) {
883 foreach (array_reverse($data->feed) as $entry) {
884 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
885 if (!empty($entry->reason)) {
886 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
890 // @todo Support paging
891 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
894 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
897 if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
901 $contact = bluesky_get_contact($reason->by, $uid, $uid);
904 'network' => Protocol::BLUESKY,
907 'uri' => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
908 'private' => Item::UNLISTED,
909 'verb' => Activity::POST,
910 'contact-id' => $contact['id'],
911 'author-name' => $contact['name'],
912 'author-link' => $contact['url'],
913 'author-avatar' => $contact['avatar'],
914 'verb' => Activity::ANNOUNCE,
915 'body' => Activity::ANNOUNCE,
916 'gravity' => Item::GRAVITY_ACTIVITY,
917 'object-type' => Activity\ObjectType::NOTE,
918 'thr-parent' => $uri,
921 if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
925 $item['guid'] = Item::guidFromUri($item['uri'], $contact['alias']);
926 $item['owner-name'] = $item['author-name'];
927 $item['owner-link'] = $item['author-link'];
928 $item['owner-avatar'] = $item['author-avatar'];
929 if (Item::insert($item)) {
930 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
931 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
935 function bluesky_fetch_notifications(int $uid)
937 $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
938 if (empty($data->notifications)) {
941 foreach ($data->notifications as $notification) {
942 $uri = bluesky_get_uri($notification);
943 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
944 Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
947 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
948 switch ($notification->reason) {
950 $item = bluesky_get_header($notification, $uri, $uid, $uid);
951 $item['gravity'] = Item::GRAVITY_ACTIVITY;
952 $item['body'] = $item['verb'] = Activity::LIKE;
953 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
954 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, $item['contact-id'], 0);
955 if (!empty($item['thr-parent'])) {
956 $data = Item::insert($item);
957 Logger::debug('Got like', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
959 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
964 $item = bluesky_get_header($notification, $uri, $uid, $uid);
965 $item['gravity'] = Item::GRAVITY_ACTIVITY;
966 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
967 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
968 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $uid, $item['contact-id'], 0);
969 if (!empty($item['thr-parent'])) {
970 $data = Item::insert($item);
971 Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
973 Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $item['thr-parent'], 'uri' => $uri]);
978 $contact = bluesky_get_contact($notification->author, $uid, $uid);
979 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
983 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
984 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
988 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
989 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
993 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
994 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
998 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
1004 function bluesky_fetch_feed(int $uid, string $feed)
1006 $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
1011 if (empty($data->feed)) {
1015 $feeddata = bluesky_xrpc_get($uid, 'app.bsky.feed.getFeedGenerator', ['feed' => $feed]);
1016 if (!empty($feeddata)) {
1017 $feedurl = $feeddata->view->uri;
1018 $feedname = $feeddata->view->displayName;
1024 foreach (array_reverse($data->feed) as $entry) {
1025 $contact = bluesky_get_contact($entry->post->author, 0, $uid);
1026 $languages = $entry->post->record->langs ?? [];
1028 if (!Relay::isWantedLanguage($entry->post->record->text, 0, $contact['id'] ?? 0, $languages)) {
1029 Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
1032 $id = bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
1034 $post = Post::selectFirst(['uri-id'], ['id' => $id]);
1035 if (!empty($post['uri-id'])) {
1036 $stored = Post\Category::storeFileByURIId($post['uri-id'], $uid, Post\Category::SUBCRIPTION, $feedname, $feedurl);
1037 Logger::debug('Stored tag subscription for user', ['uri-id' => $post['uri-id'], 'uid' => $uid, 'name' => $feedname, 'url' => $feedurl, 'stored' => $stored]);
1039 Logger::notice('Post not found', ['id' => $id, 'entry' => $entry]);
1042 if (!empty($entry->reason)) {
1043 bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
1048 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
1050 $uri = bluesky_get_uri($post);
1052 if ($id = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $uid])) {
1056 if ($id = Post::selectFirst(['id'], ['extid' => $uri, 'uid' => $uid])) {
1060 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
1062 $item = bluesky_get_header($post, $uri, $uid, $uid);
1063 $item = bluesky_get_content($item, $post->record, $uri, $uid, $uid, $level);
1068 if (!empty($post->embed)) {
1069 $item = bluesky_add_media($post->embed, $item, $uid, $level);
1072 if (empty($item['post-reason'])) {
1073 $item['post-reason'] = $post_reason;
1076 return item::insert($item);
1079 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
1081 $parts = bluesky_get_uri_parts($uri);
1082 if (empty($post->author)) {
1085 $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
1087 'network' => Protocol::BLUESKY,
1091 'guid' => $post->cid,
1092 'private' => Item::UNLISTED,
1093 'verb' => Activity::POST,
1094 'contact-id' => $contact['id'],
1095 'author-name' => $contact['name'],
1096 'author-link' => $contact['url'],
1097 'author-avatar' => $contact['avatar'],
1098 'plink' => $contact['alias'] . '/post/' . $parts->rkey,
1099 'source' => json_encode($post),
1102 $item['uri-id'] = ItemURI::getIdByURI($uri);
1103 $item['owner-name'] = $item['author-name'];
1104 $item['owner-link'] = $item['author-link'];
1105 $item['owner-avatar'] = $item['author-avatar'];
1107 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1108 $item['post-reason'] = Item::PR_FOLLOWER;
1114 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $fetch_uid, int $level): array
1120 if (!empty($record->reply)) {
1121 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1122 if ($item['parent-uri'] != $uri) {
1123 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $fetch_uid, $item['contact-id'], $level);
1124 if (empty($item['parent-uri'])) {
1129 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1130 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1131 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $fetch_uid, $item['contact-id'], $level, $item['parent-uri']);
1132 if (empty($item['thr-parent'])) {
1138 $item['body'] = bluesky_get_text($record, $item['uri-id']);
1139 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1140 $item['transmitted-languages'] = $record->langs ?? [];
1144 function bluesky_get_text(stdClass $record, int $uri_id): string
1146 $text = $record->text ?? '';
1148 if (empty($record->facets)) {
1153 foreach ($record->facets as $facet) {
1154 $facets[$facet->index->byteStart] = $facet;
1158 foreach ($facets as $facet) {
1159 $prefix = substr($text, 0, $facet->index->byteStart);
1160 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1161 $suffix = substr($text, $facet->index->byteEnd);
1165 foreach ($facet->features as $feature) {
1167 switch ($feature->$type) {
1168 case 'app.bsky.richtext.facet#link':
1169 $url = $feature->uri;
1172 case 'app.bsky.richtext.facet#mention':
1173 $contact = Contact::getByURL($feature->did, null, ['id']);
1174 if (!empty($contact['id'])) {
1175 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1176 if (substr($linktext, 0, 1) == '@') {
1178 $linktext = substr($linktext, 1);
1183 case 'app.bsky.richtext.facet#tag';
1184 Tag::store($uri_id, Tag::HASHTAG, $feature->tag);
1185 $url = DI::baseUrl() . '/search?tag=' . urlencode($feature->tag);
1186 $linktext = '#' . $feature->tag;
1190 Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'feature' => $feature, 'record' => $record]);
1195 $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1201 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1204 switch ($embed->$type) {
1205 case 'app.bsky.embed.images#view':
1206 foreach ($embed->images as $image) {
1208 'uri-id' => $item['uri-id'],
1209 'type' => Post\Media::IMAGE,
1210 'url' => $image->fullsize,
1211 'preview' => $image->thumb,
1212 'description' => $image->alt,
1214 Post\Media::insert($media);
1218 case 'app.bsky.embed.external#view':
1220 'uri-id' => $item['uri-id'],
1221 'type' => Post\Media::HTML,
1222 'url' => $embed->external->uri,
1223 'name' => $embed->external->title,
1224 'description' => $embed->external->description,
1226 Post\Media::insert($media);
1229 case 'app.bsky.embed.record#view':
1230 $uri = bluesky_get_uri($embed->record);
1231 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1232 if (empty($shared)) {
1233 if (empty($embed->record->value)) {
1234 Logger::info('Record has got no value', ['record' => $embed->record]);
1237 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1238 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $fetch_uid, $level);
1239 if (!empty($shared)) {
1240 if (!empty($embed->record->embeds)) {
1241 foreach ($embed->record->embeds as $single) {
1242 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1245 Item::insert($shared);
1248 if (!empty($shared['uri-id'])) {
1249 $item['quote-uri-id'] = $shared['uri-id'];
1253 case 'app.bsky.embed.recordWithMedia#view':
1254 $uri = bluesky_get_uri($embed->record->record);
1255 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1256 if (empty($shared)) {
1257 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1258 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $fetch_uid, $level);
1259 if (!empty($shared)) {
1260 if (!empty($embed->record->record->embeds)) {
1261 foreach ($embed->record->record->embeds as $single) {
1262 $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1265 Item::insert($shared);
1268 if (!empty($shared['uri-id'])) {
1269 $item['quote-uri-id'] = $shared['uri-id'];
1272 if (!empty($embed->media)) {
1273 $item = bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1278 Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1284 function bluesky_get_uri(stdClass $post): string
1286 if (empty($post->cid)) {
1287 Logger::info('Invalid URI', ['post' => $post]);
1290 return $post->uri . ':' . $post->cid;
1293 function bluesky_get_uri_class(string $uri): ?stdClass
1299 $elements = explode(':', $uri);
1300 if (empty($elements) || ($elements[0] != 'at')) {
1301 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1302 return bluesky_get_uri_class($post['extid'] ?? '');
1305 $class = new stdClass;
1307 $class->cid = array_pop($elements);
1308 $class->uri = implode(':', $elements);
1310 if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1311 $class->uri .= ':' . $class->cid;
1318 function bluesky_get_uri_parts(string $uri): ?stdClass
1320 $class = bluesky_get_uri_class($uri);
1321 if (empty($class)) {
1325 $parts = explode('/', substr($class->uri, 5));
1327 $class = new stdClass;
1329 $class->repo = $parts[0];
1330 $class->collection = $parts[1];
1331 $class->rkey = $parts[2];
1336 function bluesky_fetch_missing_post(string $uri, int $uid, int $fetch_uid, int $causer, int $level, string $fallback = ''): string
1338 $fetched_uri = bluesky_fetch_post($uri, $uid);
1339 if (!empty($fetched_uri)) {
1340 return $fetched_uri;
1343 if (++$level > 100) {
1344 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1345 // When the level is too deep we will fallback to the parent uri.
1346 // Allthough the threading won't be correct, we at least had stored all posts and won't try again
1350 $class = bluesky_get_uri_class($uri);
1351 $fetch_uri = $class->uri;
1353 Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1354 $data = bluesky_xrpc_get($fetch_uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1356 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1360 Logger::debug('Reply count', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1363 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1368 return bluesky_process_thread($data->thread, $uid, $fetch_uid, $cdata, $level);
1371 function bluesky_fetch_post(string $uri, int $uid): string
1373 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1374 Logger::debug('Post exists', ['uri' => $uri]);
1378 $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1379 if (!empty($reply['uri'])) {
1380 Logger::debug('Post with extid exists', ['uri' => $uri]);
1381 return $reply['uri'];
1386 function bluesky_process_thread(stdClass $thread, int $uid, int $fetch_uid, array $cdata, int $level): string
1388 if (empty($thread->post)) {
1389 Logger::info('Invalid post', ['post' => $thread]);
1392 $uri = bluesky_get_uri($thread->post);
1394 $fetched_uri = bluesky_fetch_post($uri, $uid);
1395 if (empty($fetched_uri)) {
1396 Logger::debug('Process missing post', ['uri' => $uri]);
1397 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1398 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $fetch_uid, $level);
1399 if (!empty($item)) {
1400 $item['post-reason'] = Item::PR_FETCHED;
1402 if (!empty($cdata['public'])) {
1403 $item['causer-id'] = $cdata['public'];
1406 if (!empty($thread->post->embed)) {
1407 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1409 $id = Item::insert($item);
1411 Logger::info('Item has not not been stored', ['uri' => $uri]);
1414 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1416 Logger::info('Post has not not been fetched', ['uri' => $uri]);
1420 Logger::debug('Post exists', ['uri' => $uri]);
1421 $uri = $fetched_uri;
1424 foreach ($thread->replies ?? [] as $reply) {
1425 $reply_uri = bluesky_process_thread($reply, $uid, $fetch_uid, $cdata, $level);
1426 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1432 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1434 $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1435 $contact = Contact::selectFirst(['id', 'updated'], $condition);
1437 $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1439 $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1441 $public_fields['uid'] = 0;
1442 $public_fields['rel'] = Contact::NOTHING;
1444 if (empty($contact)) {
1445 $cid = Contact::insert($public_fields);
1447 $cid = $contact['id'];
1448 Contact::update($public_fields, ['id' => $cid], true);
1452 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1454 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1455 if (!isset($fields['rel']) && isset($contact['rel'])) {
1456 $fields['rel'] = $contact['rel'];
1457 } elseif (!isset($fields['rel'])) {
1458 $fields['rel'] = Contact::NOTHING;
1462 if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1463 if (empty($contact)) {
1464 $cid = Contact::insert($fields);
1466 $cid = $contact['id'];
1467 Contact::update($fields, ['id' => $cid], true);
1469 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1471 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1473 if (!empty($author->avatar)) {
1474 Contact::updateAvatar($cid, $author->avatar);
1477 return Contact::getById($cid);
1480 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1484 'network' => Protocol::BLUESKY,
1488 'readonly' => false,
1490 'url' => $author->did,
1491 'nurl' => $author->did,
1492 'alias' => BLUESKY_WEB . '/profile/' . $author->handle,
1493 'name' => $author->displayName ?? $author->handle,
1494 'nick' => $author->handle,
1495 'addr' => $author->handle,
1499 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1503 $fields['baseurl'] = bluesky_get_pds($author->did);
1504 if (!empty($fields['baseurl'])) {
1505 GServer::check($fields['baseurl'], Protocol::BLUESKY);
1506 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
1509 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1511 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1515 $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1517 if (!empty($data->description)) {
1518 $fields['about'] = HTML::toBBCode($data->description);
1521 if (!empty($data->banner)) {
1522 $fields['header'] = $data->banner;
1525 if (!empty($data->viewer)) {
1526 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1527 $fields['rel'] = Contact::FRIEND;
1528 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1529 $fields['rel'] = Contact::SHARING;
1530 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1531 $fields['rel'] = Contact::FOLLOWER;
1533 $fields['rel'] = Contact::NOTHING;
1537 Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1541 function bluesky_get_feeds(int $uid): array
1544 $preferences = bluesky_get_preferences($uid);
1545 foreach ($preferences->preferences as $preference) {
1546 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1547 return $preference->pinned ?? [];
1553 function bluesky_get_preferences(int $uid): stdClass
1555 $cachekey = 'bluesky:preferences:' . $uid;
1556 $data = DI::cache()->get($cachekey);
1557 if (!is_null($data)) {
1561 $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1563 DI::cache()->set($cachekey, $data, Duration::HOUR);
1567 function bluesky_get_did(string $handle): string
1569 $data = bluesky_get(BLUESKY_PDS . '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1573 Logger::debug('Got DID', ['return' => $data]);
1577 function bluesky_get_user_pds(int $uid): string
1579 $pds = DI::pConfig()->get($uid, 'bluesky', 'pds');
1583 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1585 Logger::notice('Empty did for user', ['uid' => $uid]);
1588 $pds = bluesky_get_pds($did);
1589 DI::pConfig()->set($uid, 'bluesky', 'pds', $pds);
1593 function bluesky_get_pds(string $did): ?string
1595 $data = bluesky_get(BLUESKY_DIRECTORY . '/' . $did);
1596 if (empty($data) || empty($data->service)) {
1600 foreach ($data->service as $service) {
1601 if (($service->id == '#atproto_pds') && ($service->type == 'AtprotoPersonalDataServer') && !empty($service->serviceEndpoint)) {
1602 return $service->serviceEndpoint;
1609 function bluesky_get_token(int $uid): string
1611 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1612 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1613 if (empty($token)) {
1617 if ($created + 300 < time()) {
1618 return bluesky_refresh_token($uid);
1623 function bluesky_refresh_token(int $uid): string
1625 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1627 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1632 Logger::debug('Refreshed token', ['return' => $data]);
1633 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1634 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1635 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1636 return $data->accessJwt;
1639 function bluesky_create_token(int $uid, string $password): string
1641 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1643 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1648 Logger::debug('Created token', ['return' => $data]);
1649 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1650 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1651 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1652 return $data->accessJwt;
1655 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1657 return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1660 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1663 $curlResult = DI::httpClient()->post(bluesky_get_user_pds($uid) . $url, $params, $headers);
1664 } catch (\Exception $e) {
1665 Logger::notice('Exception on post', ['exception' => $e]);
1669 if (!$curlResult->isSuccess()) {
1670 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1674 return json_decode($curlResult->getBody());
1677 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1679 if (!empty($parameters)) {
1680 $url .= '?' . http_build_query($parameters);
1683 return bluesky_get(bluesky_get_user_pds($uid) . '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1686 function bluesky_get(string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1689 $curlResult = DI::httpClient()->get($url, $accept_content, $opts);
1690 } catch (\Exception $e) {
1691 Logger::notice('Exception on get', ['exception' => $e]);
1695 if (!$curlResult->isSuccess()) {
1696 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1700 return json_decode($curlResult->getBody());