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