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