]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
Bluesky: Import of remote timeline
[friendica-addons.git] / bluesky / bluesky.php
1 <?php
2 /**
3  * Name: Bluesky Connector
4  * Description: Post to Bluesky
5  * Version: 1.0
6  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
7  * 
8  * @todo
9  * - Process facets
10  * - detect incoming reshares
11  * - detect contact relations
12  * - alternate link for contacts
13  * - plink for posts
14  * - fetch missing posts
15  * - only fetch new posts
16  * - receive likes
17  *
18  * - create facets
19  * - transmit comments
20  * - transmits likes
21  * - transmit reshares
22  */
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Config\Util\ConfigFileManager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\ItemURI;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
40 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
41 use Friendica\Protocol\Activity;
42 use Friendica\Util\DateTimeFormat;
43
44 define('BLUESKY_DEFAULT_POLL_INTERVAL', 10); // given in minutes
45
46 function bluesky_install()
47 {
48         Hook::register('load_config',             __FILE__, 'bluesky_load_config');
49         Hook::register('hook_fork',               __FILE__, 'bluesky_hook_fork');
50         Hook::register('post_local',              __FILE__, 'bluesky_post_local');
51         Hook::register('notifier_normal',         __FILE__, 'bluesky_send');
52         Hook::register('jot_networks',            __FILE__, 'bluesky_jot_nets');
53         Hook::register('connector_settings',      __FILE__, 'bluesky_settings');
54         Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
55         Hook::register('cron',                    __FILE__, 'bluesky_cron');
56 }
57
58 function bluesky_load_config(ConfigFileManager $loader)
59 {
60         DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
61 }
62
63 function bluesky_settings(array &$data)
64 {
65         if (!DI::userSession()->getLocalUserId()) {
66                 return;
67         }
68
69         $enabled     = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
70         $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
71         $host        = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
72         $handle      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
73         $did         = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
74         $token       = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
75         $import      = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'import') ?? false;
76
77         $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.');
78
79         $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
80         $html = Renderer::replaceMacros($t, [
81                 '$enable'    => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
82                 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
83                 '$import'    => ['bluesky_import', DI::l10n()->t('Import the remote timeline'), $import],
84                 '$host'      => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
85                 '$handle'    => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
86                 '$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'],
87                 '$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.")],
88                 '$status'    => $status
89         ]);
90
91         $data = [
92                 'connector' => 'bluesky',
93                 'title'     => DI::l10n()->t('Bluesky Export'),
94                 'image'     => 'images/bluesky.jpg',
95                 'enabled'   => $enabled,
96                 'html'      => $html,
97         ];
98 }
99
100 function bluesky_settings_post(array &$b)
101 {
102         if (empty($_POST['bluesky-submit'])) {
103                 return;
104         }
105
106         $old_host   = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
107         $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
108         $old_did    = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
109
110         $host   = $_POST['bluesky_host'];
111         $handle = $_POST['bluesky_handle'];
112
113         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post',            intval($_POST['bluesky']));
114         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
115         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host',            $host);
116         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle',          $handle);
117         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'import',          intval($_POST['bluesky_import']));
118
119         if (!empty($host) && !empty($handle)) {
120                 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
121                         DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId()));
122                 }
123         } else {
124                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
125         }
126
127         if (!empty($_POST['bluesky_password'])) {
128                 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
129         }
130
131 }
132
133 function bluesky_jot_nets(array &$jotnets_fields)
134 {
135         if (!DI::userSession()->getLocalUserId()) {
136                 return;
137         }
138
139         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
140                 $jotnets_fields[] = [
141                         'type'  => 'checkbox',
142                         'field' => [
143                                 'bluesky_enable',
144                                 DI::l10n()->t('Post to Bluesky'),
145                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
146                         ]
147                 ];
148         }
149 }
150
151 function bluesky_cron()
152 {
153         $last = DI::keyValue()->get('bluesky_last_poll');
154
155         $poll_interval = intval(DI::config()->get('bluesky', 'poll_interval'));
156         if (!$poll_interval) {
157                 $poll_interval = BLUESKY_DEFAULT_POLL_INTERVAL;
158         }
159
160         if ($last) {
161                 $next = $last + ($poll_interval * 60);
162                 if ($next > time()) {
163                         Logger::notice('poll interval not reached');
164                         return;
165                 }
166         }
167         Logger::notice('cron_start');
168
169         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
170         if ($abandon_days < 1) {
171                 $abandon_days = 0;
172         }
173
174         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
175
176         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'bluesky', 'k' => 'import', 'v' => true]);
177         foreach ($pconfigs as $pconfig) {
178                 if ($abandon_days != 0) {
179                         if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $pconfig['uid'], $abandon_limit])) {
180                                 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $pconfig['uid']]);
181                                 continue;
182                         }
183                 }
184
185                 Logger::notice('importing timeline - start', ['user' => $pconfig['uid']]);
186                 bluesky_fetch_timeline($pconfig['uid']);
187                 Logger::notice('importing timeline - done', ['user' => $pconfig['uid']]);
188         }
189
190         Logger::notice('cron_end');
191
192         DI::keyValue()->set('bluesky_last_poll', time());
193 }
194
195 function bluesky_hook_fork(array &$b)
196 {
197         if ($b['name'] != 'notifier_normal') {
198                 return;
199         }
200
201         $post = $b['data'];
202
203         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
204                 DI::logger()->info('Editing is not supported by the addon');
205                 $b['execute'] = false;
206                 return;
207         }
208
209         if (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
210                 $b['execute'] = false;
211                 return;
212         }
213 }
214
215 function bluesky_post_local(array &$b)
216 {
217         if ($b['edit']) {
218                 return;
219         }
220
221         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
222                 return;
223         }
224
225         if ($b['private'] || $b['parent']) {
226                 return;
227         }
228
229         $bluesky_post   = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
230         $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
231
232         // if API is used, default to the chosen settings
233         if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
234                 $bluesky_enable = 1;
235         }
236
237         if (!$bluesky_enable) {
238                 return;
239         }
240
241         if (strlen($b['postopts'])) {
242                 $b['postopts'] .= ',';
243         }
244
245         $b['postopts'] .= 'bluesky';
246 }
247
248 function bluesky_send(array &$b)
249 {
250         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
251                 return;
252         }
253
254         if ($b['gravity'] != Item::GRAVITY_PARENT) {
255                 return;
256         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
257                 return;
258         }
259
260         bluesky_create_post($b);
261 }
262
263 function bluesky_create_post(array $item)
264 {
265         $uid = $item['uid'];
266         $token = bluesky_get_token($uid);
267         if (empty($token)) {
268                 return;
269         }
270
271         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
272
273         $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
274         $parent = $root = [];
275         foreach ($msg['parts'] as $key => $part) {
276                 $record = [
277                         'text'      => $part,
278                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279                         '$type'     => 'app.bsky.feed.post'
280                 ];
281
282                 if (!empty($root)) {
283                         $record['reply'] = ['root' => $root, 'parent' => $parent];
284                 }
285
286                 if ($key == count($msg['parts']) - 1) {
287                         $record = bluesky_add_embed($uid, $msg, $record);
288                 }
289
290                 $post = [
291                         'collection' => 'app.bsky.feed.post',
292                         'repo'       => $did,
293                         'record'     => $record
294                 ];
295
296                 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
297                 if (empty($parent)) {
298                         return;
299                 }
300                 Logger::debug('Posting done', ['return' => $parent]);
301                 if (empty($root)) {
302                         $root = $parent;
303                 }
304         }
305 }
306
307 function bluesky_add_embed(int $uid, array $msg, array $record): array
308 {
309         if (($msg['type'] != 'link') && !empty($msg['images'])) {
310                 $images = [];
311                 foreach ($msg['images'] as $image) {
312                         $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
313                         $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
314                         $blob = bluesky_upload_blob($uid, $photo);
315                         if (!empty($blob) && count($images) < 4) {
316                                 $images[] = ['alt' => $image['description'], 'image' => $blob];
317                         }
318                 }
319                 if (!empty($images)) {
320                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
321                 }
322         } elseif ($msg['type'] == 'link') {
323                 $record['embed'] = [
324                         '$type'    => 'app.bsky.embed.external',
325                         'external' => [
326                                 'uri'         => $msg['url'],
327                                 'title'       => $msg['title'],
328                                 'description' => $msg['description'],
329                         ]
330                 ];
331                 if (!empty($msg['image'])) {
332                         $photo = Photo::createPhotoForExternalResource($msg['image']);
333                         $blob = bluesky_upload_blob($uid, $photo);
334                         if (!empty($blob)) {
335                                 $record['embed']['external']['thumb'] = $blob;
336                         }
337                 }
338         }
339         return $record;
340 }
341
342 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
343 {
344         $content = Photo::getImageForPhoto($photo);
345         $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
346         if (empty($data)) {
347                 return null;
348         }
349
350         Logger::debug('Uploaded blob', ['return' => $data]);
351         return $data->blob;
352 }
353
354 function bluesky_fetch_timeline(int $uid)
355 {
356         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
357         if (empty($data)) {
358                 return;
359         }
360
361         if (empty($data->feed)) {
362                 return;
363         }
364
365         foreach (array_reverse($data->feed) as $entry) {
366                 Logger::debug('Importing post', ['uid' => $uid, 'indexedAt' => $entry->post->indexedAt, 'uri' => $entry->post->uri, 'cid' => $entry->post->cid]);
367
368                 bluesky_process_post($entry->post, $uid);
369         }
370
371         // @todo Support paging
372         // [cursor] => 1684670516000::bafyreidq3ilwslmlx72jf5vrk367xcc63s6lrhzlyup2bi3zwcvso6w2vi
373 }
374
375 function bluesky_process_post(stdClass $post, int $uid): int
376 {
377         $uri = bluesky_get_uri($post);
378
379         if (Post::exists(['uri' => $uri, 'uid' => $uid])) {
380                 return 0;
381         }
382
383         $item = bluesky_get_header($post, $uri, $uid);
384
385         $item = bluesky_get_content($item, $post->record);
386
387         if (!empty($post->embed)) {
388                 $item = bluesky_add_media($post->embed, $item);
389         }
390         return item::insert($item);
391 }
392
393 function bluesky_get_header(stdClass $post, string $uri, int $uid): array
394 {
395         $contact = bluesky_get_contact($post->author, $uid);
396         $item = [
397                 'network'       => Protocol::BLUESKY,
398                 'uid'           => $uid,
399                 'wall'          => false,
400                 'uri'           => $uri,
401                 'guid'          => $post->cid,
402                 'private'       => Item::UNLISTED,
403                 'verb'          => Activity::POST,
404                 'contact-id'    => $contact['id'],
405                 'author-name'   => $contact['name'],
406                 'author-link'   => $contact['url'],
407                 'author-avatar' => $contact['avatar'],
408                 // 'plink'         => '', @todo Path to a web representation
409         ];
410
411         $item['uri-id']       = ItemURI::getIdByURI($uri);
412         $item['owner-name']   = $item['author-name'];
413         $item['owner-link']   = $item['author-link'];
414         $item['owner-avatar'] = $item['author-avatar'];
415
416         return $item;
417 }
418
419 function bluesky_get_content(array $item, stdClass $record): array
420 {
421         if (!empty($record->reply)) {
422                 $item['parent']     = bluesky_get_uri($record->reply->root);
423                 $item['thr-parent'] = bluesky_get_uri($record->reply->parent);
424         }
425
426         $body = $record->text;
427
428         if (!empty($record->facets)) {
429                 // @todo add Links
430         }
431
432         $item['body']    = $body;
433         $item['created'] = DateTimeFormat::utc($record->createdAt, DateTimeFormat::MYSQL);
434         return $item;
435 }
436
437 function bluesky_add_media(stdClass $embed, array $item): array
438 {
439         if (!empty($embed->images)) {
440                 foreach ($embed->images as $image) {
441                         $media = [
442                                 'uri-id'      => $item['uri-id'],
443                                 'type'        => Post\Media::IMAGE,
444                                 'url'         => $image->fullsize,
445                                 'preview'     => $image->thumb,
446                                 'description' => $image->alt,
447                         ];
448                         Post\Media::insert($media);
449                 }
450         } elseif (!empty($embed->external)) {
451                 $media = ['uri-id' => $item['uri-id'],
452                         'type'        => Post\Media::HTML,
453                         'url'         => $embed->external->uri,
454                         'name'        => $embed->external->title,
455                         'description' => $embed->external->description,
456                 ];
457                 Post\Media::insert($media);
458         } elseif (!empty($embed->record)) {
459                 $uri = bluesky_get_uri($embed->record);
460                 $shared = Post::selectFirst(['uri-id'], ['uri' => $uri, 'uid' => $item['uid']]);
461                 if (empty($shared)) {
462                         $shared = bluesky_get_header($embed->record, $uri, 0);
463                         $shared = bluesky_get_content($shared, $embed->record->value);
464                 
465                         if (!empty($embed->record->embeds)) {
466                                 foreach ($embed->record->embeds as $single) {
467                                         $shared = bluesky_add_media($single, $shared);
468                                 }
469                         }
470                         $id = Item::insert($shared);
471                         $shared = Post::selectFirst(['uri-id'], ['id' => $id]);
472                 }
473                 if (!empty($shared)) {
474                         $item['quote-uri-id'] = $shared['uri-id'];
475                 }
476         } else {
477                 Logger::debug('Unsupported embed', ['embed' => $embed, 'item' => $item]);
478         }
479         return $item;
480 }
481
482 function bluesky_get_uri(stdClass $post): string
483 {
484         return $post->uri . ':' . $post->cid;
485
486 }
487 function bluesky_get_contact(stdClass $author, int $uid): array
488 {
489         $condition = ['network' => Protocol::BLUESKY, 'uid' => $uid, 'url' => $author->did];
490
491         $fields = [
492                 'name' => $author->displayName,
493                 'nick' => $author->handle,
494                 'addr' => $author->handle,
495         ];
496
497         $contact = Contact::selectFirst([], $condition);
498
499         if (empty($contact)) {
500                 $cid = bluesky_insert_contact($author, $uid);
501         } else {
502                 $cid = $contact['id'];
503                 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
504                         Contact::update($fields, ['id' => $cid]);
505                 }
506         }
507
508         $condition['uid'] = 0;
509
510         $contact = Contact::selectFirst([], $condition);
511         if (empty($contact)) {
512                 $pcid = bluesky_insert_contact($author, 0);
513         } else {
514                 $pcid = $contact['id'];
515                 if ($fields['name'] != $contact['name'] || $fields['nick'] != $contact['nick'] || $fields['addr'] != $contact['addr']) {
516                         Contact::update($fields, ['id' => $pcid]);
517                 }
518         }
519
520         if (!empty($author->avatar)) {
521                 Contact::updateAvatar($cid, $author->avatar);
522         }
523
524         if (empty($contact) || $contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
525                 bluesky_update_contact($author, $uid, $cid, $pcid);
526         }
527
528         return Contact::getById($cid);
529 }
530
531 function bluesky_insert_contact(stdClass $author, int $uid)
532 {
533         $fields = [
534                 'uid'      => $uid,
535                 'network'  => Protocol::BLUESKY,
536                 'priority' => 1,
537                 'writable' => true,
538                 'blocked'  => false,
539                 'readonly' => false,
540                 'pending'  => false,
541                 'url'      => $author->did,
542                 'nurl'     => $author->did,
543                 // 'alias'    => '', @todo Path to a web representation
544                 'name'     => $author->displayName,
545                 'nick'     => $author->handle,
546                 'addr'     => $author->handle,
547         ];
548         return Contact::insert($fields);
549 }
550
551 function bluesky_update_contact(stdClass $author, int $uid, int $cid, int $pcid)
552 {
553         $data = bluesky_get($uid, '/xrpc/app.bsky.actor.getProfile?actor=' . $author->did, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
554         if (empty($data)) {
555                 return;
556         }
557
558         $fields = [
559                 'name'    => $data->displayName,
560                 'nick'    => $data->handle,
561                 'addr'    => $data->handle,
562                 'about'   => HTML::toBBCode($data->description),
563                 'updated' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL),
564         ];
565
566         if (!empty($data->banner)) {
567                 $fields['header'] = $data->banner;
568         }
569
570         Contact::update($fields, ['id' => $cid]);
571         Contact::update($fields, ['id' => $pcid]);
572 }
573
574 function bluesky_get_did(int $uid): string
575 {
576         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
577         if (empty($data)) {
578                 return '';
579         }
580         Logger::debug('Got DID', ['return' => $data]);
581         return $data->did;
582 }
583
584 function bluesky_get_token(int $uid): string
585 {
586         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
587         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
588         if (empty($token)) {
589                 return '';
590         }
591
592         if ($created + 300 < time()) {
593                 return bluesky_refresh_token($uid);
594         }
595         return $token;
596 }
597
598 function bluesky_refresh_token(int $uid): string
599 {
600         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
601
602         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
603         if (empty($data)) {
604                 return '';
605         }
606
607         Logger::debug('Refreshed token', ['return' => $data]);
608         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
609         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
610         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
611         return $data->accessJwt;
612 }
613
614 function bluesky_create_token(int $uid, string $password): string
615 {
616         $did = DI::pConfig()->get($uid, 'bluesky', 'did');
617
618         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
619         if (empty($data)) {
620                 return '';
621         }
622
623         Logger::debug('Created token', ['return' => $data]);
624         DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
625         DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
626         DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
627         return $data->accessJwt;
628 }
629
630 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
631 {
632         try {
633                 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
634         } catch (\Exception $e) {
635                 Logger::notice('Exception on post', ['exception' => $e]);
636                 return null;
637         }
638
639         if (!$curlResult->isSuccess()) {
640                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
641                 return null;
642         }
643
644         return json_decode($curlResult->getBody());
645 }
646
647 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
648 {
649         try {
650                 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
651         } catch (\Exception $e) {
652                 Logger::notice('Exception on get', ['exception' => $e]);
653                 return null;
654         }
655
656         if (!$curlResult->isSuccess()) {
657                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
658                 return null;
659         }
660
661         return json_decode($curlResult->getBody());
662 }