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