3 * Name: Bluesky Connector
4 * Description: Post to Bluesky
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 * - detect incoming reshares
11 * - detect contact relations
12 * - alternate link for contacts
14 * - fetch missing posts
15 * - only fetch new posts
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Config\Util\ConfigFileManager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\ItemURI;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
40 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
41 use Friendica\Protocol\Activity;
42 use Friendica\Util\DateTimeFormat;
44 define('BLUESKY_DEFAULT_POLL_INTERVAL', 10); // given in minutes
46 function bluesky_install()
48 Hook::register('load_config', __FILE__, 'bluesky_load_config');
49 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
50 Hook::register('post_local', __FILE__, 'bluesky_post_local');
51 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
52 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
53 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
54 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
55 Hook::register('cron', __FILE__, 'bluesky_cron');
58 function bluesky_load_config(ConfigFileManager $loader)
60 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
63 function bluesky_settings(array &$data)
65 if (!DI::userSession()->getLocalUserId()) {
69 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
70 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
71 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
72 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
73 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
74 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
75 $import = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
77 $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.');
79 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
80 $html = Renderer::replaceMacros($t, [
81 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
82 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
83 '$import' => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
84 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
85 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
86 '$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'],
87 '$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.")],
92 'connector' => 'bluesky',
93 'title' => DI::l10n()->t('Bluesky Export'),
94 'image' => 'images/bluesky.jpg',
95 'enabled' => $enabled,
100 function bluesky_settings_post(array &$b)
102 if (empty($_POST['bluesky-submit'])) {
106 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
107 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
108 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
110 $host = $_POST['bluesky_host'];
111 $handle = $_POST['bluesky_handle'];
113 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
114 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
115 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
116 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
117 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import', intval($_POST['bluesky_import']));
119 if (!empty($host) && !empty($handle)) {
120 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
121 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId()));
124 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
127 if (!empty($_POST['bluesky_password'])) {
128 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
133 function bluesky_jot_nets(array &$jotnets_fields)
135 if (!DI::userSession()->getLocalUserId()) {
139 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
140 $jotnets_fields[] = [
141 'type' => 'checkbox',
144 DI::l10n()->t('Post to Bluesky'),
145 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
151 function bluesky_cron()
153 $last = DI::keyValue()->get('bluesky_last_poll');
155 $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
156 if (!$poll_interval) {
157 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
161 $next = $last + ($poll_interval * 60);
162 if ($next > time()) {
163 Logger::notice('poll interval not reached');
167 Logger::notice('cron_start');
169 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
170 if ($abandon_days < 1) {
174 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
176 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
177 foreach ($pconfigs as $pconfig) {
178 if ($abandon_days != 0) {
179 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
180 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
185 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
186 bluesky_fetch_timeline($pconfig['uid']);
187 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
190 Logger::notice('cron_end');
192 DI::keyValue()->set('bluesky_last_poll', time());
195 function bluesky_hook_fork(array &$b)
197 if ($b['name'] != 'notifier_normal') {
203 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
204 DI::logger()->info('Editing is not supported by the addon');
205 $b['execute'] = false;
209 if (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
210 $b['execute'] = false;
215 function bluesky_post_local(array &$b)
221 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
225 if ($b['private'] || $b['parent']) {
229 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
230 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
232 // if API is used, default to the chosen settings
233 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
237 if (!$bluesky_enable) {
241 if (strlen($b['postopts'])) {
242 $b['postopts'] .= ',';
245 $b['postopts'] .= 'bluesky';
248 function bluesky_send(array &$b)
250 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
254 if ($b['gravity'] != Item::GRAVITY_PARENT) {
256 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
260 bluesky_create_post($b);
263 function bluesky_create_post(array $item)
266 $token = bluesky_get_token($uid);
271 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
273 $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
274 $parent = $root = [];
275 foreach ($msg['parts'] as $key => $part) {
278 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 '$type' => 'app.bsky.feed.post'
283 $record['reply'] = ['root' => $root, 'parent' => $parent];
286 if ($key == count($msg['parts']) - 1) {
287 $record = bluesky_add_embed($uid, $msg, $record);
291 'collection' => 'app.bsky.feed.post',
296 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
297 if (empty($parent)) {
300 Logger::debug('Posting done', ['return' => $parent]);
307 function bluesky_add_embed(int $uid, array $msg, array $record): array
309 if (($msg['type'] != 'link') && !empty($msg['images'])) {
311 foreach ($msg['images'] as $image) {
312 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
313 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
314 $blob = bluesky_upload_blob($uid, $photo);
315 if (!empty($blob) && count($images) < 4) {
316 $images[] = ['alt' => $image['description'], 'image' => $blob];
319 if (!empty($images)) {
320 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
322 } elseif ($msg['type'] == 'link') {
324 '$type' => 'app.bsky.embed.external',
326 'uri' => $msg['url'],
327 'title' => $msg['title'],
328 'description' => $msg['description'],
331 if (!empty($msg['image'])) {
332 $photo = Photo::createPhotoForExternalResource($msg['image']);
333 $blob = bluesky_upload_blob($uid, $photo);
335 $record['embed']['external']['thumb'] = $blob;
342 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
344 $content = Photo::getImageForPhoto($photo);
345 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
350 Logger::debug('Uploaded blob', ['return' => $data]);
354 function bluesky_fetch_timeline(int $uid)
356 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
361 if (empty($data->feed)) {
365 foreach (array_reverse($data->feed) as $entry) {
366 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $entry->post->indexedAt, 'uri' => $entry->post->uri, 'cid' => $entry->post->cid]);
368 bluesky_process_post($entry->post, $uid);
371 // @todo Support paging
372 // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
375 function bluesky_process_post(stdClass $post, int $uid): int
377 $uri = bluesky_get_uri($post);
379 if (Post::exists(['uri' => $uri, 'uid' => $uid])) {
383 $item = bluesky_get_header($post, $uri, $uid);
385 $item = bluesky_get_content($item, $post->record);
387 if (!empty($post->embed)) {
388 $item = bluesky_add_media($post->embed, $item);
390 return item::insert($item);
393 function bluesky_get_header(stdClass $post, string $uri, int $uid): array
395 $contact = bluesky_get_contact($post->author, $uid);
397 'network' => Protocol::BLUESKY,
401 'guid' => $post->cid,
402 'private' => Item::UNLISTED,
403 'verb' => Activity::POST,
404 'contact-id' => $contact['id'],
405 'author-name' => $contact['name'],
406 'author-link' => $contact['url'],
407 'author-avatar' => $contact['avatar'],
408 // 'plink' => '', @todo Path to a web representation
411 $item['uri-id'] = ItemURI::getIdByURI($uri);
412 $item['owner-name'] = $item['author-name'];
413 $item['owner-link'] = $item['author-link'];
414 $item['owner-avatar'] = $item['author-avatar'];
419 function bluesky_get_content(array $item, stdClass $record): array
421 if (!empty($record->reply)) {
422 $item['parent'] = bluesky_get_uri($record->reply->root);
423 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
426 $body = $record->text;
428 if (!empty($record->facets)) {
432 $item['body'] = $body;
433 $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
437 function bluesky_add_media(stdClass $embed, array $item): array
439 if (!empty($embed->images)) {
440 foreach ($embed->images as $image) {
442 'uri-id' => $item['uri-id'],
443 'type' => Post\Media::IMAGE,
444 'url' => $image->fullsize,
445 'preview' => $image->thumb,
446 'description' => $image->alt,
448 Post\Media::insert($media);
450 } elseif (!empty($embed->external)) {
451 $media = ['uri-id' => $item['uri-id'],
452 'type' => Post\Media::HTML,
453 'url' => $embed->external->uri,
454 'name' => $embed->external->title,
455 'description' => $embed->external->description,
457 Post\Media::insert($media);
458 } elseif (!empty($embed->record)) {
459 $uri = bluesky_get_uri($embed->record);
460 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
461 if (empty($shared)) {
462 $shared = bluesky_get_header($embed->record, $uri, 0);
463 $shared = bluesky_get_content($shared, $embed->record->value);
465 if (!empty($embed->record->embeds)) {
466 foreach ($embed->record->embeds as $single) {
467 $shared = bluesky_add_media($single, $shared);
470 $id = Item::insert($shared);
471 $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
473 if (!empty($shared)) {
474 $item['quote-uri-id'] = $shared['uri-id'];
477 Logger::debug('Unsupported embed', ['embed' => $embed, 'item' => $item]);
482 function bluesky_get_uri(stdClass $post): string
484 return $post->uri . ':' . $post->cid;
487 function bluesky_get_contact(stdClass $author, int $uid): array
489 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
492 'name' => $author->displayName,
493 'nick' => $author->handle,
494 'addr' => $author->handle,
497 $contact = Contact::selectFirst([], $condition);
499 if (empty($contact)) {
500 $cid = bluesky_insert_contact($author, $uid);
502 $cid = $contact['id'];
503 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
504 Contact::update($fields, ['id' => $cid]);
508 $condition['uid'] = 0;
510 $contact = Contact::selectFirst([], $condition);
511 if (empty($contact)) {
512 $pcid = bluesky_insert_contact($author, 0);
514 $pcid = $contact['id'];
515 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
516 Contact::update($fields, ['id' => $pcid]);
520 if (!empty($author->avatar)) {
521 Contact::updateAvatar($cid, $author->avatar);
524 if (empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
525 bluesky_update_contact($author, $uid, $cid, $pcid);
528 return Contact::getById($cid);
531 function bluesky_insert_contact(stdClass $author, int $uid)
535 'network' => Protocol::BLUESKY,
541 'url' => $author->did,
542 'nurl' => $author->did,
543 // 'alias' => '', @todo Path to a web representation
544 'name' => $author->displayName,
545 'nick' => $author->handle,
546 'addr' => $author->handle,
548 return Contact::insert($fields);
551 function bluesky_update_contact(stdClass $author, int $uid, int $cid, int $pcid)
553 $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
559 'name' => $data->displayName,
560 'nick' => $data->handle,
561 'addr' => $data->handle,
562 'about' => HTML::toBBCode($data->description),
563 'updated' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL),
566 if (!empty($data->banner)) {
567 $fields['header'] = $data->banner;
570 Contact::update($fields, ['id' => $cid]);
571 Contact::update($fields, ['id' => $pcid]);
574 function bluesky_get_did(int $uid): string
576 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
580 Logger::debug('Got DID', ['return' => $data]);
584 function bluesky_get_token(int $uid): string
586 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
587 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
592 if ($created + 300 < time()) {
593 return bluesky_refresh_token($uid);
598 function bluesky_refresh_token(int $uid): string
600 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
602 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
607 Logger::debug('Refreshed token', ['return' => $data]);
608 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
609 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
610 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
611 return $data->accessJwt;
614 function bluesky_create_token(int $uid, string $password): string
616 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
618 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
623 Logger::debug('Created token', ['return' => $data]);
624 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
625 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
626 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
627 return $data->accessJwt;
630 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
633 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
634 } catch (\Exception $e) {
635 Logger::notice('Exception on post', ['exception' => $e]);
639 if (!$curlResult->isSuccess()) {
640 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
644 return json_decode($curlResult->getBody());
647 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
650 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
651 } catch (\Exception $e) {
652 Logger::notice('Exception on get', ['exception' => $e]);
656 if (!$curlResult->isSuccess()) {
657 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
661 return json_decode($curlResult->getBody());