]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
7499ce78a305136d83b5affc4b5ce3c5e49e205c
[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  * Currently technical issues in the core:
10  * - Outgoing mentions
11  *
12  * At some point in time:
13  * - Sending Quote shares https://atproto.com/lexicons/app-bsky-embed#appbskyembedrecord and https://atproto.com/lexicons/app-bsky-embed#appbskyembedrecordwithmedia
14 ยด*
15  * Possibly not possible:
16  * - only fetch new posts
17  *
18  * Currently not possible, due to limitations in Friendica
19  * - mute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphmuteactor
20  * - unmute contacts https://atproto.com/lexicons/app-bsky-graph#appbskygraphunmuteactor
21  *
22  * Possibly interesting:
23  * - https://atproto.com/lexicons/com-atproto-label#comatprotolabelsubscribelabels
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=' . urlencode($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, 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=' . urlencode($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=' . urlencode($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                 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
424                 bluesky_get_token($pconfig['uid']);
425
426                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
427                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
428
429                 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
430                         $feeds = bluesky_get_feeds($pconfig['uid']);
431                         foreach ($feeds as $feed) {
432                                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
433                         }
434                 }
435         }
436
437         $last_clean = DI::keyValue()->get('bluesky_last_clean');
438         if (empty($last_clean) || ($last_clean + 86400 < time())) {
439                 Logger::notice('Start contact cleanup');
440                 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
441                 while ($contact = DBA::fetch($contacts)) {
442                         Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
443                 }
444                 DBA::close($contacts);
445                 DI::keyValue()->set('bluesky_last_clean', time());
446                 Logger::notice('Contact cleanup done');
447         }
448
449         Logger::notice('cron_end');
450
451         DI::keyValue()->set('bluesky_last_poll', time());
452 }
453
454 function bluesky_hook_fork(array &$b)
455 {
456         if ($b['name'] != 'notifier_normal') {
457                 return;
458         }
459
460         $post = $b['data'];
461
462         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
463                 DI::logger()->info('Editing is not supported by the addon');
464                 $b['execute'] = false;
465                 return;
466         }
467
468         if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
469                 // Don't post if it isn't a reply to a bluesky post
470                 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
471                         Logger::notice('No bluesky parent found', ['item' => $post['id']]);
472                         $b['execute'] = false;
473                         return;
474                 }
475         } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
476                 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
477                 $b['execute'] = false;
478                 return;
479         }
480 }
481
482 function bluesky_post_local(array &$b)
483 {
484         if ($b['edit']) {
485                 return;
486         }
487
488         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
489                 return;
490         }
491
492         if ($b['private'] || $b['parent']) {
493                 return;
494         }
495
496         $bluesky_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
497         $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
498
499         // if API is used, default to the chosen settings
500         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
501                 $bluesky_enable = 1;
502         }
503
504         if (!$bluesky_enable) {
505                 return;
506         }
507
508         if (strlen($b['postopts'])) {
509                 $b['postopts'] .= ',';
510         }
511
512         $b['postopts'] .= 'bluesky';
513 }
514
515 function bluesky_send(array &$b)
516 {
517         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
518                 return;
519         }
520
521         if ($b['gravity'] != Item::GRAVITY_PARENT) {
522                 Logger::debug('Got comment', ['item' => $b]);
523
524                 if ($b['deleted']) {
525                         $uri = bluesky_get_uri_class($b['uri']);
526                         if (empty($uri)) {
527                                 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
528                                 return;
529                         }
530                         bluesky_delete_post($b['uri'], $b['uid']);
531                         return;
532                 }
533
534                 $root   = bluesky_get_uri_class($b['parent-uri']);
535                 $parent = bluesky_get_uri_class($b['thr-parent']);
536
537                 if (empty($root) || empty($parent)) {
538                         Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
539                         return;
540                 }
541
542                 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
543                         Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
544                         bluesky_create_post($b, $root, $parent);
545                         return;
546                 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
547                         bluesky_create_activity($b, $parent);
548                 }
549                 return;
550         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
551                 return;
552         }
553
554         bluesky_create_post($b);
555 }
556
557 function bluesky_create_activity(array $item, stdClass $parent = null)
558 {
559         $uid = $item['uid'];
560         $token = bluesky_get_token($uid);
561         if (empty($token)) {
562                 return;
563         }
564
565         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
566
567         if ($item['verb'] == Activity::LIKE) {
568                 $record = [
569                         'subject'   => $parent,
570                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
571                         '$type'     => 'app.bsky.feed.like'
572                 ];
573
574                 $post = [
575                         'collection' => 'app.bsky.feed.like',
576                         'repo'       => $did,
577                         'record'     => $record
578                 ];
579         } elseif ($item['verb'] == Activity::ANNOUNCE) {
580                 $record = [
581                         'subject'   => $parent,
582                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
583                         '$type'     => 'app.bsky.feed.repost'
584                 ];
585
586                 $post = [
587                         'collection' => 'app.bsky.feed.repost',
588                         'repo'       => $did,
589                         'record'     => $record
590                 ];
591         }
592
593         $activity = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
594         if (empty($activity)) {
595                 return;
596         }
597         Logger::debug('Activity done', ['return' => $activity]);
598         $uri = bluesky_get_uri($activity);
599         Item::update(['extid' => $uri], ['id' => $item['id']]);
600         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
601 }
602
603 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
604 {
605         $uid = $item['uid'];
606         $token = bluesky_get_token($uid);
607         if (empty($token)) {
608                 return;
609         }
610
611         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
612         $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
613         $item['body'] = $urls['body'];
614
615         $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
616         foreach ($msg['parts'] as $key => $part) {
617
618                 $facets = bluesky_get_facets($part, $urls['urls']);
619
620                 $record = [
621                         'text'      => $facets['body'],
622                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
623                         '$type'     => 'app.bsky.feed.post'
624                 ];
625
626                 if (!empty($facets['facets'])) {
627                         $record['facets'] = $facets['facets'];
628                 }
629
630                 if (!empty($root)) {
631                         $record['reply'] = ['root' => $root, 'parent' => $parent];
632                 }
633
634                 if ($key == count($msg['parts']) - 1) {
635                         $record = bluesky_add_embed($uid, $msg, $record);
636                 }
637
638                 $post = [
639                         'collection' => 'app.bsky.feed.post',
640                         'repo'       => $did,
641                         'record'     => $record
642                 ];
643
644                 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
645                 if (empty($parent)) {
646                         return;
647                 }
648                 Logger::debug('Posting done', ['return' => $parent]);
649                 if (empty($root)) {
650                         $root = $parent;
651                 }
652                 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
653                         $uri = bluesky_get_uri($parent);
654                         Item::update(['extid' => $uri], ['id' => $item['id']]);
655                         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
656                 }
657         }
658 }
659
660 function bluesky_get_urls(string $body): array
661 {
662         // Remove all hashtags and mentions
663         $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
664
665         $urls = [];
666
667         // Search for pure links
668         if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
669                 foreach ($matches as $match) {
670                         $text = Strings::getStyledURL($match[1]);
671                         $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
672                         $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
673                         $body = str_replace($match[0], $hash, $body);
674                 }
675         }
676
677         // Search for links with descriptions
678         if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
679                 foreach ($matches as $match) {
680                         if ($match[1] == $match[2]) {
681                                 $text = Strings::getStyledURL($match[1]);
682                         } else {
683                                 $text = $match[2];
684                         }
685                         if (mb_strlen($text) < 100) {
686                                 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
687                                 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
688                                 $body = str_replace($match[0], $hash, $body);
689                         } else {
690                                 $text = Strings::getStyledURL($match[1]);
691                                 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
692                                 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
693                                 $body = str_replace($match[0], $text . ' ' . $hash, $body);
694                         }
695                 }
696         }
697
698         return ['body' => $body, 'urls' => $urls];
699 }
700
701 function bluesky_get_hash_for_url(string $text, int $linklength): string
702 {
703         if ($linklength <= 10) {
704                 return '|' . hash('crc32', $text) . '|';
705         }
706         return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
707 }
708
709 function bluesky_get_facets(string $body, array $urls): array
710 {
711         $facets = [];
712
713         foreach ($urls as $url) {
714                 $pos = strpos($body, $url['hash']);
715                 if ($pos === false) {
716                         continue;
717                 }
718                 if ($pos > 0) {
719                         $prefix = substr($body, 0, $pos);
720                 } else {
721                         $prefix = '';
722                 }
723
724                 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
725
726                 $facet = new stdClass;
727                 $facet->index = new stdClass;
728                 $facet->index->byteEnd   = $pos + strlen($url['text']);
729                 $facet->index->byteStart = $pos;
730
731                 $feature = new stdClass;
732                 $feature->uri = $url['url'];
733                 $type = '$type';
734                 $feature->$type = 'app.bsky.richtext.facet#link';
735
736                 $facet->features = [$feature];
737                 $facets[] = $facet;
738         }
739
740         return ['facets' => $facets, 'body' => $body];
741 }
742
743 function bluesky_add_embed(int $uid, array $msg, array $record): array
744 {
745         if (($msg['type'] != 'link') && !empty($msg['images'])) {
746                 $images = [];
747                 foreach ($msg['images'] as $image) {
748                         $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
749                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
750                         $blob = bluesky_upload_blob($uid, $photo);
751                         if (!empty($blob) && count($images) < 4) {
752                                 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
753                         }
754                 }
755                 if (!empty($images)) {
756                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
757                 }
758         } elseif ($msg['type'] == 'link') {
759                 $record['embed'] = [
760                         '$type'    => 'app.bsky.embed.external',
761                         'external' => [
762                                 'uri'         => $msg['url'],
763                                 'title'       => $msg['title'],
764                                 'description' => $msg['description'],
765                         ]
766                 ];
767                 if (!empty($msg['image'])) {
768                         $photo = Photo::createPhotoForExternalResource($msg['image']);
769                         $blob = bluesky_upload_blob($uid, $photo);
770                         if (!empty($blob)) {
771                                 $record['embed']['external']['thumb'] = $blob;
772                         }
773                 }
774         }
775         return $record;
776 }
777
778 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
779 {
780         $content = Photo::getImageForPhoto($photo);
781         $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
782         if (empty($data)) {
783                 return null;
784         }
785
786         Logger::debug('Uploaded blob', ['return' => $data]);
787         return $data->blob;
788 }
789
790 function bluesky_delete_post(string $uri, int $uid)
791 {
792         $token = bluesky_get_token($uid);
793         $parts = bluesky_get_uri_parts($uri);
794         if (empty($parts)) {
795                 Logger::debug('No uri delected', ['uri' => $uri]);
796                 return;
797         }
798         bluesky_post($uid, '/xrpc/com.atproto.repo.deleteRecord', json_encode($parts), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
799         Logger::debug('Deleted', ['parts' => $parts]);
800 }
801
802 function bluesky_fetch_timeline(int $uid)
803 {
804         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
805         if (empty($data)) {
806                 return;
807         }
808
809         if (empty($data->feed)) {
810                 return;
811         }
812
813         foreach (array_reverse($data->feed) as $entry) {
814                 bluesky_process_post($entry->post, $uid, Item::PR_NONE, 0);
815                 if (!empty($entry->reason)) {
816                         bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
817                 }
818         }
819
820         // @todo Support paging
821         // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
822 }
823
824 function bluesky_process_reason(stdClass $reason, string $uri, int $uid)
825 {
826         $type = '$type';
827         if ($reason->$type != 'app.bsky.feed.defs#reasonRepost') {
828                 return;
829         }
830
831         $contact = bluesky_get_contact($reason->by, $uid, $uid);
832
833         $item = [
834                 'network'       => Protocol::BLUESKY,
835                 'uid'           => $uid,
836                 'wall'          => false,
837                 'uri'           => $reason->by->did . '/app.bsky.feed.repost/' . $reason->indexedAt,
838                 'private'       => Item::UNLISTED,
839                 'verb'          => Activity::POST,
840                 'contact-id'    => $contact['id'],
841                 'author-name'   => $contact['name'],
842                 'author-link'   => $contact['url'],
843                 'author-avatar' => $contact['avatar'],
844                 'verb'          => Activity::ANNOUNCE,
845                 'body'          => Activity::ANNOUNCE,
846                 'gravity'       => Item::GRAVITY_ACTIVITY,
847                 'object-type'   => Activity\ObjectType::NOTE,
848                 'thr-parent'    => $uri,
849         ];
850
851         if (Post::exists(['uri' => $item['uri'], 'uid' => $uid])) {
852                 return;
853         }
854
855         $item['guid']         = Item::guidFromUri($item['uri'], $contact['alias']);
856         $item['owner-name']   = $item['author-name'];
857         $item['owner-link']   = $item['author-link'];
858         $item['owner-avatar'] = $item['author-avatar'];
859         if (Item::insert($item)) {
860                 $cdata = Contact::getPublicAndUserContactID($contact['id'], $uid);
861                 Item::update(['post-reason' => Item::PR_ANNOUNCEMENT, 'causer-id' => $cdata['public']], ['uri' => $uri, 'uid' => $uid]);
862         }
863 }
864
865 function bluesky_fetch_notifications(int $uid)
866 {
867         $result = bluesky_get($uid, '/xrpc/app.bsky.notification.listNotifications', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
868         if (empty($result->notifications)) {
869                 return;
870         }
871         foreach ($result->notifications as $notification) {
872                 $uri = bluesky_get_uri($notification);
873                 if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
874                         Logger::debug('Notification already processed', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
875                         continue;
876                 }
877                 Logger::debug('Process notification', ['uid' => $uid, 'reason' => $notification->reason, 'uri' => $uri, 'indexedAt' => $notification->indexedAt]);
878                 switch ($notification->reason) {
879                         case 'like':
880                                 $item = bluesky_get_header($notification, $uri, $uid, $uid);
881                                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
882                                 $item['body'] = $item['verb'] = Activity::LIKE;
883                                 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
884                                 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
885                                 if (!empty($item['thr-parent'])) {
886                                         $result = Item::insert($item);
887                                         Logger::debug('Got like', ['uid' => $uid, 'result' => $result, 'uri' => $uri]);
888                                 } else {
889                                         Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $$item['thr-parent'], 'uri' => $uri]);
890                                 }
891                         break;
892
893                         case 'repost':
894                                 $item = bluesky_get_header($notification, $uri, $uid, $uid);
895                                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
896                                 $item['body'] = $item['verb'] = Activity::ANNOUNCE;
897                                 $item['thr-parent'] = bluesky_get_uri($notification->record->subject);
898                                 $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], 0);
899                                 if (!empty($item['thr-parent'])) {
900                                         $result = Item::insert($item);
901                                         Logger::debug('Got repost', ['uid' => $uid, 'result' => $result, 'uri' => $uri]);
902                                 } else {
903                                         Logger::info('Thread parent not found', ['uid' => $uid, 'parent' => $$item['thr-parent'], 'uri' => $uri]);
904                                 }
905                         break;
906
907                         case 'follow':
908                                 $contact = bluesky_get_contact($notification->author, $uid, $uid);
909                                 Logger::debug('New follower', ['uid' => $uid, 'nick' => $contact['nick'], 'uri' => $uri]);
910                                 break;
911
912                         case 'mention':
913                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
914                                 Logger::debug('Got mention', ['uid' => $uid, 'result' => $result, 'uri' => $uri]);
915                                 break;
916
917                         case 'reply':
918                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
919                                 Logger::debug('Got reply', ['uid' => $uid, 'result' => $result, 'uri' => $uri]);
920                                 break;
921
922                         case 'quote':
923                                 $result = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
924                                 Logger::debug('Got quote', ['uid' => $uid, 'result' => $result, 'uri' => $uri]);
925                                 break;
926
927                         default:
928                                 Logger::notice('Unhandled reason', ['reason' => $notification->reason, 'uri' => $uri]);
929                                 break;
930                 }
931         }
932 }
933
934 function bluesky_fetch_feed(int $uid, string $feed)
935 {
936         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getFeed?feed=' . urlencode($feed), HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
937         if (empty($data)) {
938                 return;
939         }
940
941         if (empty($data->feed)) {
942                 return;
943         }
944
945         foreach (array_reverse($data->feed) as $entry) {
946                 if (!Relay::isWantedLanguage($entry->post->record->text)) {
947                         Logger::debug('Unwanted language detected', ['text' => $entry->post->record->text]);
948                         continue;
949                 }
950                 bluesky_process_post($entry->post, $uid, Item::PR_TAG, 0);
951                 if (!empty($entry->reason)) {
952                         bluesky_process_reason($entry->reason, bluesky_get_uri($entry->post), $uid);
953                 }
954         }
955 }
956
957 function bluesky_process_post(stdClass $post, int $uid, int $post_reason, $level): int
958 {
959         $uri = bluesky_get_uri($post);
960
961         if (Post::exists(['uri' => $uri, 'uid' => $uid]) || Post::exists(['extid' => $uri, 'uid' => $uid])) {
962                 return 0;
963         }
964
965         Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $post->indexedAt, 'uri' => $post->uri, 'cid' => $post->cid, 'root' => $post->record->reply->root ?? '']);
966
967         $item = bluesky_get_header($post, $uri, $uid, $uid);
968         $item = bluesky_get_content($item, $post->record, $uri, $uid, $level);
969         if (empty($item)) {
970                 return 0;
971         }
972
973         if (!empty($post->embed)) {
974                 $item = bluesky_add_media($post->embed, $item, $uid, $level);
975         }
976
977         if (empty($item['post-reason'])) {
978                 $item['post-reason'] = $post_reason;
979         }
980
981         return item::insert($item);
982 }
983
984 function bluesky_get_header(stdClass $post, string $uri, int $uid, int $fetch_uid): array
985 {
986         $parts = bluesky_get_uri_parts($uri);
987         if (empty($post->author)) {
988                 return [];
989         }
990         $contact = bluesky_get_contact($post->author, $uid, $fetch_uid);
991         $item = [
992                 'network'       => Protocol::BLUESKY,
993                 'uid'           => $uid,
994                 'wall'          => false,
995                 'uri'           => $uri,
996                 'guid'          => $post->cid,
997                 'private'       => Item::UNLISTED,
998                 'verb'          => Activity::POST,
999                 'contact-id'    => $contact['id'],
1000                 'author-name'   => $contact['name'],
1001                 'author-link'   => $contact['url'],
1002                 'author-avatar' => $contact['avatar'],
1003                 'plink'         => $contact['alias'] . '/post/' . $parts->rkey,
1004         ];
1005
1006         $item['uri-id']       = ItemURI::getIdByURI($uri);
1007         $item['owner-name']   = $item['author-name'];
1008         $item['owner-link']   = $item['author-link'];
1009         $item['owner-avatar'] = $item['author-avatar'];
1010
1011         if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1012                 $item['post-reason'] = Item::PR_FOLLOWER;
1013         }
1014
1015         return $item;
1016 }
1017
1018 function bluesky_get_content(array $item, stdClass $record, string $uri, int $uid, int $level): array
1019 {
1020         if (empty($item)) {
1021                 return [];
1022         }
1023
1024         if (!empty($record->reply)) {
1025                 $item['parent-uri'] = bluesky_get_uri($record->reply->root);
1026                 if ($item['parent-uri'] != $uri) {
1027                         $item['parent-uri'] = bluesky_fetch_missing_post($item['parent-uri'], $uid, $item['contact-id'], $level);
1028                         if (empty($item['parent-uri'])) {
1029                                 return [];
1030                         }
1031                 }
1032
1033                 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
1034                 if (!in_array($item['thr-parent'], [$uri, $item['parent-uri']])) {
1035                         $item['thr-parent'] = bluesky_fetch_missing_post($item['thr-parent'], $uid, $item['contact-id'], $level, $item['parent-uri']);
1036                         if (empty($item['thr-parent'])) {
1037                                 return [];
1038                         }
1039                 }
1040         }
1041
1042         $item['body']    = bluesky_get_text($record);
1043         $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
1044         return $item;
1045 }
1046
1047 function bluesky_get_text(stdClass $record): string
1048 {
1049         $text = $record->text;
1050
1051         if (empty($record->facets)) {
1052                 return $text;
1053         }
1054
1055         $facets = [];
1056         foreach ($record->facets as $facet) {
1057                 $facets[$facet->index->byteStart] = $facet;
1058         }
1059         krsort($facets);
1060
1061         foreach ($facets as $facet) {
1062                 $prefix   = substr($text, 0, $facet->index->byteStart);
1063                 $linktext = substr($text, $facet->index->byteStart, $facet->index->byteEnd - $facet->index->byteStart);
1064                 $suffix   = substr($text, $facet->index->byteEnd);
1065
1066                 $url  = '';
1067                 $type = '$type';
1068                 foreach ($facet->features as $feature) {
1069
1070                         switch ($feature->$type) {
1071                                 case 'app.bsky.richtext.facet#link':
1072                                         $url = $feature->uri;
1073                                         break;
1074
1075                                 case 'app.bsky.richtext.facet#mention':
1076                                         $contact = Contact::getByURL($feature->did, null, ['id']);
1077                                         if (!empty($contact['id'])) {
1078                                                 $url = DI::baseUrl() . '/contact/' . $contact['id'];
1079                                                 if (substr($linktext, 0, 1) == '@') {
1080                                                         $prefix .= '@';
1081                                                         $linktext = substr($linktext, 1);
1082                                                 }
1083                                         }
1084                                         break;
1085
1086                                 default:
1087                                         Logger::notice('Unhandled feature type', ['type' => $feature->$type, 'record' => $record]);
1088                                         break;
1089                         }
1090                 }
1091                 if (!empty($url)) {
1092                         $text = $prefix . '[url=' . $url . ']' . $linktext . '[/url]' . $suffix;
1093                 }
1094         }
1095         return $text;
1096 }
1097
1098 function bluesky_add_media(stdClass $embed, array $item, int $fetch_uid, int $level): array
1099 {
1100         $type = '$type';
1101         switch ($embed->$type) {
1102                 case 'app.bsky.embed.images#view':
1103                         foreach ($embed->images as $image) {
1104                                 $media = [
1105                                         'uri-id'      => $item['uri-id'],
1106                                         'type'        => Post\Media::IMAGE,
1107                                         'url'         => $image->fullsize,
1108                                         'preview'     => $image->thumb,
1109                                         'description' => $image->alt,
1110                                 ];
1111                                 Post\Media::insert($media);
1112                         }
1113                         break;
1114
1115                 case 'app.bsky.embed.external#view':
1116                         $media = [
1117                                 'uri-id' => $item['uri-id'],
1118                                 'type'        => Post\Media::HTML,
1119                                 'url'         => $embed->external->uri,
1120                                 'name'        => $embed->external->title,
1121                                 'description' => $embed->external->description,
1122                         ];
1123                         Post\Media::insert($media);
1124                         break;
1125
1126                 case 'app.bsky.embed.record#view':
1127                         $uri = bluesky_get_uri($embed->record);
1128                         $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1129                         if (empty($shared)) {
1130                                 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1131                                 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1132                                 if (!empty($shared)) {
1133                                         if (!empty($embed->record->embeds)) {
1134                                                 foreach ($embed->record->embeds as $single) {
1135                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1136                                                 }
1137                                         }
1138                                         $id = Item::insert($shared);
1139                                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1140                                 }
1141                         }
1142                         if (!empty($shared)) {
1143                                 $item['quote-uri-id'] = $shared['uri-id'];
1144                         }
1145                         break;
1146
1147                 case 'app.bsky.embed.recordWithMedia#view':
1148                         $uri = bluesky_get_uri($embed->record->record);
1149                         $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1150                         if (empty($shared)) {
1151                                 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1152                                 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1153                                 if (!empty($shared)) {
1154                                         if (!empty($embed->record->embeds)) {
1155                                                 foreach ($embed->record->record->embeds as $single) {
1156                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1157                                                 }
1158                                         }
1159
1160                                         if (!empty($embed->media)) {
1161                                                 bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1162                                         }
1163
1164                                         $id = Item::insert($shared);
1165                                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1166                                 }
1167                         }
1168                         if (!empty($shared)) {
1169                                 $item['quote-uri-id'] = $shared['uri-id'];
1170                         }
1171                         break;
1172
1173                 default:
1174                         Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1175                         break;
1176         }
1177         return $item;
1178 }
1179
1180 function bluesky_get_uri(stdClass $post): string
1181 {
1182         return $post->uri . ':' . $post->cid;
1183 }
1184
1185 function bluesky_get_uri_class(string $uri): ?stdClass
1186 {
1187         if (empty($uri)) {
1188                 return null;
1189         }
1190
1191         $elements = explode(':', $uri);
1192         if (empty($elements) || ($elements[0] != 'at')) {
1193                 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1194                 return bluesky_get_uri_class($post['extid'] ?? '');
1195         }
1196
1197         $class = new stdClass;
1198
1199         $class->cid = array_pop($elements);
1200         $class->uri = implode(':', $elements);
1201
1202         if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1203                 $class->uri .= ':' . $class->cid;
1204                 $class->cid = '';
1205         }
1206
1207         return $class;
1208 }
1209
1210 function bluesky_get_uri_parts(string $uri): ?stdClass
1211 {
1212         $class = bluesky_get_uri_class($uri);
1213         if (empty($class)) {
1214                 return null;
1215         }
1216
1217         $parts = explode('/', substr($class->uri, 5));
1218
1219         $class = new stdClass;
1220
1221         $class->repo       = $parts[0];
1222         $class->collection = $parts[1];
1223         $class->rkey       = $parts[2];
1224
1225         return $class;
1226 }
1227
1228 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1229 {
1230         $fetched_uri = bluesky_fetch_post($uri, $uid);
1231         if (!empty($fetched_uri)) {
1232                 return $fetched_uri;
1233         }
1234
1235         if (++$level > 100) {
1236                 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1237                 // When the level is too deep we will fallback to the parent uri.
1238                 // Allthough the threading won't be correct, we at least had stored all posts and won't try again 
1239                 return $fallback;
1240         }
1241
1242         $class = bluesky_get_uri_class($uri);
1243         $fetch_uri = $class->uri;
1244
1245         Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1246         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getPostThread?uri=' . urlencode($fetch_uri), HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1247         if (empty($data)) {
1248                 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1249                 return $fallback;
1250         }
1251         
1252         Logger::debug('Reply count', ['replies' => $data->thread->post->replyCount, 'level' => $level, 'uid' => $uid, 'uri' => $uri]); 
1253
1254         if ($causer != 0) {
1255                 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1256         }
1257
1258         return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1259 }
1260
1261 function bluesky_fetch_post(string $uri, int $uid): string
1262 {
1263         if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1264                 Logger::debug('Post exists', ['uri' => $uri]);
1265                 return $uri;
1266         }
1267
1268         $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1269         if (!empty($reply['uri'])) {
1270                 Logger::debug('Post with extid exists', ['uri' => $uri]);
1271                 return $reply['uri'];
1272         }
1273         return '';
1274 }
1275
1276 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1277 {
1278         $uri = bluesky_get_uri($thread->post);
1279         $fetched_uri = bluesky_fetch_post($uri, $uid);
1280         if (empty($fetched_uri)) {
1281                 Logger::debug('Process missing post', ['uri' => $uri]);
1282                 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1283                 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1284                 if (!empty($item)) {
1285                         $item['post-reason'] = Item::PR_FETCHED;
1286
1287                         if (!empty($cdata['public'])) {
1288                                 $item['causer-id']   = $cdata['public'];
1289                         }
1290
1291                         if (!empty($thread->post->embed)) {
1292                                 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1293                         }
1294                         $id = Item::insert($item);
1295                         if (!$id) {
1296                                 Logger::info('Item has not not been stored', ['uri' => $uri]);
1297                                 return '';
1298                         }
1299                         Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1300                 } else {
1301                         Logger::info('Post has not not been fetched', ['uri' => $uri]);
1302                         return '';
1303                 }
1304         } else {
1305                 Logger::debug('Post exists', ['uri' => $uri]);
1306                 $uri = $fetched_uri;
1307         }
1308
1309         foreach ($thread->replies ?? [] as $reply) {
1310                 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1311                 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1312         }
1313
1314         return $uri;
1315 }
1316
1317 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1318 {
1319         $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1320         $contact = Contact::selectFirst(['id', 'updated'], $condition);
1321
1322         $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1323
1324         $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1325
1326         $public_fields['uid'] = 0;
1327         $public_fields['rel'] = Contact::NOTHING;
1328
1329         if (empty($contact)) {
1330                 $cid = Contact::insert($public_fields);
1331         } else {
1332                 $cid = $contact['id'];
1333                 Contact::update($public_fields, ['id' => $cid], true);
1334         }
1335
1336         if ($uid != 0) {
1337                 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1338
1339                 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1340                 if (!isset($fields['rel']) && isset($contact['rel'])) {
1341                         $fields['rel'] = $contact['rel'];
1342                 } elseif (!isset($fields['rel'])) {
1343                         $fields['rel'] = Contact::NOTHING;
1344                 }
1345         }
1346
1347         if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1348                 if (empty($contact)) {
1349                         $cid = Contact::insert($fields);
1350                 } else {
1351                         $cid = $contact['id'];
1352                         Contact::update($fields, ['id' => $cid], true);
1353                 }
1354                 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1355         } else {
1356                 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1357         }
1358         if (!empty($author->avatar)) {
1359                 Contact::updateAvatar($cid, $author->avatar);
1360         }
1361
1362         return Contact::getById($cid);
1363 }
1364
1365 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1366 {
1367         $fields = [
1368                 'uid'      => $uid,
1369                 'network'  => Protocol::BLUESKY,
1370                 'priority' => 1,
1371                 'writable' => true,
1372                 'blocked'  => false,
1373                 'readonly' => false,
1374                 'pending'  => false,
1375                 'baseurl'  => BLUESKY_HOST,
1376                 'url'      => $author->did,
1377                 'nurl'     => $author->did,
1378                 'alias'    => BLUESKY_HOST . '/profile/' . $author->handle,
1379                 'name'     => $author->displayName ?? $author->handle,
1380                 'nick'     => $author->handle,
1381                 'addr'     => $author->handle,
1382         ];
1383
1384         if (!$update) {
1385                 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1386                 return $fields;
1387         }
1388
1389         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . urlencode($author->did), HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1390         if (empty($data)) {
1391                 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1392                 return $fields;
1393         }
1394
1395         $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1396
1397         if (!empty($data->description)) {
1398                 $fields['about'] = HTML::toBBCode($data->description);
1399         }
1400
1401         if (!empty($data->banner)) {
1402                 $fields['header'] = $data->banner;
1403         }
1404
1405         if (!empty($data->viewer)) {
1406                 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1407                         $fields['rel'] = Contact::FRIEND;
1408                 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1409                         $fields['rel'] = Contact::SHARING;
1410                 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1411                         $fields['rel'] = Contact::FOLLOWER;
1412                 } else {
1413                         $fields['rel'] = Contact::NOTHING;
1414                 }
1415         }
1416
1417         Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1418         return $fields;
1419 }
1420
1421 function bluesky_get_feeds(int $uid): array
1422 {
1423         $type = '$type';
1424         $preferences = bluesky_get_preferences($uid);
1425         foreach ($preferences->preferences as $preference) {
1426                 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1427                         return $preference->pinned ?? [];
1428                 }
1429         }
1430         return [];
1431 }
1432
1433 function bluesky_get_preferences(int $uid): stdClass
1434 {
1435         $cachekey = 'bluesky:preferences:' . $uid;
1436         $data = DI::cache()->get($cachekey);
1437         if (!is_null($data)) {
1438                 return $data;
1439         }
1440
1441         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getPreferences', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1442
1443         DI::cache()->set($cachekey, $data, Duration::HOUR);
1444         return $data;
1445 }
1446
1447 function bluesky_get_did(int $uid, string $handle): string
1448 {
1449         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1450         if (empty($data)) {
1451                 return '';
1452         }
1453         Logger::debug('Got DID', ['return' => $data]);
1454         return $data->did;
1455 }
1456
1457 function bluesky_get_token(int $uid): string
1458 {
1459         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1460         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1461         if (empty($token)) {
1462                 return '';
1463         }
1464
1465         if ($created + 300 < time()) {
1466                 return bluesky_refresh_token($uid);
1467         }
1468         return $token;
1469 }
1470
1471 function bluesky_refresh_token(int $uid): string
1472 {
1473         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1474
1475         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1476         if (empty($data)) {
1477                 return '';
1478         }
1479
1480         Logger::debug('Refreshed token', ['return' => $data]);
1481         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1482         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1483         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1484         return $data->accessJwt;
1485 }
1486
1487 function bluesky_create_token(int $uid, string $password): string
1488 {
1489         $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1490
1491         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1492         if (empty($data)) {
1493                 return '';
1494         }
1495
1496         Logger::debug('Created token', ['return' => $data]);
1497         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1498         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1499         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1500         return $data->accessJwt;
1501 }
1502
1503 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1504 {
1505         try {
1506                 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1507         } catch (\Exception $e) {
1508                 Logger::notice('Exception on post', ['exception' => $e]);
1509                 return null;
1510         }
1511
1512         if (!$curlResult->isSuccess()) {
1513                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1514                 return null;
1515         }
1516
1517         return json_decode($curlResult->getBody());
1518 }
1519
1520 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1521 {
1522         try {
1523                 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1524         } catch (\Exception $e) {
1525                 Logger::notice('Exception on get', ['exception' => $e]);
1526                 return null;
1527         }
1528
1529         if (!$curlResult->isSuccess()) {
1530                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1531                 return null;
1532         }
1533
1534         return json_decode($curlResult->getBody());
1535 }