]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
Merge pull request 'Bluesky: Pinned feeds can now be imported' (#1396) from heluecht...
[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  * - Outgoing mentions
10  *
11  * Possibly not possible:
12  * - only fetch new posts
13  *
14  * Currently not possible, due to limitations in Friendica
15  * - mute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphmuteactor
16  * - unmute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphunmuteactor
17  *
18  * Possibly interesting:
19  * - https://atproto.com/lexicons/com-atproto-label#comatprotolabelsubscribelabels
20  * - https://atproto.com/lexicons/com-atproto-moderation#comatprotomoderationcreatereport
21  * - https://atproto.com/lexicons/com-atproto-repo#comatprotorepoputrecord
22  * - https://atproto.com/lexicons/app-bsky-embed#appbskyembedrecordwithmedia
23  * - https://atproto.com/lexicons/app-bsky-feed#appbskyfeedgetpostthread
24  */
25
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;
37 use Friendica\DI;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Photo;
42 use Friendica\Model\Post;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Relay;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Strings;
49
50 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
51 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
52
53 function bluesky_install()
54 {
55         Hook::register('load_config',             __FILE__, 'bluesky_load_config');
56         Hook::register('hook_fork',               __FILE__, 'bluesky_hook_fork');
57         Hook::register('post_local',              __FILE__, 'bluesky_post_local');
58         Hook::register('notifier_normal',         __FILE__, 'bluesky_send');
59         Hook::register('jot_networks',            __FILE__, 'bluesky_jot_nets');
60         Hook::register('connector_settings',      __FILE__, 'bluesky_settings');
61         Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
62         Hook::register('cron',                    __FILE__, 'bluesky_cron');
63         Hook::register('support_follow',          __FILE__, 'bluesky_support_follow');
64         Hook::register('support_probe',           __FILE__, 'bluesky_support_probe');
65         Hook::register('follow',                  __FILE__, 'bluesky_follow');
66         Hook::register('unfollow',                __FILE__, 'bluesky_unfollow');
67         Hook::register('block',                   __FILE__, 'bluesky_block');
68         Hook::register('unblock',                 __FILE__, 'bluesky_unblock');
69         Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
70         Hook::register('probe_detect',            __FILE__, 'bluesky_probe_detect');
71         Hook::register('item_by_link',            __FILE__, 'bluesky_item_by_link');
72 }
73
74 function bluesky_load_config(ConfigFileManager $loader)
75 {
76         DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
77 }
78
79 function bluesky_check_item_notification(array &$notification_data)
80 {
81         $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
82
83         if (!empty($did)) {
84                 $notification_data['profiles'][] = $did;
85         }
86 }
87
88 function bluesky_probe_detect(array &$hookData)
89 {
90         // Don't overwrite an existing result
91         if (isset($hookData['result'])) {
92                 return;
93         }
94
95         // Avoid a lookup for the wrong network
96         if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
97                 return;
98         }
99
100         $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
101         if (empty($pconfig['uid'])) {
102                 return;
103         }
104
105         if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
106                 $did = $hookData['uri'];
107         } elseif (preg_match('#^' . BLUESKY_HOST . '/profile/(.+)#', $hookData['uri'], $matches)) {
108                 $did = bluesky_get_did($pconfig['uid'], $matches[1]);
109                 if (empty($did)) {
110                         return;
111                 }
112         } else {
113                 return;
114         }
115
116         $token = bluesky_get_token($pconfig['uid']);
117         if (empty($token)) {
118                 return;
119         }
120
121         $data = bluesky_get($pconfig['uid'], '/xrpc/app.bsky.actor.getProfile?actor=' . $did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $token]]]);
122         if (empty($data)) {
123                 return;
124         }
125
126         $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
127
128         // Preparing probe data. This differs slightly from the contact array
129         $hookData['result']['about']    = HTML::toBBCode($data->description ?? '');
130         $hookData['result']['photo']    = $data->avatar ?? '';
131         $hookData['result']['header']   = $data->banner ?? '';
132         $hookData['result']['batch']    = '';
133         $hookData['result']['notify']   = '';
134         $hookData['result']['poll']     = '';
135         $hookData['result']['poco']     = '';
136         $hookData['result']['pubkey']   = '';
137         $hookData['result']['priority'] = 0;
138         $hookData['result']['guid']     = '';
139 }
140
141 function bluesky_item_by_link(array &$hookData)
142 {
143         // Don't overwrite an existing result
144         if (isset($hookData['item_id'])) {
145                 return;
146         }
147
148         $token = bluesky_get_token($hookData['uid']);
149         if (empty($token)) {
150                 return;
151         }
152
153         if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
154                 return;
155         }
156
157         $did = bluesky_get_did($hookData['uid'], $matches[1]);
158         if (empty($did)) {
159                 return;
160         }
161
162         Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
163
164         $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
165
166         $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0);
167         Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
168         if (!empty($uri)) {
169                 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
170                 if (!empty($item['id'])) {
171                         $hookData['item_id'] = $item['id'];
172                 }
173         }
174 }
175
176 function bluesky_support_follow(array &$data)
177 {
178         if ($data['protocol'] == Protocol::BLUESKY) {
179                 $data['result'] = true;
180         }
181 }
182
183 function bluesky_support_probe(array &$data)
184 {
185         if ($data['protocol'] == Protocol::BLUESKY) {
186                 $data['result'] = true;
187         }
188 }
189
190 function bluesky_follow(array &$hook_data)
191 {
192         $token = bluesky_get_token($hook_data['uid']);
193         if (empty($token)) {
194                 return;
195         }
196
197         Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
198         $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
199         if (empty($contact)) {
200                 return;
201         }
202
203         $record = [
204                 'subject'   => $contact['url'],
205                 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
206                 '$type'     => 'app.bsky.graph.follow'
207         ];
208
209         $post = [
210                 'collection' => 'app.bsky.graph.follow',
211                 'repo'       => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
212                 'record'     => $record
213         ];
214
215         $activity = bluesky_post($hook_data['uid'], '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
216         if (!empty($activity->uri)) {
217                 $hook_data['contact'] = $contact;
218                 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
219         }
220 }
221
222 function bluesky_unfollow(array &$hook_data)
223 {
224         $token = bluesky_get_token($hook_data['uid']);
225         if (empty($token)) {
226                 return;
227         }
228
229         if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
230                 return;
231         }
232
233         $data = bluesky_get($hook_data['uid'], '/xrpc/app.bsky.actor.getProfile?actor=' . $hook_data['contact']['url'], HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $token]]]);
234         if (empty($data->viewer) || empty($data->viewer->following)) {
235                 return;
236         }
237
238         bluesky_delete_post($data->viewer->following, $hook_data['uid']);
239
240         $hook_data['result'] = true;
241 }
242
243 function bluesky_block(array &$hook_data)
244 {
245         $token = bluesky_get_token($hook_data['uid']);
246         if (empty($token)) {
247                 return;
248         }
249
250         Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
251         $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
252         if (empty($contact)) {
253                 return;
254         }
255
256         $record = [
257                 'subject'   => $contact['url'],
258                 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
259                 '$type'     => 'app.bsky.graph.block'
260         ];
261
262         $post = [
263                 'collection' => 'app.bsky.graph.block',
264                 'repo'       => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
265                 'record'     => $record
266         ];
267
268         $activity = bluesky_post($hook_data['uid'], '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
269         if (!empty($activity->uri)) {
270                 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
271                 if (!empty($cdata['user'])) {
272                         Contact::remove($cdata['user']);
273                 }
274                 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
275         }
276 }
277
278 function bluesky_unblock(array &$hook_data)
279 {
280         $token = bluesky_get_token($hook_data['uid']);
281         if (empty($token)) {
282                 return;
283         }
284
285         if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
286                 return;
287         }
288
289         $data = bluesky_get($hook_data['uid'], '/xrpc/app.bsky.actor.getProfile?actor=' . $hook_data['contact']['url'], HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $token]]]);
290         if (empty($data->viewer) || empty($data->viewer->blocking)) {
291                 return;
292         }
293
294         bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
295
296         $hook_data['result'] = true;
297 }
298
299 function bluesky_settings(array &$data)
300 {
301         if (!DI::userSession()->getLocalUserId()) {
302                 return;
303         }
304
305         $enabled      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
306         $def_enabled  = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
307         $host         = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
308         $handle       = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
309         $did          = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
310         $token        = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
311         $import       = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
312         $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
313
314         $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.');
315
316         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
317         $html = Renderer::replaceMacros($t, [
318                 '$enable'       => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
319                 '$bydefault'    => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
320                 '$import'       => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
321                 '$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.')],
322                 '$host'         => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
323                 '$handle'       => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
324                 '$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'],
325                 '$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.")],
326                 '$status'       => $status
327         ]);
328
329         $data = [
330                 'connector' => 'bluesky',
331                 'title'     => DI::l10n()->t('Bluesky Import/Export'),
332                 'image'     => 'images/bluesky.jpg',
333                 'enabled'   => $enabled,
334                 'html'      => $html,
335         ];
336 }
337
338 function bluesky_settings_post(array &$b)
339 {
340         if (empty($_POST['bluesky-submit'])) {
341                 return;
342         }
343
344         $old_host   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
345         $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
346         $old_did    = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
347
348         $host   = $_POST['bluesky_host'];
349         $handle = $_POST['bluesky_handle'];
350
351         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post',            intval($_POST['bluesky']));
352         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
353         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host',            $host);
354         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle',          $handle);
355         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import',          intval($_POST['bluesky_import']));
356         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds',    intval($_POST['bluesky_import_feeds']));
357
358         if (!empty($host) && !empty($handle)) {
359                 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
360                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
361                 }
362         } else {
363                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
364         }
365
366         if (!empty($_POST['bluesky_password'])) {
367                 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
368         }
369 }
370
371 function bluesky_jot_nets(array &$jotnets_fields)
372 {
373         if (!DI::userSession()->getLocalUserId()) {
374                 return;
375         }
376
377         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
378                 $jotnets_fields[] = [
379                         'type'  => 'checkbox',
380                         'field' => [
381                                 'bluesky_enable',
382                                 DI::l10n()->t('Post to Bluesky'),
383                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
384                         ]
385                 ];
386         }
387 }
388
389 function bluesky_cron()
390 {
391         $last = DI::keyValue()->get('bluesky_last_poll');
392
393         $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
394         if (!$poll_interval) {
395                 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
396         }
397
398         if ($last) {
399                 $next = $last + ($poll_interval * 60);
400                 if ($next > time()) {
401                         Logger::notice('poll interval not reached');
402                         return;
403                 }
404         }
405         Logger::notice('cron_start');
406
407         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
408         if ($abandon_days < 1) {
409                 $abandon_days = 0;
410         }
411
412         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
413
414         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
415         foreach ($pconfigs as $pconfig) {
416                 if ($abandon_days != 0) {
417                         if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
418                                 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
419                                 continue;
420                         }
421                 }
422
423                 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
424                 bluesky_fetch_timeline($pconfig['uid']);
425                 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
426
427                 Logger::notice('importing notifications - start', ['user' => $pconfig['uid']]);
428                 bluesky_fetch_notifications($pconfig['uid']);
429                 Logger::notice('importing notifications - done', ['user' => $pconfig['uid']]);
430
431                 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
432                         Logger::notice('importing feeds - start', ['user' => $pconfig['uid']]);
433                         $feeds = bluesky_get_feeds($pconfig['uid']);
434                         foreach ($feeds as $feed) {
435                                 Logger::debug('Importing feed', ['user' => $pconfig['uid'], 'feed' => $feed]);
436                                 bluesky_fetch_feed($pconfig['uid'], $feed);
437                         }
438                         Logger::notice('importing feeds - done', ['user' => $pconfig['uid']]);
439                 }
440         }
441
442         $last_clean = DI::keyValue()->get('bluesky_last_clean');
443         if (empty($last_clean) || ($last_clean + 86400 < time())) {
444                 Logger::notice('Start contact cleanup');
445                 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
446                 while ($contact = DBA::fetch($contacts)) {
447                         Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
448                 }
449                 DBA::close($contacts);
450                 DI::keyValue()->set('bluesky_last_clean', time());
451                 Logger::notice('Contact cleanup done');
452         }
453
454         Logger::notice('cron_end');
455
456         DI::keyValue()->set('bluesky_last_poll', time());
457 }
458
459 function bluesky_hook_fork(array &$b)
460 {
461         if ($b['name'] != 'notifier_normal') {
462                 return;
463         }
464
465         $post = $b['data'];
466
467         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
468                 DI::logger()->info('Editing is not supported by the addon');
469                 $b['execute'] = false;
470                 return;
471         }
472
473         if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
474                 // Don't post if it isn't a reply to a bluesky post
475                 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
476                         Logger::notice('No bluesky parent found', ['item' => $post['id']]);
477                         $b['execute'] = false;
478                         return;
479                 }
480         } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
481                 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
482                 $b['execute'] = false;
483                 return;
484         }
485 }
486
487 function bluesky_post_local(array &$b)
488 {
489         if ($b['edit']) {
490                 return;
491         }
492
493         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
494                 return;
495         }
496
497         if ($b['private'] || $b['parent']) {
498                 return;
499         }
500
501         $bluesky_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
502         $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
503
504         // if API is used, default to the chosen settings
505         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
506                 $bluesky_enable = 1;
507         }
508
509         if (!$bluesky_enable) {
510                 return;
511         }
512
513         if (strlen($b['postopts'])) {
514                 $b['postopts'] .= ',';
515         }
516
517         $b['postopts'] .= 'bluesky';
518 }
519
520 function bluesky_send(array &$b)
521 {
522         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
523                 return;
524         }
525
526         if ($b['gravity'] != Item::GRAVITY_PARENT) {
527                 Logger::debug('Got comment', ['item' => $b]);
528
529                 if ($b['deleted']) {
530                         $uri = bluesky_get_uri_class($b['uri']);
531                         if (empty($uri)) {
532                                 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
533                                 return;
534                         }
535                         bluesky_delete_post($b['uri'], $b['uid']);
536                         return;
537                 }
538
539                 $root   = bluesky_get_uri_class($b['parent-uri']);
540                 $parent = bluesky_get_uri_class($b['thr-parent']);
541
542                 if (empty($root) || empty($parent)) {
543                         Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
544                         return;
545                 }
546
547                 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
548                         Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
549                         bluesky_create_post($b, $root, $parent);
550                         return;
551                 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
552                         bluesky_create_activity($b, $parent);
553                 }
554                 return;
555         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
556                 return;
557         }
558
559         bluesky_create_post($b);
560 }
561
562 function bluesky_create_activity(array $item, stdClass $parent = null)
563 {
564         $uid = $item['uid'];
565         $token = bluesky_get_token($uid);
566         if (empty($token)) {
567                 return;
568         }
569
570         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
571
572         if ($item['verb'] == Activity::LIKE) {
573                 $record = [
574                         'subject'   => $parent,
575                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
576                         '$type'     => 'app.bsky.feed.like'
577                 ];
578
579                 $post = [
580                         'collection' => 'app.bsky.feed.like',
581                         'repo'       => $did,
582                         'record'     => $record
583                 ];
584         } elseif ($item['verb'] == Activity::ANNOUNCE) {
585                 $record = [
586                         'subject'   => $parent,
587                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
588                         '$type'     => 'app.bsky.feed.repost'
589                 ];
590
591                 $post = [
592                         'collection' => 'app.bsky.feed.repost',
593                         'repo'       => $did,
594                         'record'     => $record
595                 ];
596         }
597
598         $activity = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
599         if (empty($activity)) {
600                 return;
601         }
602         Logger::debug('Activity done', ['return' => $activity]);
603         $uri = bluesky_get_uri($activity);
604         Item::update(['extid' => $uri], ['id' => $item['id']]);
605         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
606 }
607
608 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
609 {
610         $uid = $item['uid'];
611         $token = bluesky_get_token($uid);
612         if (empty($token)) {
613                 return;
614         }
615
616         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
617         $urls = bluesky_get_urls($item['body']);
618
619         $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
620         foreach ($msg['parts'] as $key => $part) {
621
622                 $facets = bluesky_get_facets($part, $urls);
623
624                 $record = [
625                         'text'      => $facets['body'],
626                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
627                         '$type'     => 'app.bsky.feed.post'
628                 ];
629
630                 if (!empty($facets['facets'])) {
631                         $record['facets'] = $facets['facets'];
632                 }
633
634                 if (!empty($root)) {
635                         $record['reply'] = ['root' => $root, 'parent' => $parent];
636                 }
637
638                 if ($key == count($msg['parts']) - 1) {
639                         $record = bluesky_add_embed($uid, $msg, $record);
640                 }
641
642                 $post = [
643                         'collection' => 'app.bsky.feed.post',
644                         'repo'       => $did,
645                         'record'     => $record
646                 ];
647
648                 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
649                 if (empty($parent)) {
650                         return;
651                 }
652                 Logger::debug('Posting done', ['return' => $parent]);
653                 if (empty($root)) {
654                         $root = $parent;
655                 }
656                 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
657                         $uri = bluesky_get_uri($parent);
658                         Item::update(['extid' => $uri], ['id' => $item['id']]);
659                         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
660                 }
661         }
662 }
663
664 function bluesky_get_urls(string $body): array
665 {
666         // Remove all hashtags and mentions
667         $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
668
669         $urls = [];
670
671         // Search for pure links
672         if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
673                 foreach ($matches[1] as $url) {
674                         $urls[] = $url;
675                 }
676         }
677
678         // Search for links with descriptions
679         if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
680                 foreach ($matches[1] as $url) {
681                         $urls[] = $url;
682                 }
683         }
684         return $urls;
685 }
686
687 function bluesky_get_facets(string $body, array $urls): array
688 {
689         $facets = [];
690
691         foreach ($urls as $url) {
692                 $pos = strpos($body, $url);
693                 if ($pos === false) {
694                         continue;
695                 }
696                 if ($pos > 0) {
697                         $prefix = substr($body, 0, $pos);
698                 } else {
699                         $prefix = '';
700                 }
701                 $linktext = Strings::getStyledURL($url);
702                 $body = $prefix . $linktext . substr($body, $pos + strlen($url));
703
704                 $facet = new stdClass;
705                 $facet->index = new stdClass;
706                 $facet->index->byteEnd   = $pos + strlen($linktext);
707                 $facet->index->byteStart = $pos;
708
709                 $feature = new stdClass;
710                 $feature->uri = $url;
711                 $type = '$type';
712                 $feature->$type = 'app.bsky.richtext.facet#link';
713
714                 $facet->features = [$feature];
715                 $facets[] = $facet;
716         }
717
718         return ['facets' => $facets, 'body' => $body];
719 }
720
721 function bluesky_add_embed(int $uid, array $msg, array $record): array
722 {
723         if (($msg['type'] != 'link') && !empty($msg['images'])) {
724                 $images = [];
725                 foreach ($msg['images'] as $image) {
726                         $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
727                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
728                         $blob = bluesky_upload_blob($uid, $photo);
729                         if (!empty($blob) && count($images) < 4) {
730                                 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
731                         }
732                 }
733                 if (!empty($images)) {
734                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
735                 }
736         } elseif ($msg['type'] == 'link') {
737                 $record['embed'] = [
738                         '$type'    => 'app.bsky.embed.external',
739                         'external' => [
740                                 'uri'         => $msg['url'],
741                                 'title'       => $msg['title'],
742                                 'description' => $msg['description'],
743                         ]
744                 ];
745                 if (!empty($msg['image'])) {
746                         $photo = Photo::createPhotoForExternalResource($msg['image']);
747                         $blob = bluesky_upload_blob($uid, $photo);
748                         if (!empty($blob)) {
749                                 $record['embed']['external']['thumb'] = $blob;
750                         }
751                 }
752         }
753         return $record;
754 }
755
756 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
757 {
758         $content = Photo::getImageForPhoto($photo);
759         $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
760         if (empty($data)) {
761                 return null;
762         }
763
764         Logger::debug('Uploaded blob', ['return' => $data]);
765         return $data->blob;
766 }
767
768 function bluesky_delete_post(string $uri, int $uid)
769 {
770         $token = bluesky_get_token($uid);
771         $parts = bluesky_get_uri_parts($uri);
772         if (empty($parts)) {
773                 Logger::debug('No uri delected', ['uri' => $uri]);
774                 return;
775         }
776         bluesky_post($uid, '/xrpc/com.atproto.repo.deleteRecord', json_encode($parts), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
777         Logger::debug('Deleted', ['parts' => $parts]);
778 }
779
780 function bluesky_fetch_timeline(int $uid)
781 {
782         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
783         if (empty($data)) {
784                 return;
785         }
786
787         if (empty($data->feed)) {
788                 return;
789         }
790
791         foreach (array_reverse($data->feed) as $entry) {
792                 bluesky_process_post($entry->post, $uid, Item::PR_NONE);
793                 if (!empty($entry->reason)) {
794                         bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
795                 }
796         }
797
798         // @todo Support paging
799         // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
800 }
801
802 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
803 {
804         $type = '$type';
805         if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
806                 return;
807         }
808
809         $contact = bluesky_get_contact($reason->by, $uid, $uid);
810
811         $item = [
812                 'network'       => Protocol::BLUESKY,
813                 'uid'           => $uid,
814                 'wall'          => false,
815                 'uri'           => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
816                 'private'       => Item::UNLISTED,
817                 'verb'          => Activity::POST,
818                 'contact-id'    => $contact['id'],
819                 'author-name'   => $contact['name'],
820                 'author-link'   => $contact['url'],
821                 'author-avatar' => $contact['avatar'],
822                 'verb'          => Activity::ANNOUNCE,
823                 'body'          => Activity::ANNOUNCE,
824                 'gravity'       => Item::GRAVITY_ACTIVITY,
825                 'object-type'   => Activity\ObjectType::NOTE,
826                 'thr-parent'    => $uri,
827         ];
828
829         if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
830                 return;
831         }
832
833         $item['owner-name']   = $item['author-name'];
834         $item['owner-link']   = $item['author-link'];
835         $item['owner-avatar'] = $item['author-avatar'];
836         if (Item::insert($item)) {
837                 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
838                 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
839         }
840 }
841
842 function bluesky_fetch_notifications(int $uid)
843 {
844         $result = bluesky_get($uid, '/xrpc/app.bsky.notification.listNotifications', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
845         if (empty($result->notifications)) {
846                 return;
847         }
848         foreach ($result->notifications as $notification) {
849                 $uri = bluesky_get_uri($notification);
850                 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
851                         Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
852                         continue;
853                 }
854                 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
855                 switch ($notification->reason) {
856                         case 'like':
857                                 $item = bluesky_get_header($notification, $uri, $uid, $uid);
858                                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
859                                 $item['body'] = $item['verb'] = Activity::LIKE;
860                                 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
861                                 $result = Item::insert($item);
862                                 Logger::debug('Got like', ['uid' => $uid, 'result' => $result]);
863                                 break;
864
865                         case 'repost':
866                                 $item = bluesky_get_header($notification, $uri, $uid, $uid);
867                                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
868                                 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
869                                 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
870                                 $result = Item::insert($item);
871                                 Logger::debug('Got repost', ['uid' => $uid, 'result' => $result]);
872                                 break;
873
874                         case 'follow':
875                                 $contact = bluesky_get_contact($notification->author, $uid, $uid);
876                                 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick']]);
877                                 break;
878
879                         case 'mention':
880                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED);
881                                 Logger::debug('Got mention', ['uid' => $uid, 'result' => $result]);
882                                 break;
883
884                         case 'reply':
885                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED);
886                                 Logger::debug('Got reply', ['uid' => $uid, 'result' => $result]);
887                                 break;
888
889                         case 'quote':
890                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED);
891                                 Logger::debug('Got quote', ['uid' => $uid, 'result' => $result]);
892                                 break;
893
894                         default:
895                                 Logger::notice('Unhandled reason', ['reason' => $notification->reason]);
896                                 break;
897                 }
898         }
899 }
900
901 function bluesky_fetch_feed(int $uid, string $feed)
902 {
903         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getFeed?feed=' . $feed, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
904         if (empty($data)) {
905                 return;
906         }
907
908         if (empty($data->feed)) {
909                 return;
910         }
911
912         foreach (array_reverse($data->feed) as $entry) {
913                 if (!Relay::isWantedLanguage($entry->post->record->text)) {
914                         Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
915                         continue;
916                 }
917                 bluesky_process_post($entry->post, $uid, Item::PR_TAG);
918                 if (!empty($entry->reason)) {
919                         bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
920                 }
921         }
922 }
923
924 function bluesky_process_post(stdClass $post, int $uid, int $post_reason): int
925 {
926         $uri = bluesky_get_uri($post);
927
928         if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
929                 return 0;
930         }
931
932         Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid]);
933
934         $item = bluesky_get_header($post, $uri, $uid, $uid);
935
936         $item = bluesky_get_content($item, $post->record, $uid);
937
938         if (!empty($post->embed)) {
939                 $item = bluesky_add_media($post->embed, $item, $uid);
940         }
941
942         if (empty($item['post-reason'])) {
943                 $item['post-reason'] = $post_reason;
944         }
945
946         return item::insert($item);
947 }
948
949 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
950 {
951         $parts = bluesky_get_uri_parts($uri);
952         if (empty($post->author)) {
953                 return [];
954         }
955         $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
956         $item = [
957                 'network'       => Protocol::BLUESKY,
958                 'uid'           => $uid,
959                 'wall'          => false,
960                 'uri'           => $uri,
961                 'guid'          => $post->cid,
962                 'private'       => Item::UNLISTED,
963                 'verb'          => Activity::POST,
964                 'contact-id'    => $contact['id'],
965                 'author-name'   => $contact['name'],
966                 'author-link'   => $contact['url'],
967                 'author-avatar' => $contact['avatar'],
968                 'plink'         => $contact['alias'] . '/post/' . $parts->rkey,
969         ];
970
971         $item['uri-id']       = ItemURI::getIdByURI($uri);
972         $item['owner-name']   = $item['author-name'];
973         $item['owner-link']   = $item['author-link'];
974         $item['owner-avatar'] = $item['author-avatar'];
975
976         if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
977                 $item['post-reason'] = Item::PR_FOLLOWER;
978         }
979
980         return $item;
981 }
982
983 function bluesky_get_content(array $item, stdClass $record, int $uid): array
984 {
985         if (!empty($record->reply)) {
986                 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
987                 $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id']);
988                 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
989                 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id']);
990         }
991
992         $item['body']    = bluesky_get_text($record, $uid);
993         $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
994         return $item;
995 }
996
997 function bluesky_get_text(stdClass $record, int $uid): string
998 {
999         $text = $record->text;
1000
1001         if (empty($record->facets)) {
1002                 return $text;
1003         }
1004
1005         $facets = [];
1006         foreach ($record->facets as $facet) {
1007                 $facets[$facet->index->byteStart] = $facet;
1008         }
1009         krsort($facets);
1010
1011         foreach ($facets as $facet) {
1012                 $prefix   = substr($text, 0, $facet->index->byteStart);
1013                 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1014                 $suffix   = substr($text, $facet->index->byteEnd);
1015
1016                 $url  = '';
1017                 $type = '$type';
1018                 foreach ($facet->features as $feature) {
1019
1020                         switch ($feature->$type) {
1021                                 case 'app.bsky.richtext.facet#link':
1022                                         $url = $feature->uri;
1023                                         break;
1024
1025                                 case 'app.bsky.richtext.facet#mention':
1026                                         $contact = Contact::selectFirst(['id'], ['nurl' => $feature->did, 'uid' => [0, $uid]]);
1027                                         if (!empty($contact['id'])) {
1028                                                 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1029                                                 if (substr($linktext, 0, 1) == '@') {
1030                                                         $prefix .= '@';
1031                                                         $linktext = substr($linktext, 1);
1032                                                 }
1033                                         }
1034                                         break;
1035
1036                                 default:
1037                                         Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1038                                         break;
1039                         }
1040                 }
1041                 if (!empty($url)) {
1042                         $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1043                 }
1044         }
1045         return $text;
1046 }
1047
1048 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid): array
1049 {
1050         $type = '$type';
1051         switch ($embed->$type) {
1052                 case 'app.bsky.embed.images#view':
1053                         foreach ($embed->images as $image) {
1054                                 $media = [
1055                                         'uri-id'      => $item['uri-id'],
1056                                         'type'        => Post\Media::IMAGE,
1057                                         'url'         => $image->fullsize,
1058                                         'preview'     => $image->thumb,
1059                                         'description' => $image->alt,
1060                                 ];
1061                                 Post\Media::insert($media);
1062                         }
1063                         break;
1064
1065                 case 'app.bsky.embed.external#view':
1066                         $media = [
1067                                 'uri-id' => $item['uri-id'],
1068                                 'type'        => Post\Media::HTML,
1069                                 'url'         => $embed->external->uri,
1070                                 'name'        => $embed->external->title,
1071                                 'description' => $embed->external->description,
1072                         ];
1073                         Post\Media::insert($media);
1074                         break;
1075
1076                 case 'app.bsky.embed.record#view':
1077                         $uri = bluesky_get_uri($embed->record);
1078                         $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1079                         if (empty($shared)) {
1080                                 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1081                                 if (!empty($shared)) {
1082                                         $shared = bluesky_get_content($shared, $embed->record->value, $item['uid']);
1083
1084                                         if (!empty($embed->record->embeds)) {
1085                                                 foreach ($embed->record->embeds as $single) {
1086                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid);
1087                                                 }
1088                                         }
1089                                         $id = Item::insert($shared);
1090                                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1091                                 }
1092                         }
1093                         if (!empty($shared)) {
1094                                 $item['quote-uri-id'] = $shared['uri-id'];
1095                         }
1096                         break;
1097
1098                 case 'app.bsky.embed.recordWithMedia#view':
1099                         $uri = bluesky_get_uri($embed->record->record);
1100                         $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1101                         if (empty($shared)) {
1102                                 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1103                                 if (!empty($shared)) {
1104                                         $shared = bluesky_get_content($shared, $embed->record->record->value, $item['uid']);
1105
1106                                         if (!empty($embed->record->embeds)) {
1107                                                 foreach ($embed->record->record->embeds as $single) {
1108                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid);
1109                                                 }
1110                                         }
1111
1112                                         if (!empty($embed->media)) {
1113                                                 bluesky_add_media($embed->media, $item, $fetch_uid);
1114                                         }
1115
1116                                         $id = Item::insert($shared);
1117                                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1118                                 }
1119                         }
1120                         if (!empty($shared)) {
1121                                 $item['quote-uri-id'] = $shared['uri-id'];
1122                         }
1123                         break;
1124
1125                 default:
1126                         Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1127                         break;
1128         }
1129         return $item;
1130 }
1131
1132 function bluesky_get_uri(stdClass $post): string
1133 {
1134         return $post->uri . ':' . $post->cid;
1135 }
1136
1137 function bluesky_get_uri_class(string $uri): ?stdClass
1138 {
1139         if (empty($uri)) {
1140                 return null;
1141         }
1142
1143         $elements = explode(':', $uri);
1144         if (empty($elements) || ($elements[0] != 'at')) {
1145                 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1146                 return bluesky_get_uri_class($post['extid'] ?? '');
1147         }
1148
1149         $class = new stdClass;
1150
1151         $class->cid = array_pop($elements);
1152         $class->uri = implode(':', $elements);
1153
1154         if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1155                 $class->uri .= ':' . $class->cid;
1156                 $class->cid = '';
1157         }
1158
1159         return $class;
1160 }
1161
1162 function bluesky_get_uri_parts(string $uri): ?stdClass
1163 {
1164         $class = bluesky_get_uri_class($uri);
1165         if (empty($class)) {
1166                 return null;
1167         }
1168
1169         $parts = explode('/', substr($class->uri, 5));
1170
1171         $class = new stdClass;
1172
1173         $class->repo       = $parts[0];
1174         $class->collection = $parts[1];
1175         $class->rkey       = $parts[2];
1176
1177         return $class;
1178 }
1179
1180 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer): string
1181 {
1182         if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1183                 Logger::debug('Post exists', ['uri' => $uri]);
1184                 return $uri;
1185         }
1186
1187         $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1188         if (!empty($reply['uri'])) {
1189                 return $reply['uri'];
1190         }
1191
1192         Logger::debug('Fetch missing post', ['uri' => $uri]);
1193         $class = bluesky_get_uri_class($uri);
1194         $fetch_uri = $class->uri;
1195
1196         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getPosts?uris=' . urlencode($fetch_uri), HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1197         if (empty($data)) {
1198                 return '';
1199         }
1200
1201         if ($causer != 0) {
1202                 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1203         }
1204
1205         foreach ($data->posts as $post) {
1206                 $uri = bluesky_get_uri($post);
1207                 $item = bluesky_get_header($post, $uri, $uid, $uid);
1208                 $item = bluesky_get_content($item, $post->record, $uid);
1209
1210                 $item['post-reason'] = Item::PR_FETCHED;
1211
1212                 if (!empty($cdata['public'])) {
1213                         $item['causer-id']   = $cdata['public'];
1214                 }
1215
1216                 if (!empty($post->embed)) {
1217                         $item = bluesky_add_media($post->embed, $item, $uid);
1218                 }
1219                 $id = Item::insert($item);
1220                 Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1221         }
1222
1223         return $uri;
1224 }
1225
1226 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1227 {
1228         $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1229         $contact = Contact::selectFirst(['id', 'updated'], $condition);
1230
1231         $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1232
1233         $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1234
1235         $public_fields['uid'] = 0;
1236         $public_fields['rel'] = Contact::NOTHING;
1237
1238         if (empty($contact)) {
1239                 $cid = Contact::insert($public_fields);
1240         } else {
1241                 $cid = $contact['id'];
1242                 Contact::update($public_fields, ['id' => $cid], true);
1243         }
1244
1245         if ($uid != 0) {
1246                 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1247
1248                 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1249                 if (!isset($fields['rel']) && isset($contact['rel'])) {
1250                         $fields['rel'] = $contact['rel'];
1251                 } elseif (!isset($fields['rel'])) {
1252                         $fields['rel'] = Contact::NOTHING;
1253                 }
1254         }
1255
1256         if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1257                 if (empty($contact)) {
1258                         $cid = Contact::insert($fields);
1259                 } else {
1260                         $cid = $contact['id'];
1261                         Contact::update($fields, ['id' => $cid], true);
1262                 }
1263                 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1264         } else {
1265                 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1266         }
1267         if (!empty($author->avatar)) {
1268                 Contact::updateAvatar($cid, $author->avatar);
1269         }
1270
1271         return Contact::getById($cid);
1272 }
1273
1274 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1275 {
1276         $fields = [
1277                 'uid'      => $uid,
1278                 'network'  => Protocol::BLUESKY,
1279                 'priority' => 1,
1280                 'writable' => true,
1281                 'blocked'  => false,
1282                 'readonly' => false,
1283                 'pending'  => false,
1284                 'baseurl'  => BLUESKY_HOST,
1285                 'url'      => $author->did,
1286                 'nurl'     => $author->did,
1287                 'alias'    => BLUESKY_HOST . '/profile/' . $author->handle,
1288                 'name'     => $author->displayName ?? $author->handle,
1289                 'nick'     => $author->handle,
1290                 'addr'     => $author->handle,
1291         ];
1292
1293         if (!$update) {
1294                 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1295                 return $fields;
1296         }
1297
1298         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1299         if (empty($data)) {
1300                 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1301                 return $fields;
1302         }
1303
1304         $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1305
1306         if (!empty($data->description)) {
1307                 $fields['about'] = HTML::toBBCode($data->description);
1308         }
1309
1310         if (!empty($data->banner)) {
1311                 $fields['header'] = $data->banner;
1312         }
1313
1314         if (!empty($data->viewer)) {
1315                 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1316                         $fields['rel'] = Contact::FRIEND;
1317                 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1318                         $fields['rel'] = Contact::SHARING;
1319                 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1320                         $fields['rel'] = Contact::FOLLOWER;
1321                 } else {
1322                         $fields['rel'] = Contact::NOTHING;
1323                 }
1324         }
1325
1326         Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1327         return $fields;
1328 }
1329
1330 function bluesky_get_feeds(int $uid): array
1331 {
1332         $type = '$type';
1333         $preferences = bluesky_get_preferences($uid);
1334         foreach ($preferences->preferences as $preference) {
1335                 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1336                         return $preference->pinned ?? [];
1337                 }
1338         }
1339         return [];
1340 }
1341
1342 function bluesky_get_preferences(int $uid): stdClass
1343 {
1344         $cachekey = 'bluesky:preferences:' . $uid;
1345         $data = DI::cache()->get($cachekey);
1346         if (!is_null($data)) {
1347                 return $data;
1348         }
1349
1350         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getPreferences', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1351
1352         DI::cache()->set($cachekey, $data, Duration::HOUR);
1353         return $data;
1354 }
1355
1356 function bluesky_get_did(int $uid, string $handle): string
1357 {
1358         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . $handle);
1359         if (empty($data)) {
1360                 return '';
1361         }
1362         Logger::debug('Got DID', ['return' => $data]);
1363         return $data->did;
1364 }
1365
1366 function bluesky_get_token(int $uid): string
1367 {
1368         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1369         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1370         if (empty($token)) {
1371                 return '';
1372         }
1373
1374         if ($created + 300 < time()) {
1375                 return bluesky_refresh_token($uid);
1376         }
1377         return $token;
1378 }
1379
1380 function bluesky_refresh_token(int $uid): string
1381 {
1382         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1383
1384         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1385         if (empty($data)) {
1386                 return '';
1387         }
1388
1389         Logger::debug('Refreshed token', ['return' => $data]);
1390         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1391         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1392         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1393         return $data->accessJwt;
1394 }
1395
1396 function bluesky_create_token(int $uid, string $password): string
1397 {
1398         $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1399
1400         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1401         if (empty($data)) {
1402                 return '';
1403         }
1404
1405         Logger::debug('Created token', ['return' => $data]);
1406         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1407         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1408         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1409         return $data->accessJwt;
1410 }
1411
1412 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1413 {
1414         try {
1415                 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1416         } catch (\Exception $e) {
1417                 Logger::notice('Exception on post', ['exception' => $e]);
1418                 return null;
1419         }
1420
1421         if (!$curlResult->isSuccess()) {
1422                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1423                 return null;
1424         }
1425
1426         return json_decode($curlResult->getBody());
1427 }
1428
1429 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1430 {
1431         try {
1432                 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1433         } catch (\Exception $e) {
1434                 Logger::notice('Exception on get', ['exception' => $e]);
1435                 return null;
1436         }
1437
1438         if (!$curlResult->isSuccess()) {
1439                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1440                 return null;
1441         }
1442
1443         return json_decode($curlResult->getBody());
1444 }