3 * Name: Bluesky Connector
4 * Description: Post to Bluesky
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\Plaintext;
11 use Friendica\Core\Config\Util\ConfigFileManager;
12 use Friendica\Core\Hook;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Renderer;
16 use Friendica\Model\Item;
17 use Friendica\Model\Photo;
18 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
19 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
20 use Friendica\Util\DateTimeFormat;
22 function bluesky_install()
24 Hook::register('load_config', __FILE__, 'bluesky_load_config');
25 Hook::register('hook_fork', __FILE__, 'bluesky_hook_fork');
26 Hook::register('post_local', __FILE__, 'bluesky_post_local');
27 Hook::register('notifier_normal', __FILE__, 'bluesky_send');
28 Hook::register('jot_networks', __FILE__, 'bluesky_jot_nets');
29 Hook::register('connector_settings', __FILE__, 'bluesky_settings');
30 Hook::register('connector_settings_post', __FILE__, 'bluesky_settings_post');
33 function bluesky_load_config(ConfigFileManager $loader)
35 DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
38 function bluesky_settings(array &$data)
40 if (!DI::userSession()->getLocalUserId()) {
44 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post') ?? false;
45 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default') ?? false;
46 $host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host') ?: 'https://bsky.social';
47 $handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
48 $did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
49 $token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'access_token');
51 $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.');
53 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
54 $html = Renderer::replaceMacros($t, [
55 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
56 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
57 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', 'readonly'],
58 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
59 '$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'],
60 '$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.")],
65 'connector' => 'bluesky',
66 'title' => DI::l10n()->t('Bluesky Export'),
67 'image' => 'images/bluesky.jpg',
68 'enabled' => $enabled,
73 function bluesky_settings_post(array &$b)
75 if (empty($_POST['bluesky-submit'])) {
79 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
80 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
81 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
83 $host = $_POST['bluesky_host'];
84 $handle = $_POST['bluesky_handle'];
86 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
87 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
88 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
89 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
91 if (!empty($host) && !empty($handle)) {
92 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
93 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId()));
96 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
99 if (!empty($_POST['bluesky_password'])) {
100 bluesky_create_token(DI::userSession()->getLocalUserId(), $_POST['bluesky_password']);
105 function bluesky_jot_nets(array &$jotnets_fields)
107 if (!DI::userSession()->getLocalUserId()) {
111 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
112 $jotnets_fields[] = [
113 'type' => 'checkbox',
116 DI::l10n()->t('Post to Bluesky'),
117 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
123 function bluesky_hook_fork(array &$b)
125 if ($b['name'] != 'notifier_normal') {
131 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
132 DI::logger()->info('Editing is not supported by the addon');
133 $b['execute'] = false;
137 if (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
138 $b['execute'] = false;
143 function bluesky_post_local(array &$b)
149 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
153 if ($b['private'] || $b['parent']) {
157 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
158 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
160 // if API is used, default to the chosen settings
161 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
165 if (!$bluesky_enable) {
169 if (strlen($b['postopts'])) {
170 $b['postopts'] .= ',';
173 $b['postopts'] .= 'bluesky';
176 function bluesky_send(array &$b)
178 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
182 if ($b['gravity'] != Item::GRAVITY_PARENT) {
184 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
188 bluesky_create_post($b);
191 function bluesky_create_post(array $item)
194 $token = bluesky_get_token($uid);
199 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
201 $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
202 $parent = $root = [];
203 foreach ($msg['parts'] as $key => $part) {
206 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
207 '$type' => 'app.bsky.feed.post'
211 $record['reply'] = ['root' => $root, 'parent' => $parent];
214 if ($key == count($msg['parts']) - 1) {
215 $record = bluesky_add_embed($uid, $msg, $record);
219 'collection' => 'app.bsky.feed.post',
224 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
225 if (empty($parent)) {
228 Logger::debug('Posting done', ['return' => $parent]);
235 function bluesky_add_embed(int $uid, array $msg, array $record): array
237 if (($msg['type'] != 'link') && !empty($msg['images'])) {
239 foreach ($msg['images'] as $image) {
240 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
241 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
242 $blob = bluesky_upload_blob($uid, $photo);
244 $images[] = ['alt' => $image['description'], 'image' => $blob];
247 if (!empty($images)) {
248 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
250 } elseif ($msg['type'] == 'link') {
252 '$type' => 'app.bsky.embed.external',
254 'uri' => $msg['url'],
255 'title' => $msg['title'],
256 'description' => $msg['description'],
259 if (!empty($msg['image'])) {
260 $photo = Photo::createPhotoForExternalResource($msg['image']);
261 $blob = bluesky_upload_blob($uid, $photo);
263 $record['embed']['external']['thumb'] = $blob;
270 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
272 $content = Photo::getImageForPhoto($photo);
273 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
278 Logger::debug('Uploaded blob', ['return' => $data]);
282 function bluesky_get_timeline(int $uid)
284 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
288 // TODO Add Functionality to read the timeline
291 function bluesky_get_did(int $uid): string
293 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
297 Logger::debug('Got DID', ['return' => $data]);
301 function bluesky_get_token(int $uid): string
303 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
304 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
309 if ($created + 300 < time()) {
310 return bluesky_refresh_token($uid);
315 function bluesky_refresh_token(int $uid): string
317 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
319 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
324 Logger::debug('Refreshed token', ['return' => $data]);
325 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
326 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
327 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
328 return $data->accessJwt;
331 function bluesky_create_token(int $uid, string $password): string
333 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
335 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
340 Logger::debug('Created token', ['return' => $data]);
341 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
342 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
343 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
344 return $data->accessJwt;
347 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
350 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
351 } catch (\Exception $e) {
352 Logger::notice('Exception on post', ['exception' => $e]);
356 if (!$curlResult->isSuccess()) {
357 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
361 return json_decode($curlResult->getBody());
364 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
367 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
368 } catch (\Exception $e) {
369 Logger::notice('Exception on get', ['exception' => $e]);
373 if (!$curlResult->isSuccess()) {
374 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
378 return json_decode($curlResult->getBody());