]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
Bluesky import and transmission of activities is now possible
[friendica-addons.git] / bluesky / bluesky.php
1 <?php
2 /**
3  * Name: Bluesky Connector
4  * Description: Post to Bluesky
5  * Version: 1.1
6  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
7  *
8  * @todo
9  * Piece of cake?
10  * - Process facets
11  * - create facets
12  *
13  * Possible but less important:
14  * - Block, unblock, mute and unmute contacts
15  *
16  * Need inspiration:
17  * - alternate link for contacts
18  * - plink for posts
19  *
20  * Need more information:
21  * - only fetch new posts
22  * - detect incoming reshares
23  * - detect contact relations
24  * - receive likes
25  */
26
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;
36 use Friendica\DI;
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;
46
47 define('BLUESKY_DEFAULT_POLL_INTERVAL', 10); // given in minutes
48
49 function bluesky_install()
50 {
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');
68 }
69
70 function bluesky_load_config(ConfigFileManager $loader)
71 {
72         DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
73 }
74
75 function bluesky_check_item_notification(array &$notification_data)
76 {
77         $handle = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'handle');
78         $did    = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
79
80         if (!empty($handle) && !empty($did)) {
81                 $notification_data['profiles'][] = $handle;
82                 $notification_data['profiles'][] = $did;
83         }
84 }
85
86 function bluesky_settings(array &$data)
87 {
88         if (!DI::userSession()->getLocalUserId()) {
89                 return;
90         }
91
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;
99
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.');
101
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.")],
111                 '$status'    => $status
112         ]);
113
114         $data = [
115                 'connector' => 'bluesky',
116                 'title'     => DI::l10n()->t('Bluesky Import/Export'),
117                 'image'     => 'images/bluesky.jpg',
118                 'enabled'   => $enabled,
119                 'html'      => $html,
120         ];
121 }
122
123 function bluesky_settings_post(array &$b)
124 {
125         if (empty($_POST['bluesky-submit'])) {
126                 return;
127         }
128
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');
132
133         $host   = $_POST['bluesky_host'];
134         $handle = $_POST['bluesky_handle'];
135
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']));
141
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()));
145                 }
146         } else {
147                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
148         }
149
150         if (!empty($_POST['bluesky_password'])) {
151                 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
152         }
153
154 }
155
156 function bluesky_jot_nets(array &$jotnets_fields)
157 {
158         if (!DI::userSession()->getLocalUserId()) {
159                 return;
160         }
161
162         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
163                 $jotnets_fields[] = [
164                         'type'  => 'checkbox',
165                         'field' => [
166                                 'bluesky_enable',
167                                 DI::l10n()->t('Post to Bluesky'),
168                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
169                         ]
170                 ];
171         }
172 }
173
174 function bluesky_cron()
175 {
176         $last = DI::keyValue()->get('bluesky_last_poll');
177
178         $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
179         if (!$poll_interval) {
180                 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
181         }
182
183         if ($last) {
184                 $next = $last + ($poll_interval * 60);
185                 if ($next > time()) {
186                         Logger::notice('poll interval not reached');
187                         return;
188                 }
189         }
190         Logger::notice('cron_start');
191
192         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
193         if ($abandon_days < 1) {
194                 $abandon_days = 0;
195         }
196
197         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
198
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']]);
204                                 continue;
205                         }
206                 }
207
208                 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
209                 bluesky_fetch_timeline($pconfig['uid']);
210                 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
211         }
212
213         Logger::notice('cron_end');
214
215         DI::keyValue()->set('bluesky_last_poll', time());
216 }
217
218 function bluesky_hook_fork(array &$b)
219 {
220         if ($b['name'] != 'notifier_normal') {
221                 return;
222         }
223
224         $post = $b['data'];
225
226         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
227                 DI::logger()->info('Editing is not supported by the addon');
228                 $b['execute'] = false;
229                 return;
230         }
231
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;
237                         return;
238                 }
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;
242                 return;
243         }
244 }
245
246 function bluesky_post_local(array &$b)
247 {
248         if ($b['edit']) {
249                 return;
250         }
251
252         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
253                 return;
254         }
255
256         if ($b['private'] || $b['parent']) {
257                 return;
258         }
259
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);
262
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'))) {
265                 $bluesky_enable = 1;
266         }
267
268         if (!$bluesky_enable) {
269                 return;
270         }
271
272         if (strlen($b['postopts'])) {
273                 $b['postopts'] .= ',';
274         }
275
276         $b['postopts'] .= 'bluesky';
277 }
278
279 function bluesky_send(array &$b)
280 {
281         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
282                 return;
283         }
284
285         if ($b['gravity'] != Item::GRAVITY_PARENT) {
286                 Logger::debug('Got comment', ['item' => $b]);
287
288                 if ($b['deleted']) {
289                         $uri = bluesky_get_uri_class($b['uri']);
290                         if (empty($uri)) {
291                                 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
292                                 return;
293                         }
294                         bluesky_delete_post($b['uri'], $b['uid']);
295                         return;
296                 }
297
298                 $root   = bluesky_get_uri_class($b['parent-uri']);
299                 $parent = bluesky_get_uri_class($b['thr-parent']);
300
301                 if (empty($root) || empty($parent)) {
302                         Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
303                         return;
304                 }
305
306                 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
307                         Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
308                         bluesky_create_post($b, $root, $parent);
309                         return;
310                 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
311                         bluesky_create_activity($b, $parent);
312                 }
313                 return;
314         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
315                 return;
316         }
317
318         bluesky_create_post($b);
319 }
320
321 function bluesky_create_activity(array $item, stdClass $parent = null)
322 {
323         $uid = $item['uid'];
324         $token = bluesky_get_token($uid);
325         if (empty($token)) {
326                 return;
327         }
328
329         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
330
331         if ($item['verb'] == Activity::LIKE) {
332                 $record = [
333                         'subject'   => $parent,
334                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
335                         '$type'     => 'app.bsky.feed.like'
336                 ];
337                 
338                 $post = [
339                         'collection' => 'app.bsky.feed.like',
340                         'repo'       => $did,
341                         'record'     => $record
342                 ];
343         } elseif ($item['verb'] == Activity::ANNOUNCE) {
344                 $record = [
345                         'subject'   => $parent,
346                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
347                         '$type'     => 'app.bsky.feed.repost'
348                 ];
349
350                 $post = [
351                         'collection' => 'app.bsky.feed.repost',
352                         'repo'       => $did,
353                         'record'     => $record
354                 ];
355         }
356
357         $activity = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
358         if (empty($activity)) {
359                 return;
360         }
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]);
365 }
366
367 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
368 {
369         $uid = $item['uid'];
370         $token = bluesky_get_token($uid);
371         if (empty($token)) {
372                 return;
373         }
374
375         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
376
377         $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
378         foreach ($msg['parts'] as $key => $part) {
379                 $record = [
380                         'text'      => $part,
381                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
382                         '$type'     => 'app.bsky.feed.post'
383                 ];
384
385                 if (!empty($root)) {
386                         $record['reply'] = ['root' => $root, 'parent' => $parent];
387                 }
388
389                 if ($key == count($msg['parts']) - 1) {
390                         $record = bluesky_add_embed($uid, $msg, $record);
391                 }
392
393                 $post = [
394                         'collection' => 'app.bsky.feed.post',
395                         'repo'       => $did,
396                         'record'     => $record
397                 ];
398
399                 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
400                 if (empty($parent)) {
401                         return;
402                 }
403                 Logger::debug('Posting done', ['return' => $parent]);
404                 if (empty($root)) {
405                         $root = $parent;
406                 }
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]);
411                 }
412         }
413 }
414
415 function bluesky_add_embed(int $uid, array $msg, array $record): array
416 {
417         if (($msg['type'] != 'link') && !empty($msg['images'])) {
418                 $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];
425                         }
426                 }
427                 if (!empty($images)) {
428                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
429                 }
430         } elseif ($msg['type'] == 'link') {
431                 $record['embed'] = [
432                         '$type'    => 'app.bsky.embed.external',
433                         'external' => [
434                                 'uri'         => $msg['url'],
435                                 'title'       => $msg['title'],
436                                 'description' => $msg['description'],
437                         ]
438                 ];
439                 if (!empty($msg['image'])) {
440                         $photo = Photo::createPhotoForExternalResource($msg['image']);
441                         $blob = bluesky_upload_blob($uid, $photo);
442                         if (!empty($blob)) {
443                                 $record['embed']['external']['thumb'] = $blob;
444                         }
445                 }
446         }
447         return $record;
448 }
449
450 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
451 {
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)]]);
454         if (empty($data)) {
455                 return null;
456         }
457
458         Logger::debug('Uploaded blob', ['return' => $data]);
459         return $data->blob;
460 }
461
462 function bluesky_delete_post(string $uri, int $uid)
463 {
464         $token = bluesky_get_token($uid);
465         $parts = bluesky_get_uri_parts($uri);
466         if (empty($parts)) {
467                 Logger::debug('No uri delected', ['uri' => $uri]);
468                 return;
469         }
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]);
472 }
473
474 function bluesky_fetch_timeline(int $uid)
475 {
476         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
477         if (empty($data)) {
478                 return;
479         }
480
481         if (empty($data->feed)) {
482                 return;
483         }
484
485         foreach (array_reverse($data->feed) as $entry) {
486                 bluesky_process_post($entry->post, $uid);
487         }
488
489         // @todo Support paging
490         // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
491 }
492
493 function bluesky_process_post(stdClass $post, int $uid): int
494 {
495         $uri = bluesky_get_uri($post);
496
497         if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
498                 return 0;
499         }
500
501         Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid]);
502
503         $item = bluesky_get_header($post, $uri, $uid);
504
505         $item = bluesky_get_content($item, $post->record, $uid);
506
507         if (!empty($post->embed)) {
508                 $item = bluesky_add_media($post->embed, $item);
509         }
510         return item::insert($item);
511 }
512
513 function bluesky_get_header(stdClass $post, string $uri, int $uid): array
514 {
515         $contact = bluesky_get_contact($post->author, $uid);
516         $item = [
517                 'network'       => Protocol::BLUESKY,
518                 'uid'           => $uid,
519                 'wall'          => false,
520                 'uri'           => $uri,
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
529         ];
530
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'];
535
536         return $item;
537 }
538
539 function bluesky_get_content(array $item, stdClass $record, int $uid): array
540 {
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);
546         }
547
548         $body = $record->text;
549
550         if (!empty($record->facets)) {
551                 // @todo add Links
552         }
553
554         $item['body']    = $body;
555         $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
556         return $item;
557 }
558
559 function bluesky_add_media(stdClass $embed, array $item): array
560 {
561         if (!empty($embed->images)) {
562                 foreach ($embed->images as $image) {
563                         $media = [
564                                 'uri-id'      => $item['uri-id'],
565                                 'type'        => Post\Media::IMAGE,
566                                 'url'         => $image->fullsize,
567                                 'preview'     => $image->thumb,
568                                 'description' => $image->alt,
569                         ];
570                         Post\Media::insert($media);
571                 }
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,
578                 ];
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']);
586
587                         if (!empty($embed->record->embeds)) {
588                                 foreach ($embed->record->embeds as $single) {
589                                         $shared = bluesky_add_media($single, $shared);
590                                 }
591                         }
592                         $id = Item::insert($shared);
593                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
594                 }
595                 if (!empty($shared)) {
596                         $item['quote-uri-id'] = $shared['uri-id'];
597                 }
598         } else {
599                 Logger::debug('Unsupported embed', ['embed' => $embed, 'item' => $item]);
600         }
601         return $item;
602 }
603
604 function bluesky_get_uri(stdClass $post): string
605 {
606         return $post->uri . ':' . $post->cid;
607 }
608
609 function bluesky_get_uri_class(string $uri): ?stdClass
610 {
611         if (empty($uri)) {
612                 return null;
613         }
614
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'] ?? '');
619         }
620
621         $class = new stdClass;
622
623         $class->cid = array_pop($elements);
624         $class->uri = implode(':', $elements);
625
626         return $class;
627 }
628
629 function bluesky_get_uri_parts(string $uri): ?stdClass
630 {
631         $class = bluesky_get_uri_class($uri);
632         if (empty($class)) {
633                 return null;
634         }
635
636         $parts = explode('/', substr($class->uri, 5));
637
638         $class = new stdClass;
639
640         $class->repo       = $parts[0];
641         $class->collection = $parts[1];
642         $class->rkey       = $parts[2];
643
644         return $class;
645 }
646
647 function bluesky_fetch_missing_post(string $uri, int $uid)
648 {
649         if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
650                 Logger::debug('Post exists', ['uri' => $uri]);
651                 return;
652         }
653
654         Logger::debug('Fetch missing post', ['uri' => $uri]);
655         $class = bluesky_get_uri_class($uri);
656         
657         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getPosts?uris=' . $class->uri, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
658         if (empty($data)) {
659                 return;
660         }
661
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);
667                 }
668                 $id = Item::insert($item);
669                 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
670         }
671 }
672
673 function bluesky_get_contact(stdClass $author, int $uid): array
674 {
675         $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
676
677         $fields = [
678                 'name' => $author->displayName,
679                 'nick' => $author->handle,
680                 'addr' => $author->handle,
681         ];
682
683         $contact = Contact::selectFirst([], $condition);
684
685         if (empty($contact)) {
686                 $cid = bluesky_insert_contact($author, $uid);
687         } else {
688                 $cid = $contact['id'];
689                 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
690                         Contact::update($fields, ['id' => $cid]);
691                 }
692         }
693
694         $condition['uid'] = 0;
695
696         $contact = Contact::selectFirst([], $condition);
697         if (empty($contact)) {
698                 $pcid = bluesky_insert_contact($author, 0);
699         } else {
700                 $pcid = $contact['id'];
701                 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
702                         Contact::update($fields, ['id' => $pcid]);
703                 }
704         }
705
706         if (!empty($author->avatar)) {
707                 Contact::updateAvatar($cid, $author->avatar);
708         }
709
710         if (empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
711                 bluesky_update_contact($author, $uid, $cid, $pcid);
712         }
713
714         return Contact::getById($cid);
715 }
716
717 function bluesky_insert_contact(stdClass $author, int $uid)
718 {
719         $fields = [
720                 'uid'      => $uid,
721                 'network'  => Protocol::BLUESKY,
722                 'priority' => 1,
723                 'writable' => true,
724                 'blocked'  => false,
725                 'readonly' => false,
726                 'pending'  => false,
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,
733         ];
734         return Contact::insert($fields);
735 }
736
737 function bluesky_update_contact(stdClass $author, int $uid, int $cid, int $pcid)
738 {
739         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
740         if (empty($data)) {
741                 return;
742         }
743
744         $fields = [
745                 'name'    => $data->displayName,
746                 'nick'    => $data->handle,
747                 'addr'    => $data->handle,
748                 'about'   => HTML::toBBCode($data->description),
749                 'updated' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL),
750         ];
751
752         if (!empty($data->banner)) {
753                 $fields['header'] = $data->banner;
754         }
755
756         Contact::update($fields, ['id' => $cid]);
757         Contact::update($fields, ['id' => $pcid]);
758 }
759
760 function bluesky_get_did(int $uid): string
761 {
762         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
763         if (empty($data)) {
764                 return '';
765         }
766         Logger::debug('Got DID', ['return' => $data]);
767         return $data->did;
768 }
769
770 function bluesky_get_token(int $uid): string
771 {
772         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
773         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
774         if (empty($token)) {
775                 return '';
776         }
777
778         if ($created + 300 < time()) {
779                 return bluesky_refresh_token($uid);
780         }
781         return $token;
782 }
783
784 function bluesky_refresh_token(int $uid): string
785 {
786         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
787
788         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
789         if (empty($data)) {
790                 return '';
791         }
792
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;
798 }
799
800 function bluesky_create_token(int $uid, string $password): string
801 {
802         $did = DI::pConfig()->get($uid, 'bluesky', 'did');
803
804         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
805         if (empty($data)) {
806                 return '';
807         }
808
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;
814 }
815
816 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
817 {
818         try {
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]);
822                 return null;
823         }
824
825         if (!$curlResult->isSuccess()) {
826                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
827                 return null;
828         }
829
830         return json_decode($curlResult->getBody());
831 }
832
833 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
834 {
835         try {
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]);
839                 return null;
840         }
841
842         if (!$curlResult->isSuccess()) {
843                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
844                 return null;
845         }
846
847         return json_decode($curlResult->getBody());
848 }