3 * Name: Bluesky Connector
4 * Description: Post to Bluesky
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
13 * Possible but less important:
14 * - Block, unblock, mute and unmute contacts
17 * - alternate link for contacts
20 * Need more information:
21 * - only fetch new posts
22 * - detect incoming reshares
23 * - detect contact relations
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Content\Text\Plaintext;
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\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
43 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
44 use Friendica\Protocol\Activity;
45 use Friendica\Util\DateTimeFormat;
47 define('BLUESKY_DEFAULT_POLL_INTERVAL', 10); // given in minutes
49 function bluesky_install()
51 Hook::register('load_config', __FILE__, 'bluesky_load_config');
52 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
53 Hook::register('post_local', __FILE__, 'bluesky_post_local');
54 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
55 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
56 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
57 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
58 Hook::register('cron', __FILE__, 'bluesky_cron');
59 // Hook::register('support_follow', __FILE__, 'bluesky_support_follow');
60 // Hook::register('support_probe', __FILE__, 'bluesky_support_probe');
61 // Hook::register('follow', __FILE__, 'bluesky_follow');
62 // Hook::register('unfollow', __FILE__, 'bluesky_unfollow');
63 // Hook::register('block', __FILE__, 'bluesky_block');
64 // Hook::register('unblock', __FILE__, 'bluesky_unblock');
65 Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
66 // Hook::register('probe_detect', __FILE__, 'bluesky_probe_detect');
67 // Hook::register('item_by_link', __FILE__, 'bluesky_item_by_link');
70 function bluesky_load_config(ConfigFileManager $loader)
72 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
75 function bluesky_check_item_notification(array &$notification_data)
77 $handle = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'handle');
78 $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
80 if (!empty($handle) && !empty($did)) {
81 $notification_data['profiles'][] = $handle;
82 $notification_data['profiles'][] = $did;
86 function bluesky_settings(array &$data)
88 if (!DI::userSession()->getLocalUserId()) {
92 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
93 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
94 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
95 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
96 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
97 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
98 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
100 $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.');
102 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
103 $html = Renderer::replaceMacros($t, [
104 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
105 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
106 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
107 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
108 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
109 '$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'],
110 '$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.")],
115 'connector' => 'bluesky',
116 'title' => DI::l10n()->t('Bluesky Import/Export'),
117 'image' => 'images/bluesky.jpg',
118 'enabled' => $enabled,
123 function bluesky_settings_post(array &$b)
125 if (empty($_POST['bluesky-submit'])) {
129 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
130 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
131 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
133 $host = $_POST['bluesky_host'];
134 $handle = $_POST['bluesky_handle'];
136 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
137 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
138 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
139 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
140 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
142 if (!empty($host) && !empty($handle)) {
143 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
144 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId()));
147 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
150 if (!empty($_POST['bluesky_password'])) {
151 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
156 function bluesky_jot_nets(array &$jotnets_fields)
158 if (!DI::userSession()->getLocalUserId()) {
162 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
163 $jotnets_fields[] = [
164 'type' => 'checkbox',
167 DI::l10n()->t('Post to Bluesky'),
168 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
174 function bluesky_cron()
176 $last = DI::keyValue()->get('bluesky_last_poll');
178 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
179 if (!$poll_interval) {
180 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
184 $next = $last + ($poll_interval * 60);
185 if ($next > time()) {
186 Logger::notice('poll interval not reached');
190 Logger::notice('cron_start');
192 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
193 if ($abandon_days < 1) {
197 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
199 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
200 foreach ($pconfigs as $pconfig) {
201 if ($abandon_days != 0) {
202 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
203 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
208 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
209 bluesky_fetch_timeline($pconfig['uid']);
210 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
213 Logger::notice('cron_end');
215 DI::keyValue()->set('bluesky_last_poll', time());
218 function bluesky_hook_fork(array &$b)
220 if ($b['name'] != 'notifier_normal') {
226 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
227 DI::logger()->info('Editing is not supported by the addon');
228 $b['execute'] = false;
232 if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
233 // Don't post if it isn't a reply to a bluesky post
234 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
235 Logger::notice('No bluesky parent found', ['item' => $post['id']]);
236 $b['execute'] = false;
239 } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
240 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
241 $b['execute'] = false;
246 function bluesky_post_local(array &$b)
252 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
256 if ($b['private'] || $b['parent']) {
260 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
261 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
263 // if API is used, default to the chosen settings
264 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
268 if (!$bluesky_enable) {
272 if (strlen($b['postopts'])) {
273 $b['postopts'] .= ',';
276 $b['postopts'] .= 'bluesky';
279 function bluesky_send(array &$b)
281 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
285 if ($b['gravity'] != Item::GRAVITY_PARENT) {
286 Logger::debug('Got comment', ['item' => $b]);
289 $uri = bluesky_get_uri_class($b['uri']);
291 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
294 bluesky_delete_post($b['uri'], $b['uid']);
298 $root = bluesky_get_uri_class($b['parent-uri']);
299 $parent = bluesky_get_uri_class($b['thr-parent']);
301 if (empty($root) || empty($parent)) {
302 Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
306 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
307 Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
308 bluesky_create_post($b, $root, $parent);
310 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
311 bluesky_create_activity($b, $parent);
314 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
318 bluesky_create_post($b);
321 function bluesky_create_activity(array $item, stdClass $parent = null)
324 $token = bluesky_get_token($uid);
329 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
331 if ($item['verb'] == Activity::LIKE) {
333 'subject' => $parent,
334 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
335 '$type' => 'app.bsky.feed.like'
339 'collection' => 'app.bsky.feed.like',
343 } elseif ($item['verb'] == Activity::ANNOUNCE) {
345 'subject' => $parent,
346 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
347 '$type' => 'app.bsky.feed.repost'
351 'collection' => 'app.bsky.feed.repost',
357 $activity = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
358 if (empty($activity)) {
361 Logger::debug('Activity done', ['return' => $activity]);
362 $uri = bluesky_get_uri($activity);
363 Item::update(['extid' => $uri], ['id' => $item['id']]);
364 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
367 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
370 $token = bluesky_get_token($uid);
375 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
377 $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
378 foreach ($msg['parts'] as $key => $part) {
381 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
382 '$type' => 'app.bsky.feed.post'
386 $record['reply'] = ['root' => $root, 'parent' => $parent];
389 if ($key == count($msg['parts']) - 1) {
390 $record = bluesky_add_embed($uid, $msg, $record);
394 'collection' => 'app.bsky.feed.post',
399 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
400 if (empty($parent)) {
403 Logger::debug('Posting done', ['return' => $parent]);
407 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
408 $uri = bluesky_get_uri($parent);
409 Item::update(['extid' => $uri], ['id' => $item['id']]);
410 Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
415 function bluesky_add_embed(int $uid, array $msg, array $record): array
417 if (($msg['type'] != 'link') && !empty($msg['images'])) {
419 foreach ($msg['images'] as $image) {
420 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
421 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
422 $blob = bluesky_upload_blob($uid, $photo);
423 if (!empty($blob) && count($images) < 4) {
424 $images[] = ['alt' => $image['description'], 'image' => $blob];
427 if (!empty($images)) {
428 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
430 } elseif ($msg['type'] == 'link') {
432 '$type' => 'app.bsky.embed.external',
434 'uri' => $msg['url'],
435 'title' => $msg['title'],
436 'description' => $msg['description'],
439 if (!empty($msg['image'])) {
440 $photo = Photo::createPhotoForExternalResource($msg['image']);
441 $blob = bluesky_upload_blob($uid, $photo);
443 $record['embed']['external']['thumb'] = $blob;
450 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
452 $content = Photo::getImageForPhoto($photo);
453 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
458 Logger::debug('Uploaded blob', ['return' => $data]);
462 function bluesky_delete_post(string $uri, int $uid)
464 $token = bluesky_get_token($uid);
465 $parts = bluesky_get_uri_parts($uri);
467 Logger::debug('No uri delected', ['uri' => $uri]);
470 bluesky_post($uid, '/xrpc/com.atproto.repo.deleteRecord', json_encode($parts), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
471 Logger::debug('Deleted', ['parts' => $parts]);
474 function bluesky_fetch_timeline(int $uid)
476 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
481 if (empty($data->feed)) {
485 foreach (array_reverse($data->feed) as $entry) {
486 bluesky_process_post($entry->post, $uid);
489 // @todo Support paging
490 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
493 function bluesky_process_post(stdClass $post, int $uid): int
495 $uri = bluesky_get_uri($post);
497 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
501 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid]);
503 $item = bluesky_get_header($post, $uri, $uid);
505 $item = bluesky_get_content($item, $post->record, $uid);
507 if (!empty($post->embed)) {
508 $item = bluesky_add_media($post->embed, $item);
510 return item::insert($item);
513 function bluesky_get_header(stdClass $post, string $uri, int $uid): array
515 $contact = bluesky_get_contact($post->author, $uid);
517 'network' => Protocol::BLUESKY,
521 'guid' => $post->cid,
522 'private' => Item::UNLISTED,
523 'verb' => Activity::POST,
524 'contact-id' => $contact['id'],
525 'author-name' => $contact['name'],
526 'author-link' => $contact['url'],
527 'author-avatar' => $contact['avatar'],
528 // 'plink' => '', @todo Path to a web representation
531 $item['uri-id'] = ItemURI::getIdByURI($uri);
532 $item['owner-name'] = $item['author-name'];
533 $item['owner-link'] = $item['author-link'];
534 $item['owner-avatar'] = $item['author-avatar'];
539 function bluesky_get_content(array $item, stdClass $record, int $uid): array
541 if (!empty($record->reply)) {
542 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
543 bluesky_fetch_missing_post($item['parent-uri'], $uid);
544 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
545 bluesky_fetch_missing_post($item['thr-parent'], $uid);
548 $body = $record->text;
550 if (!empty($record->facets)) {
554 $item['body'] = $body;
555 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
559 function bluesky_add_media(stdClass $embed, array $item): array
561 if (!empty($embed->images)) {
562 foreach ($embed->images as $image) {
564 'uri-id' => $item['uri-id'],
565 'type' => Post\Media::IMAGE,
566 'url' => $image->fullsize,
567 'preview' => $image->thumb,
568 'description' => $image->alt,
570 Post\Media::insert($media);
572 } elseif (!empty($embed->external)) {
573 $media = ['uri-id' => $item['uri-id'],
574 'type' => Post\Media::HTML,
575 'url' => $embed->external->uri,
576 'name' => $embed->external->title,
577 'description' => $embed->external->description,
579 Post\Media::insert($media);
580 } elseif (!empty($embed->record)) {
581 $uri = bluesky_get_uri($embed->record);
582 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
583 if (empty($shared)) {
584 $shared = bluesky_get_header($embed->record, $uri, 0);
585 $shared = bluesky_get_content($shared, $embed->record->value, $item['uid']);
587 if (!empty($embed->record->embeds)) {
588 foreach ($embed->record->embeds as $single) {
589 $shared = bluesky_add_media($single, $shared);
592 $id = Item::insert($shared);
593 $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
595 if (!empty($shared)) {
596 $item['quote-uri-id'] = $shared['uri-id'];
599 Logger::debug('Unsupported embed', ['embed' => $embed, 'item' => $item]);
604 function bluesky_get_uri(stdClass $post): string
606 return $post->uri . ':' . $post->cid;
609 function bluesky_get_uri_class(string $uri): ?stdClass
615 $elements = explode(':', $uri);
616 if (empty($elements) || ($elements[0] != 'at')) {
617 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
618 return bluesky_get_uri_class($post['extid'] ?? '');
621 $class = new stdClass;
623 $class->cid = array_pop($elements);
624 $class->uri = implode(':', $elements);
629 function bluesky_get_uri_parts(string $uri): ?stdClass
631 $class = bluesky_get_uri_class($uri);
636 $parts = explode('/', substr($class->uri, 5));
638 $class = new stdClass;
640 $class->repo = $parts[0];
641 $class->collection = $parts[1];
642 $class->rkey = $parts[2];
647 function bluesky_fetch_missing_post(string $uri, int $uid)
649 if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
650 Logger::debug('Post exists', ['uri' => $uri]);
654 Logger::debug('Fetch missing post', ['uri' => $uri]);
655 $class = bluesky_get_uri_class($uri);
657 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getPosts?uris=' . $class->uri, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
662 foreach ($data->posts as $post) {
663 $item = bluesky_get_header($post, $uri, $uid);
664 $item = bluesky_get_content($item, $post->record, $uid);
665 if (!empty($post->embed)) {
666 $item = bluesky_add_media($post->embed, $item);
668 $id = Item::insert($item);
669 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
673 function bluesky_get_contact(stdClass $author, int $uid): array
675 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
678 'name' => $author->displayName,
679 'nick' => $author->handle,
680 'addr' => $author->handle,
683 $contact = Contact::selectFirst([], $condition);
685 if (empty($contact)) {
686 $cid = bluesky_insert_contact($author, $uid);
688 $cid = $contact['id'];
689 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
690 Contact::update($fields, ['id' => $cid]);
694 $condition['uid'] = 0;
696 $contact = Contact::selectFirst([], $condition);
697 if (empty($contact)) {
698 $pcid = bluesky_insert_contact($author, 0);
700 $pcid = $contact['id'];
701 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
702 Contact::update($fields, ['id' => $pcid]);
706 if (!empty($author->avatar)) {
707 Contact::updateAvatar($cid, $author->avatar);
710 if (empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
711 bluesky_update_contact($author, $uid, $cid, $pcid);
714 return Contact::getById($cid);
717 function bluesky_insert_contact(stdClass $author, int $uid)
721 'network' => Protocol::BLUESKY,
727 'url' => $author->did,
728 'nurl' => $author->did,
729 // 'alias' => '', @todo Path to a web representation
730 'name' => $author->displayName,
731 'nick' => $author->handle,
732 'addr' => $author->handle,
734 return Contact::insert($fields);
737 function bluesky_update_contact(stdClass $author, int $uid, int $cid, int $pcid)
739 $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
745 'name' => $data->displayName,
746 'nick' => $data->handle,
747 'addr' => $data->handle,
748 'about' => HTML::toBBCode($data->description),
749 'updated' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL),
752 if (!empty($data->banner)) {
753 $fields['header'] = $data->banner;
756 Contact::update($fields, ['id' => $cid]);
757 Contact::update($fields, ['id' => $pcid]);
760 function bluesky_get_did(int $uid): string
762 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
766 Logger::debug('Got DID', ['return' => $data]);
770 function bluesky_get_token(int $uid): string
772 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
773 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
778 if ($created + 300 < time()) {
779 return bluesky_refresh_token($uid);
784 function bluesky_refresh_token(int $uid): string
786 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
788 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
793 Logger::debug('Refreshed token', ['return' => $data]);
794 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
795 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
796 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
797 return $data->accessJwt;
800 function bluesky_create_token(int $uid, string $password): string
802 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
804 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
809 Logger::debug('Created token', ['return' => $data]);
810 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
811 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
812 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
813 return $data->accessJwt;
816 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
819 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
820 } catch (\Exception $e) {
821 Logger::notice('Exception on post', ['exception' => $e]);
825 if (!$curlResult->isSuccess()) {
826 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
830 return json_decode($curlResult->getBody());
833 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
836 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
837 } catch (\Exception $e) {
838 Logger::notice('Exception on get', ['exception' => $e]);
842 if (!$curlResult->isSuccess()) {
843 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
847 return json_decode($curlResult->getBody());