]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
Bluesky: Fix "E_WARNING: Undefined property: stdClass::$cid"
[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\System;
36 use Friendica\Core\Worker;
37 use Friendica\Database\DBA;
38 use Friendica\DI;
39 use Friendica\Model\Contact;
40 use Friendica\Model\Item;
41 use Friendica\Model\ItemURI;
42 use Friendica\Model\Photo;
43 use Friendica\Model\Post;
44 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
45 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
46 use Friendica\Protocol\Activity;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\Strings;
50
51 const BLUESKY_DEFAULT_POLL_INTERVAL = 10; // given in minutes
52 const BLUESKY_HOST = 'https://bsky.app'; // Hard wired until Bluesky will run on multiple systems
53
54 function bluesky_install()
55 {
56         Hook::register('load_config',             __FILE__, 'bluesky_load_config');
57         Hook::register('hook_fork',               __FILE__, 'bluesky_hook_fork');
58         Hook::register('post_local',              __FILE__, 'bluesky_post_local');
59         Hook::register('notifier_normal',         __FILE__, 'bluesky_send');
60         Hook::register('jot_networks',            __FILE__, 'bluesky_jot_nets');
61         Hook::register('connector_settings',      __FILE__, 'bluesky_settings');
62         Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
63         Hook::register('cron',                    __FILE__, 'bluesky_cron');
64         Hook::register('support_follow',          __FILE__, 'bluesky_support_follow');
65         Hook::register('support_probe',           __FILE__, 'bluesky_support_probe');
66         Hook::register('follow',                  __FILE__, 'bluesky_follow');
67         Hook::register('unfollow',                __FILE__, 'bluesky_unfollow');
68         Hook::register('block',                   __FILE__, 'bluesky_block');
69         Hook::register('unblock',                 __FILE__, 'bluesky_unblock');
70         Hook::register('check_item_notification', __FILE__, 'bluesky_check_item_notification');
71         Hook::register('probe_detect',            __FILE__, 'bluesky_probe_detect');
72         Hook::register('item_by_link',            __FILE__, 'bluesky_item_by_link');
73 }
74
75 function bluesky_load_config(ConfigFileManager $loader)
76 {
77         DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
78 }
79
80 function bluesky_check_item_notification(array &$notification_data)
81 {
82         $did = DI::pConfig()->get($notification_data['uid'], 'bluesky', 'did');
83
84         if (!empty($did)) {
85                 $notification_data['profiles'][] = $did;
86         }
87 }
88
89 function bluesky_probe_detect(array &$hookData)
90 {
91         // Don't overwrite an existing result
92         if (isset($hookData['result'])) {
93                 return;
94         }
95
96         // Avoid a lookup for the wrong network
97         if (!in_array($hookData['network'], ['', Protocol::BLUESKY])) {
98                 return;
99         }
100
101         $pconfig = DBA::selectFirst('pconfig', ['uid'], ["`cat` = ? AND `k` = ? AND `v` != ?", 'bluesky', 'access_token', '']);
102         if (empty($pconfig['uid'])) {
103                 return;
104         }
105
106         if (parse_url($hookData['uri'], PHP_URL_SCHEME) == 'did') {
107                 $did = $hookData['uri'];
108         } elseif (preg_match('#^' . BLUESKY_HOST . '/profile/(.+)#', $hookData['uri'], $matches)) {
109                 $did = bluesky_get_did($pconfig['uid'], $matches[1]);
110                 if (empty($did)) {
111                         return;
112                 }
113         } else {
114                 return;
115         }
116
117         $token = bluesky_get_token($pconfig['uid']);
118         if (empty($token)) {
119                 return;
120         }
121
122         $data = bluesky_xrpc_get($pconfig['uid'], 'app.bsky.actor.getProfile', ['actor' => $did]);
123         if (empty($data)) {
124                 return;
125         }
126
127         $hookData['result'] = bluesky_get_contact_fields($data, 0, false);
128
129         // Preparing probe data. This differs slightly from the contact array
130         $hookData['result']['about']    = HTML::toBBCode($data->description ?? '');
131         $hookData['result']['photo']    = $data->avatar ?? '';
132         $hookData['result']['header']   = $data->banner ?? '';
133         $hookData['result']['batch']    = '';
134         $hookData['result']['notify']   = '';
135         $hookData['result']['poll']     = '';
136         $hookData['result']['poco']     = '';
137         $hookData['result']['pubkey']   = '';
138         $hookData['result']['priority'] = 0;
139         $hookData['result']['guid']     = '';
140 }
141
142 function bluesky_item_by_link(array &$hookData)
143 {
144         // Don't overwrite an existing result
145         if (isset($hookData['item_id'])) {
146                 return;
147         }
148
149         $token = bluesky_get_token($hookData['uid']);
150         if (empty($token)) {
151                 return;
152         }
153
154         if (!preg_match('#^' . BLUESKY_HOST . '/profile/(.+)/post/(.+)#', $hookData['uri'], $matches)) {
155                 return;
156         }
157
158         $did = bluesky_get_did($hookData['uid'], $matches[1]);
159         if (empty($did)) {
160                 return;
161         }
162
163         Logger::debug('Found bluesky post', ['url' => $hookData['uri'], 'handle' => $matches[1], 'did' => $did, 'cid' => $matches[2]]);
164
165         $uri = 'at://' . $did . '/app.bsky.feed.post/' . $matches[2];
166
167         $uri = bluesky_fetch_missing_post($uri, $hookData['uid'], 0, 0);
168         Logger::debug('Got post', ['profile' => $matches[1], 'cid' => $matches[2], 'result' => $uri]);
169         if (!empty($uri)) {
170                 $item = Post::selectFirst(['id'], ['uri' => $uri, 'uid' => $hookData['uid']]);
171                 if (!empty($item['id'])) {
172                         $hookData['item_id'] = $item['id'];
173                 }
174         }
175 }
176
177 function bluesky_support_follow(array &$data)
178 {
179         if ($data['protocol'] == Protocol::BLUESKY) {
180                 $data['result'] = true;
181         }
182 }
183
184 function bluesky_support_probe(array &$data)
185 {
186         if ($data['protocol'] == Protocol::BLUESKY) {
187                 $data['result'] = true;
188         }
189 }
190
191 function bluesky_follow(array &$hook_data)
192 {
193         $token = bluesky_get_token($hook_data['uid']);
194         if (empty($token)) {
195                 return;
196         }
197
198         Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
199         $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
200         if (empty($contact)) {
201                 return;
202         }
203
204         $record = [
205                 'subject'   => $contact['url'],
206                 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
207                 '$type'     => 'app.bsky.graph.follow'
208         ];
209
210         $post = [
211                 'collection' => 'app.bsky.graph.follow',
212                 'repo'       => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
213                 'record'     => $record
214         ];
215
216         $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
217         if (!empty($activity->uri)) {
218                 $hook_data['contact'] = $contact;
219                 Logger::debug('Successfully start following', ['url' => $contact['url'], 'uri' => $activity->uri]);
220         }
221 }
222
223 function bluesky_unfollow(array &$hook_data)
224 {
225         $token = bluesky_get_token($hook_data['uid']);
226         if (empty($token)) {
227                 return;
228         }
229
230         if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
231                 return;
232         }
233
234         $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
235         if (empty($data->viewer) || empty($data->viewer->following)) {
236                 return;
237         }
238
239         bluesky_delete_post($data->viewer->following, $hook_data['uid']);
240
241         $hook_data['result'] = true;
242 }
243
244 function bluesky_block(array &$hook_data)
245 {
246         $token = bluesky_get_token($hook_data['uid']);
247         if (empty($token)) {
248                 return;
249         }
250
251         Logger::debug('Check if contact is bluesky', ['data' => $hook_data]);
252         $contact = DBA::selectFirst('contact', [], ['network' => Protocol::BLUESKY, 'url' => $hook_data['url'], 'uid' => [0, $hook_data['uid']]]);
253         if (empty($contact)) {
254                 return;
255         }
256
257         $record = [
258                 'subject'   => $contact['url'],
259                 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
260                 '$type'     => 'app.bsky.graph.block'
261         ];
262
263         $post = [
264                 'collection' => 'app.bsky.graph.block',
265                 'repo'       => DI::pConfig()->get($hook_data['uid'], 'bluesky', 'did'),
266                 'record'     => $record
267         ];
268
269         $activity = bluesky_xrpc_post($hook_data['uid'], 'com.atproto.repo.createRecord', $post);
270         if (!empty($activity->uri)) {
271                 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
272                 if (!empty($cdata['user'])) {
273                         Contact::remove($cdata['user']);
274                 }
275                 Logger::debug('Successfully blocked contact', ['url' => $hook_data['contact']['url'], 'uri' => $activity->uri]);
276         }
277 }
278
279 function bluesky_unblock(array &$hook_data)
280 {
281         $token = bluesky_get_token($hook_data['uid']);
282         if (empty($token)) {
283                 return;
284         }
285
286         if ($hook_data['contact']['network'] != Protocol::BLUESKY) {
287                 return;
288         }
289
290         $data = bluesky_xrpc_get($hook_data['uid'], 'app.bsky.actor.getProfile', ['actor' => $hook_data['contact']['url']]);
291         if (empty($data->viewer) || empty($data->viewer->blocking)) {
292                 return;
293         }
294
295         bluesky_delete_post($data->viewer->blocking, $hook_data['uid']);
296
297         $hook_data['result'] = true;
298 }
299
300 function bluesky_settings(array &$data)
301 {
302         if (!DI::userSession()->getLocalUserId()) {
303                 return;
304         }
305
306         $enabled      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
307         $def_enabled  = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
308         $host         = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
309         $handle       = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
310         $did          = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
311         $token        = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
312         $import       = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
313         $import_feeds = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds') ?? false;
314
315         $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.');
316
317         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
318         $html = Renderer::replaceMacros($t, [
319                 '$enable'       => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
320                 '$bydefault'    => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
321                 '$import'       => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
322                 '$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.')],
323                 '$host'         => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
324                 '$handle'       => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
325                 '$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'],
326                 '$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.")],
327                 '$status'       => $status
328         ]);
329
330         $data = [
331                 'connector' => 'bluesky',
332                 'title'     => DI::l10n()->t('Bluesky Import/Export'),
333                 'image'     => 'images/bluesky.jpg',
334                 'enabled'   => $enabled,
335                 'html'      => $html,
336         ];
337 }
338
339 function bluesky_settings_post(array &$b)
340 {
341         if (empty($_POST['bluesky-submit'])) {
342                 return;
343         }
344
345         $old_host   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
346         $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
347         $old_did    = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
348
349         $host   = $_POST['bluesky_host'];
350         $handle = $_POST['bluesky_handle'];
351
352         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post',            intval($_POST['bluesky']));
353         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
354         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host',            $host);
355         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle',          $handle);
356         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import',          intval($_POST['bluesky_import']));
357         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import_feeds',    intval($_POST['bluesky_import_feeds']));
358
359         if (!empty($host) && !empty($handle)) {
360                 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
361                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId(), DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle')));
362                 }
363         } else {
364                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
365         }
366
367         if (!empty($_POST['bluesky_password'])) {
368                 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
369         }
370 }
371
372 function bluesky_jot_nets(array &$jotnets_fields)
373 {
374         if (!DI::userSession()->getLocalUserId()) {
375                 return;
376         }
377
378         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
379                 $jotnets_fields[] = [
380                         'type'  => 'checkbox',
381                         'field' => [
382                                 'bluesky_enable',
383                                 DI::l10n()->t('Post to Bluesky'),
384                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
385                         ]
386                 ];
387         }
388 }
389
390 function bluesky_cron()
391 {
392         $last = DI::keyValue()->get('bluesky_last_poll');
393
394         $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
395         if (!$poll_interval) {
396                 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
397         }
398
399         if ($last) {
400                 $next = $last + ($poll_interval * 60);
401                 if ($next > time()) {
402                         Logger::notice('poll interval not reached');
403                         return;
404                 }
405         }
406         Logger::notice('cron_start');
407
408         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
409         if ($abandon_days < 1) {
410                 $abandon_days = 0;
411         }
412
413         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
414
415         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
416         foreach ($pconfigs as $pconfig) {
417                 if ($abandon_days != 0) {
418                         if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
419                                 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
420                                 continue;
421                         }
422                 }
423
424                 // Refresh the token now, so that it doesn't need to be refreshed in parallel by the following workers
425                 bluesky_get_token($pconfig['uid']);
426
427                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_timeline.php', $pconfig['uid']);
428                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_notifications.php', $pconfig['uid']);
429
430                 if (DI::pConfig()->get($pconfig['uid'], 'bluesky', 'import_feeds')) {
431                         $feeds = bluesky_get_feeds($pconfig['uid']);
432                         foreach ($feeds as $feed) {
433                                 Worker::add(['priority' => Worker::PRIORITY_MEDIUM, 'force_priority' => true], 'addon/bluesky/bluesky_feed.php', $pconfig['uid'], $feed);
434                         }
435                 }
436         }
437
438         $last_clean = DI::keyValue()->get('bluesky_last_clean');
439         if (empty($last_clean) || ($last_clean + 86400 < time())) {
440                 Logger::notice('Start contact cleanup');
441                 $contacts = DBA::select('account-user-view', ['id', 'pid'], ["`network` = ? AND `uid` != ? AND `rel` = ?", Protocol::BLUESKY, 0, Contact::NOTHING]);
442                 while ($contact = DBA::fetch($contacts)) {
443                         Worker::add(Worker::PRIORITY_LOW, 'MergeContact', $contact['pid'], $contact['id'], 0);
444                 }
445                 DBA::close($contacts);
446                 DI::keyValue()->set('bluesky_last_clean', time());
447                 Logger::notice('Contact cleanup done');
448         }
449
450         Logger::notice('cron_end');
451
452         DI::keyValue()->set('bluesky_last_poll', time());
453 }
454
455 function bluesky_hook_fork(array &$b)
456 {
457         if ($b['name'] != 'notifier_normal') {
458                 return;
459         }
460
461         $post = $b['data'];
462
463         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
464                 DI::logger()->info('Editing is not supported by the addon');
465                 $b['execute'] = false;
466                 return;
467         }
468
469         if (DI::pConfig()->get($post['uid'], 'bluesky', 'import')) {
470                 // Don't post if it isn't a reply to a bluesky post
471                 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::BLUESKY])) {
472                         Logger::notice('No bluesky parent found', ['item' => $post['id']]);
473                         $b['execute'] = false;
474                         return;
475                 }
476         } elseif (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
477                 DI::logger()->info('Activities are never exported when we don\'t import the bluesky timeline', ['uid' => $post['uid']]);
478                 $b['execute'] = false;
479                 return;
480         }
481 }
482
483 function bluesky_post_local(array &$b)
484 {
485         if ($b['edit']) {
486                 return;
487         }
488
489         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
490                 return;
491         }
492
493         if ($b['private'] || $b['parent']) {
494                 return;
495         }
496
497         $bluesky_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
498         $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
499
500         // if API is used, default to the chosen settings
501         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
502                 $bluesky_enable = 1;
503         }
504
505         if (!$bluesky_enable) {
506                 return;
507         }
508
509         if (strlen($b['postopts'])) {
510                 $b['postopts'] .= ',';
511         }
512
513         $b['postopts'] .= 'bluesky';
514 }
515
516 function bluesky_send(array &$b)
517 {
518         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
519                 return;
520         }
521
522         if ($b['gravity'] != Item::GRAVITY_PARENT) {
523                 Logger::debug('Got comment', ['item' => $b]);
524
525                 if ($b['deleted']) {
526                         $uri = bluesky_get_uri_class($b['uri']);
527                         if (empty($uri)) {
528                                 Logger::debug('Not a bluesky post', ['uri' => $b['uri']]);
529                                 return;
530                         }
531                         bluesky_delete_post($b['uri'], $b['uid']);
532                         return;
533                 }
534
535                 $root   = bluesky_get_uri_class($b['parent-uri']);
536                 $parent = bluesky_get_uri_class($b['thr-parent']);
537
538                 if (empty($root) || empty($parent)) {
539                         Logger::debug('No bluesky post', ['parent' => $b['parent'], 'thr-parent' => $b['thr-parent']]);
540                         return;
541                 }
542
543                 if ($b['gravity'] == Item::GRAVITY_COMMENT) {
544                         Logger::debug('Posting comment', ['root' => $root, 'parent' => $parent]);
545                         bluesky_create_post($b, $root, $parent);
546                         return;
547                 } elseif (in_array($b['verb'], [Activity::LIKE, Activity::ANNOUNCE])) {
548                         bluesky_create_activity($b, $parent);
549                 }
550                 return;
551         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
552                 return;
553         }
554
555         bluesky_create_post($b);
556 }
557
558 function bluesky_create_activity(array $item, stdClass $parent = null)
559 {
560         $uid = $item['uid'];
561         $token = bluesky_get_token($uid);
562         if (empty($token)) {
563                 return;
564         }
565
566         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
567
568         if ($item['verb'] == Activity::LIKE) {
569                 $record = [
570                         'subject'   => $parent,
571                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
572                         '$type'     => 'app.bsky.feed.like'
573                 ];
574
575                 $post = [
576                         'collection' => 'app.bsky.feed.like',
577                         'repo'       => $did,
578                         'record'     => $record
579                 ];
580         } elseif ($item['verb'] == Activity::ANNOUNCE) {
581                 $record = [
582                         'subject'   => $parent,
583                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
584                         '$type'     => 'app.bsky.feed.repost'
585                 ];
586
587                 $post = [
588                         'collection' => 'app.bsky.feed.repost',
589                         'repo'       => $did,
590                         'record'     => $record
591                 ];
592         }
593
594         $activity = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
595         if (empty($activity)) {
596                 return;
597         }
598         Logger::debug('Activity done', ['return' => $activity]);
599         $uri = bluesky_get_uri($activity);
600         Item::update(['extid' => $uri], ['id' => $item['id']]);
601         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $activity]);
602 }
603
604 function bluesky_create_post(array $item, stdClass $root = null, stdClass $parent = null)
605 {
606         $uid = $item['uid'];
607         $token = bluesky_get_token($uid);
608         if (empty($token)) {
609                 return;
610         }
611
612         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
613         $urls = bluesky_get_urls(Post\Media::removeFromBody($item['body']));
614         $item['body'] = $urls['body'];
615
616         $msg = Plaintext::getPost($item, 300, false, BBCode::BLUESKY);
617         foreach ($msg['parts'] as $key => $part) {
618
619                 $facets = bluesky_get_facets($part, $urls['urls']);
620
621                 $record = [
622                         'text'      => $facets['body'],
623                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
624                         '$type'     => 'app.bsky.feed.post'
625                 ];
626
627                 if (!empty($facets['facets'])) {
628                         $record['facets'] = $facets['facets'];
629                 }
630
631                 if (!empty($root)) {
632                         $record['reply'] = ['root' => $root, 'parent' => $parent];
633                 }
634
635                 if ($key == count($msg['parts']) - 1) {
636                         $record = bluesky_add_embed($uid, $msg, $record);
637                 }
638
639                 $post = [
640                         'collection' => 'app.bsky.feed.post',
641                         'repo'       => $did,
642                         'record'     => $record
643                 ];
644
645                 $parent = bluesky_xrpc_post($uid, 'com.atproto.repo.createRecord', $post);
646                 if (empty($parent)) {
647                         return;
648                 }
649                 Logger::debug('Posting done', ['return' => $parent]);
650                 if (empty($root)) {
651                         $root = $parent;
652                 }
653                 if (($key == 0) && ($item['gravity'] != Item::GRAVITY_PARENT)) {
654                         $uri = bluesky_get_uri($parent);
655                         Item::update(['extid' => $uri], ['id' => $item['id']]);
656                         Logger::debug('Set extid', ['id' => $item['id'], 'extid' => $uri]);
657                 }
658         }
659 }
660
661 function bluesky_get_urls(string $body): array
662 {
663         // Remove all hashtag and mention links
664         $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $body);
665
666         $urls = [];
667
668         // Search for pure links
669         if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
670                 foreach ($matches as $match) {
671                         $text = Strings::getStyledURL($match[1]);
672                         $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
673                         $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
674                         $body = str_replace($match[0], $hash, $body);
675                 }
676         }
677
678         // Search for links with descriptions
679         if (preg_match_all("/\[url\=(https?:.*?)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER)) {
680                 foreach ($matches as $match) {
681                         if ($match[1] == $match[2]) {
682                                 $text = Strings::getStyledURL($match[1]);
683                         } else {
684                                 $text = $match[2];
685                         }
686                         if (mb_strlen($text) < 100) {
687                                 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
688                                 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
689                                 $body = str_replace($match[0], $hash, $body);
690                         } else {
691                                 $text = Strings::getStyledURL($match[1]);
692                                 $hash = bluesky_get_hash_for_url($match[0], mb_strlen($text));
693                                 $urls[] = ['url' => $match[1], 'text' => $text, 'hash' => $hash];
694                                 $body = str_replace($match[0], $text . ' ' . $hash, $body);
695                         }
696                 }
697         }
698
699         return ['body' => $body, 'urls' => $urls];
700 }
701
702 function bluesky_get_hash_for_url(string $text, int $linklength): string
703 {
704         if ($linklength <= 10) {
705                 return '|' . hash('crc32', $text) . '|';
706         }
707         return substr('|' . hash('crc32', $text) . base64_encode($text), 0, $linklength - 2) . '|';
708 }
709
710 function bluesky_get_facets(string $body, array $urls): array
711 {
712         $facets = [];
713
714         foreach ($urls as $url) {
715                 $pos = strpos($body, $url['hash']);
716                 if ($pos === false) {
717                         continue;
718                 }
719                 if ($pos > 0) {
720                         $prefix = substr($body, 0, $pos);
721                 } else {
722                         $prefix = '';
723                 }
724
725                 $body = $prefix . $url['text'] . substr($body, $pos + strlen($url['hash']));
726
727                 $facet = new stdClass;
728                 $facet->index = new stdClass;
729                 $facet->index->byteEnd   = $pos + strlen($url['text']);
730                 $facet->index->byteStart = $pos;
731
732                 $feature = new stdClass;
733                 $feature->uri = $url['url'];
734                 $type = '$type';
735                 $feature->$type = 'app.bsky.richtext.facet#link';
736
737                 $facet->features = [$feature];
738                 $facets[] = $facet;
739         }
740
741         return ['facets' => $facets, 'body' => $body];
742 }
743
744 function bluesky_add_embed(int $uid, array $msg, array $record): array
745 {
746         if (($msg['type'] != 'link') && !empty($msg['images'])) {
747                 $images = [];
748                 foreach ($msg['images'] as $image) {
749                         $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
750                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
751                         $blob = bluesky_upload_blob($uid, $photo);
752                         if (!empty($blob) && count($images) < 4) {
753                                 $images[] = ['alt' => $image['description'] ?? '', 'image' => $blob];
754                         }
755                 }
756                 if (!empty($images)) {
757                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
758                 }
759         } elseif ($msg['type'] == 'link') {
760                 $record['embed'] = [
761                         '$type'    => 'app.bsky.embed.external',
762                         'external' => [
763                                 'uri'         => $msg['url'],
764                                 'title'       => $msg['title'] ?? '',
765                                 'description' => $msg['description'] ?? '',
766                         ]
767                 ];
768                 if (!empty($msg['image'])) {
769                         $photo = Photo::createPhotoForExternalResource($msg['image']);
770                         $blob = bluesky_upload_blob($uid, $photo);
771                         if (!empty($blob)) {
772                                 $record['embed']['external']['thumb'] = $blob;
773                         }
774                 }
775         }
776         return $record;
777 }
778
779 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
780 {
781         $content = Photo::getImageForPhoto($photo);
782         $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
783         if (empty($data)) {
784                 return null;
785         }
786
787         Logger::debug('Uploaded blob', ['return' => $data]);
788         return $data->blob;
789 }
790
791 function bluesky_delete_post(string $uri, int $uid)
792 {
793         $parts = bluesky_get_uri_parts($uri);
794         if (empty($parts)) {
795                 Logger::debug('No uri delected', ['uri' => $uri]);
796                 return;
797         }
798         bluesky_xrpc_post($uid, 'com.atproto.repo.deleteRecord', $parts);
799         Logger::debug('Deleted', ['parts' => $parts]);
800 }
801
802 function bluesky_fetch_timeline(int $uid)
803 {
804         $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getTimeline');
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         $data = bluesky_xrpc_get($uid, 'app.bsky.notification.listNotifications');
868         if (empty($data->notifications)) {
869                 return;
870         }
871         foreach ($data->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                                         $data = Item::insert($item);
887                                         Logger::debug('Got like', ['uid' => $uid, 'result' => $data, '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                                         $data = Item::insert($item);
901                                         Logger::debug('Got repost', ['uid' => $uid, 'result' => $data, '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                                 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
914                                 Logger::debug('Got mention', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
915                                 break;
916
917                         case 'reply':
918                                 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
919                                 Logger::debug('Got reply', ['uid' => $uid, 'result' => $data, 'uri' => $uri]);
920                                 break;
921
922                         case 'quote':
923                                 $data = bluesky_process_post($notification, $uid, Item::PR_PUSHED, 0);
924                                 Logger::debug('Got quote', ['uid' => $uid, 'result' => $data, '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_xrpc_get($uid, 'app.bsky.feed.getFeed', ['feed' => $feed]);
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                                 if (empty($embed->record->value)) {
1131                                         Logger::info('Record has got no value', ['record' => $embed->record]);
1132                                         break;
1133                                 }
1134                                 $shared = bluesky_get_header($embed->record, $uri, 0, $fetch_uid);
1135                                 $shared = bluesky_get_content($shared, $embed->record->value, $uri, $item['uid'], $level);
1136                                 if (!empty($shared)) {
1137                                         if (!empty($embed->record->embeds)) {
1138                                                 foreach ($embed->record->embeds as $single) {
1139                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1140                                                 }
1141                                         }
1142                                         $id = Item::insert($shared);
1143                                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
1144                                 }
1145                         }
1146                         if (!empty($shared)) {
1147                                 $item['quote-uri-id'] = $shared['uri-id'];
1148                         }
1149                         break;
1150
1151                 case 'app.bsky.embed.recordWithMedia#view':
1152                         $uri = bluesky_get_uri($embed->record->record);
1153                         $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
1154                         if (empty($shared)) {
1155                                 $shared = bluesky_get_header($embed->record->record, $uri, 0, $fetch_uid);
1156                                 $shared = bluesky_get_content($shared, $embed->record->record->value, $uri, $item['uid'], $level);
1157                                 if (!empty($shared)) {
1158                                         if (!empty($embed->record->record->embeds)) {
1159                                                 foreach ($embed->record->record->embeds as $single) {
1160                                                         $shared = bluesky_add_media($single, $shared, $fetch_uid, $level);
1161                                                 }
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
1172                         if (!empty($embed->media)) {
1173                                 bluesky_add_media($embed->media, $item, $fetch_uid, $level);
1174                         }
1175                         break;
1176
1177                 default:
1178                         Logger::notice('Unhandled embed type', ['type' => $embed->$type, 'embed' => $embed]);
1179                         break;
1180         }
1181         return $item;
1182 }
1183
1184 function bluesky_get_uri(stdClass $post): string
1185 {
1186         if (empty($post->cid)) {
1187                 Logger::info('Invalid URI', ['post' => $post, 'callstack' => System::callstack(10, 0, true)]);
1188                 return '';
1189         }
1190         return $post->uri . ':' . $post->cid;
1191 }
1192
1193 function bluesky_get_uri_class(string $uri): ?stdClass
1194 {
1195         if (empty($uri)) {
1196                 return null;
1197         }
1198
1199         $elements = explode(':', $uri);
1200         if (empty($elements) || ($elements[0] != 'at')) {
1201                 $post = Post::selectFirstPost(['extid'], ['uri' => $uri]);
1202                 return bluesky_get_uri_class($post['extid'] ?? '');
1203         }
1204
1205         $class = new stdClass;
1206
1207         $class->cid = array_pop($elements);
1208         $class->uri = implode(':', $elements);
1209
1210         if ((substr_count($class->uri, '/') == 2) && (substr_count($class->cid, '/') == 2)) {
1211                 $class->uri .= ':' . $class->cid;
1212                 $class->cid = '';
1213         }
1214
1215         return $class;
1216 }
1217
1218 function bluesky_get_uri_parts(string $uri): ?stdClass
1219 {
1220         $class = bluesky_get_uri_class($uri);
1221         if (empty($class)) {
1222                 return null;
1223         }
1224
1225         $parts = explode('/', substr($class->uri, 5));
1226
1227         $class = new stdClass;
1228
1229         $class->repo       = $parts[0];
1230         $class->collection = $parts[1];
1231         $class->rkey       = $parts[2];
1232
1233         return $class;
1234 }
1235
1236 function bluesky_fetch_missing_post(string $uri, int $uid, int $causer, int $level, string $fallback = ''): string
1237 {
1238         $fetched_uri = bluesky_fetch_post($uri, $uid);
1239         if (!empty($fetched_uri)) {
1240                 return $fetched_uri;
1241         }
1242
1243         if (++$level > 100) {
1244                 Logger::info('Recursion level too deep', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1245                 // When the level is too deep we will fallback to the parent uri.
1246                 // Allthough the threading won't be correct, we at least had stored all posts and won't try again 
1247                 return $fallback;
1248         }
1249
1250         $class = bluesky_get_uri_class($uri);
1251         $fetch_uri = $class->uri;
1252
1253         Logger::debug('Fetch missing post', ['level' => $level, 'uid' => $uid, 'uri' => $uri]);
1254         $data = bluesky_xrpc_get($uid, 'app.bsky.feed.getPostThread', ['uri' => $fetch_uri]);
1255         if (empty($data)) {
1256                 Logger::info('Thread was not fetched', ['level' => $level, 'uid' => $uid, 'uri' => $uri, 'fallback' => $fallback]);
1257                 return $fallback;
1258         }
1259         
1260         Logger::debug('Reply count', ['replies' => $data->thread->post->replyCount, 'level' => $level, 'uid' => $uid, 'uri' => $uri]); 
1261
1262         if ($causer != 0) {
1263                 $cdata = Contact::getPublicAndUserContactID($causer, $uid);
1264         } else {
1265                 $cdata = [];
1266         }
1267
1268         return bluesky_process_thread($data->thread, $uid, $cdata, $level);
1269 }
1270
1271 function bluesky_fetch_post(string $uri, int $uid): string
1272 {
1273         if (Post::exists(['uri' => $uri, 'uid' => [$uid, 0]])) {
1274                 Logger::debug('Post exists', ['uri' => $uri]);
1275                 return $uri;
1276         }
1277
1278         $reply = Post::selectFirst(['uri'], ['extid' => $uri, 'uid' => [$uid, 0]]);
1279         if (!empty($reply['uri'])) {
1280                 Logger::debug('Post with extid exists', ['uri' => $uri]);
1281                 return $reply['uri'];
1282         }
1283         return '';
1284 }
1285
1286 function bluesky_process_thread(stdClass $thread, int $uid, array $cdata, int $level): string
1287 {
1288         $uri = bluesky_get_uri($thread->post);
1289         $fetched_uri = bluesky_fetch_post($uri, $uid);
1290         if (empty($fetched_uri)) {
1291                 Logger::debug('Process missing post', ['uri' => $uri]);
1292                 $item = bluesky_get_header($thread->post, $uri, $uid, $uid);
1293                 $item = bluesky_get_content($item, $thread->post->record, $uri, $uid, $level);
1294                 if (!empty($item)) {
1295                         $item['post-reason'] = Item::PR_FETCHED;
1296
1297                         if (!empty($cdata['public'])) {
1298                                 $item['causer-id']   = $cdata['public'];
1299                         }
1300
1301                         if (!empty($thread->post->embed)) {
1302                                 $item = bluesky_add_media($thread->post->embed, $item, $uid, $level);
1303                         }
1304                         $id = Item::insert($item);
1305                         if (!$id) {
1306                                 Logger::info('Item has not not been stored', ['uri' => $uri]);
1307                                 return '';
1308                         }
1309                         Logger::debug('Stored item', ['id' => $id, 'uri' => $uri]);
1310                 } else {
1311                         Logger::info('Post has not not been fetched', ['uri' => $uri]);
1312                         return '';
1313                 }
1314         } else {
1315                 Logger::debug('Post exists', ['uri' => $uri]);
1316                 $uri = $fetched_uri;
1317         }
1318
1319         foreach ($thread->replies ?? [] as $reply) {
1320                 $reply_uri = bluesky_process_thread($reply, $uid, $cdata, $level);
1321                 Logger::debug('Reply has been processed', ['uri' => $uri, 'reply' => $reply_uri]);
1322         }
1323
1324         return $uri;
1325 }
1326
1327 function bluesky_get_contact(stdClass $author, int $uid, int $fetch_uid): array
1328 {
1329         $condition = ['network' => Protocol::BLUESKY, 'uid' => 0, 'url' => $author->did];
1330         $contact = Contact::selectFirst(['id', 'updated'], $condition);
1331
1332         $update = empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours');
1333
1334         $public_fields = $fields = bluesky_get_contact_fields($author, $fetch_uid, $update);
1335
1336         $public_fields['uid'] = 0;
1337         $public_fields['rel'] = Contact::NOTHING;
1338
1339         if (empty($contact)) {
1340                 $cid = Contact::insert($public_fields);
1341         } else {
1342                 $cid = $contact['id'];
1343                 Contact::update($public_fields, ['id' => $cid], true);
1344         }
1345
1346         if ($uid != 0) {
1347                 $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
1348
1349                 $contact = Contact::selectFirst(['id', 'rel', 'uid'], $condition);
1350                 if (!isset($fields['rel']) && isset($contact['rel'])) {
1351                         $fields['rel'] = $contact['rel'];
1352                 } elseif (!isset($fields['rel'])) {
1353                         $fields['rel'] = Contact::NOTHING;
1354                 }
1355         }
1356
1357         if (($uid != 0) && ($fields['rel'] != Contact::NOTHING)) {
1358                 if (empty($contact)) {
1359                         $cid = Contact::insert($fields);
1360                 } else {
1361                         $cid = $contact['id'];
1362                         Contact::update($fields, ['id' => $cid], true);
1363                 }
1364                 Logger::debug('Get user contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1365         } else {
1366                 Logger::debug('Get public contact', ['id' => $cid, 'uid' => $uid, 'update' => $update]);
1367         }
1368         if (!empty($author->avatar)) {
1369                 Contact::updateAvatar($cid, $author->avatar);
1370         }
1371
1372         return Contact::getById($cid);
1373 }
1374
1375 function bluesky_get_contact_fields(stdClass $author, int $uid, bool $update): array
1376 {
1377         $fields = [
1378                 'uid'      => $uid,
1379                 'network'  => Protocol::BLUESKY,
1380                 'priority' => 1,
1381                 'writable' => true,
1382                 'blocked'  => false,
1383                 'readonly' => false,
1384                 'pending'  => false,
1385                 'baseurl'  => BLUESKY_HOST,
1386                 'url'      => $author->did,
1387                 'nurl'     => $author->did,
1388                 'alias'    => BLUESKY_HOST . '/profile/' . $author->handle,
1389                 'name'     => $author->displayName ?? $author->handle,
1390                 'nick'     => $author->handle,
1391                 'addr'     => $author->handle,
1392         ];
1393
1394         if (!$update) {
1395                 Logger::debug('Got contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1396                 return $fields;
1397         }
1398
1399         $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getProfile', ['actor' => $author->did]);
1400         if (empty($data)) {
1401                 Logger::debug('Error fetching contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1402                 return $fields;
1403         }
1404
1405         $fields['updated'] = DateTimeFormat::utcNow(DateTimeFormat::MYSQL);
1406
1407         if (!empty($data->description)) {
1408                 $fields['about'] = HTML::toBBCode($data->description);
1409         }
1410
1411         if (!empty($data->banner)) {
1412                 $fields['header'] = $data->banner;
1413         }
1414
1415         if (!empty($data->viewer)) {
1416                 if (!empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1417                         $fields['rel'] = Contact::FRIEND;
1418                 } elseif (!empty($data->viewer->following) && empty($data->viewer->followedBy)) {
1419                         $fields['rel'] = Contact::SHARING;
1420                 } elseif (empty($data->viewer->following) && !empty($data->viewer->followedBy)) {
1421                         $fields['rel'] = Contact::FOLLOWER;
1422                 } else {
1423                         $fields['rel'] = Contact::NOTHING;
1424                 }
1425         }
1426
1427         Logger::debug('Got updated contact fields', ['uid' => $uid, 'url' => $fields['url']]);
1428         return $fields;
1429 }
1430
1431 function bluesky_get_feeds(int $uid): array
1432 {
1433         $type = '$type';
1434         $preferences = bluesky_get_preferences($uid);
1435         foreach ($preferences->preferences as $preference) {
1436                 if ($preference->$type == 'app.bsky.actor.defs#savedFeedsPref') {
1437                         return $preference->pinned ?? [];
1438                 }
1439         }
1440         return [];
1441 }
1442
1443 function bluesky_get_preferences(int $uid): stdClass
1444 {
1445         $cachekey = 'bluesky:preferences:' . $uid;
1446         $data = DI::cache()->get($cachekey);
1447         if (!is_null($data)) {
1448                 return $data;
1449         }
1450
1451         $data = bluesky_xrpc_get($uid, 'app.bsky.actor.getPreferences');
1452
1453         DI::cache()->set($cachekey, $data, Duration::HOUR);
1454         return $data;
1455 }
1456
1457 function bluesky_get_did(int $uid, string $handle): string
1458 {
1459         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . urlencode($handle));
1460         if (empty($data)) {
1461                 return '';
1462         }
1463         Logger::debug('Got DID', ['return' => $data]);
1464         return $data->did;
1465 }
1466
1467 function bluesky_get_token(int $uid): string
1468 {
1469         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
1470         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
1471         if (empty($token)) {
1472                 return '';
1473         }
1474
1475         if ($created + 300 < time()) {
1476                 return bluesky_refresh_token($uid);
1477         }
1478         return $token;
1479 }
1480
1481 function bluesky_refresh_token(int $uid): string
1482 {
1483         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
1484
1485         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
1486         if (empty($data)) {
1487                 return '';
1488         }
1489
1490         Logger::debug('Refreshed token', ['return' => $data]);
1491         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1492         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1493         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1494         return $data->accessJwt;
1495 }
1496
1497 function bluesky_create_token(int $uid, string $password): string
1498 {
1499         $did = DI::pConfig()->get($uid, 'bluesky', 'did');
1500
1501         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
1502         if (empty($data)) {
1503                 return '';
1504         }
1505
1506         Logger::debug('Created token', ['return' => $data]);
1507         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
1508         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
1509         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
1510         return $data->accessJwt;
1511 }
1512
1513 function bluesky_xrpc_post(int $uid, string $url, $parameters): ?stdClass
1514 {
1515         return bluesky_post($uid, '/xrpc/' . $url, json_encode($parameters),  ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
1516 }
1517
1518 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
1519 {
1520         try {
1521                 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
1522         } catch (\Exception $e) {
1523                 Logger::notice('Exception on post', ['exception' => $e]);
1524                 return null;
1525         }
1526
1527         if (!$curlResult->isSuccess()) {
1528                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1529                 return null;
1530         }
1531
1532         return json_decode($curlResult->getBody());
1533 }
1534
1535 function bluesky_xrpc_get(int $uid, string $url, array $parameters = []): ?stdClass
1536 {
1537         if (!empty($parameters)) {
1538                 $url .= '?' . http_build_query($parameters);
1539         }
1540
1541         return bluesky_get($uid, '/xrpc/' . $url, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
1542 }
1543
1544 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
1545 {
1546         try {
1547                 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
1548         } catch (\Exception $e) {
1549                 Logger::notice('Exception on get', ['exception' => $e]);
1550                 return null;
1551         }
1552
1553         if (!$curlResult->isSuccess()) {
1554                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
1555                 return null;
1556         }
1557
1558         return json_decode($curlResult->getBody());
1559 }