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