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 $username = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'username');
51 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/bluesky/');
52 $html = Renderer::replaceMacros($t, [
53 '$enable' => ['bluesky', DI::l10n()->t('Enable Bluesky Post Addon'), $enabled],
54 '$bydefault' => ['bluesky_bydefault', DI::l10n()->t('Post to Bluesky by default'), $def_enabled],
55 '$host' => ['bluesky_host', DI::l10n()->t('Bluesky host'), $host, '', '', '', 'url'],
56 '$handle' => ['bluesky_handle', DI::l10n()->t('Bluesky handle'), $handle],
57 '$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'],
58 '$username' => ['bluesky_username', DI::l10n()->t('Bluesky app username'), $username, DI::l10n()->t("Please don't add your real username here, but instead create a specific app username and app password in the Bluesky settings.")],
59 '$password' => ['bluesky_password', DI::l10n()->t('Bluesky app password'), ''],
63 'connector' => 'bluesky',
64 'title' => DI::l10n()->t('Bluesky Export'),
65 'image' => 'images/bluesky.jpg',
66 'enabled' => $enabled,
71 function bluesky_settings_post(array &$b)
73 if (empty($_POST['bluesky-submit'])) {
77 $old_host = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'host');
78 $old_handle = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'handle');
79 $old_did = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
81 $host = $_POST['bluesky_host'];
82 $handle = $_POST['bluesky_handle'];
84 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post', intval($_POST['bluesky']));
85 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default', intval($_POST['bluesky_bydefault']));
86 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'host', $host);
87 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'handle', $handle);
88 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'username', $_POST['bluesky_username']);
90 if (!empty($_POST['bluesky_password'])) {
91 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'app_password', $_POST['bluesky_password']);
94 if (!empty($host) && !empty($handle)) {
95 if (empty($old_did) || $old_host != $host || $old_handle != $handle) {
96 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'did', bluesky_get_did(DI::userSession()->getLocalUserId()));
99 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
103 function bluesky_jot_nets(array &$jotnets_fields)
105 if (!DI::userSession()->getLocalUserId()) {
109 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
110 $jotnets_fields[] = [
111 'type' => 'checkbox',
114 DI::l10n()->t('Post to Bluesky'),
115 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
121 function bluesky_hook_fork(array &$b)
123 if ($b['name'] != 'notifier_normal') {
129 if (($post['created'] !== $post['edited']) && !$post['deleted']) {
130 DI::logger()->info('Editing is not supported by the addon');
131 $b['execute'] = false;
135 if (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
136 $b['execute'] = false;
141 function bluesky_post_local(array &$b)
147 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
151 if ($b['private'] || $b['parent']) {
155 $bluesky_post = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post'));
156 $bluesky_enable = (($bluesky_post && !empty($_REQUEST['bluesky_enable'])) ? intval($_REQUEST['bluesky_enable']) : 0);
158 // if API is used, default to the chosen settings
159 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default'))) {
163 if (!$bluesky_enable) {
167 if (strlen($b['postopts'])) {
168 $b['postopts'] .= ',';
171 $b['postopts'] .= 'bluesky';
174 function bluesky_send(array &$b)
176 if (($b['created'] !== $b['edited']) && !$b['deleted']) {
180 if ($b['gravity'] != Item::GRAVITY_PARENT) {
182 } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
186 bluesky_create_post($b);
189 function bluesky_create_post(array $item)
192 $token = bluesky_get_token($uid);
197 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
199 $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
200 $parent = $root = [];
201 foreach ($msg['parts'] as $key => $part) {
204 'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
205 '$type' => 'app.bsky.feed.post'
209 $record['reply'] = ['root' => $root, 'parent' => $parent];
212 if ($key == count($msg['parts']) - 1) {
213 $record = bluesky_add_embed($uid, $msg, $record);
217 'collection' => 'app.bsky.feed.post',
222 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
223 if (empty($parent)) {
226 Logger::debug('Posting done', ['return' => $parent]);
233 function bluesky_add_embed(int $uid, array $msg, array $record): array
235 if (($msg['type'] != 'link') && !empty($msg['images'])) {
237 foreach ($msg['images'] as $image) {
238 $photo = Photo::selectFirst(['resource-id'], ['id' => $image['id']]);
239 $photo = Photo::selectFirst([], ["`resource-id` = ? AND `scale` > ?", $photo['resource-id'], 0], ['order' => ['scale']]);
240 $blob = bluesky_upload_blob($uid, $photo);
242 $images[] = ['alt' => $image['description'], 'image' => $blob];
245 if (!empty($images)) {
246 $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
248 } elseif ($msg['type'] == 'link') {
250 '$type' => 'app.bsky.embed.external',
252 'uri' => $msg['url'],
253 'title' => $msg['title'],
254 'description' => $msg['description'],
257 if (!empty($msg['image'])) {
258 $photo = Photo::createPhotoForExternalResource($msg['image']);
259 $blob = bluesky_upload_blob($uid, $photo);
261 $record['embed']['external']['thumb'] = $blob;
268 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
270 $content = Photo::getImageForPhoto($photo);
271 $data = bluesky_post($uid, '/xrpc/com.atproto.repo.uploadBlob', $content, ['Content-type' => $photo['type'], 'Authorization' => ['Bearer ' . bluesky_get_token($uid)]]);
276 Logger::debug('Uploaded blob', ['return' => $data]);
280 function bluesky_get_timeline(int $uid)
282 $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
286 // TODO Add Functionality to read the timeline
289 function bluesky_get_did(int $uid): string
291 $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
295 Logger::debug('Got DID', ['return' => $data]);
299 function bluesky_get_token(int $uid): string
301 $token = DI::pConfig()->get($uid, 'bluesky', 'access_token');
302 $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
304 return bluesky_create_token($uid);
307 if ($created + 300 < time()) {
308 return bluesky_refresh_token($uid);
313 function bluesky_refresh_token(int $uid): string
315 $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
317 $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
322 Logger::debug('Refreshed token', ['return' => $data]);
323 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
324 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
325 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
326 return $data->accessJwt;
329 function bluesky_create_token(int $uid): string
331 $did = DI::pConfig()->get($uid, 'bluesky', 'did');
332 $password = DI::pConfig()->get($uid, 'bluesky', 'app_password');
334 $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
339 Logger::debug('Created token', ['return' => $data]);
340 DI::pConfig()->set($uid, 'bluesky', 'access_token', $data->accessJwt);
341 DI::pConfig()->set($uid, 'bluesky', 'refresh_token', $data->refreshJwt);
342 DI::pConfig()->set($uid, 'bluesky', 'token_created', time());
343 return $data->accessJwt;
346 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
349 $curlResult = DI::httpClient()->post(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $params, $headers);
350 } catch (\Exception $e) {
351 Logger::notice('Exception on post', ['exception' => $e]);
355 if (!$curlResult->isSuccess()) {
356 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
360 return json_decode($curlResult->getBody());
363 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
366 $curlResult = DI::httpClient()->get(DI::pConfig()->get($uid, 'bluesky', 'host') . $url, $accept_content, $opts);
367 } catch (\Exception $e) {
368 Logger::notice('Exception on get', ['exception' => $e]);
372 if (!$curlResult->isSuccess()) {
373 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
377 return json_decode($curlResult->getBody());