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