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