]> git.mxchange.org Git - friendica-addons.git/blob - bluesky/bluesky.php
Bluesky: Basic connector for Bluesky is added
[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
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;
15 use Friendica\DI;
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;
21
22 function bluesky_install()
23 {
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');
31 }
32
33 function bluesky_load_config(ConfigFileManager $loader)
34 {
35         DI::app()->getConfigCache()->load($loader->loadAddonConfig('bluesky'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
36 }
37
38 function bluesky_settings(array &$data)
39 {
40         if (!DI::userSession()->getLocalUserId()) {
41                 return;
42         }
43
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');
50
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'), ''],
60         ]);
61
62         $data = [
63                 'connector' => 'bluesky',
64                 'title'     => DI::l10n()->t('Bluesky Export'),
65                 'image'     => 'images/bluesky.jpg',
66                 'enabled'   => $enabled,
67                 'html'      => $html,
68         ];
69 }
70
71 function bluesky_settings_post(array &$b)
72 {
73         if (empty($_POST['bluesky-submit'])) {
74                 return;
75         }
76
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');
80
81         $host   = $_POST['bluesky_host'];
82         $handle = $_POST['bluesky_handle'];
83
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']);
89
90         if (!empty($_POST['bluesky_password'])) {
91                 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'bluesky', 'app_password', $_POST['bluesky_password']);
92         }
93
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()));
97                 }
98         } else {
99                 DI::pConfig()->delete(DI::userSession()->getLocalUserId(), 'bluesky', 'did');
100         }
101 }
102
103 function bluesky_jot_nets(array &$jotnets_fields)
104 {
105         if (!DI::userSession()->getLocalUserId()) {
106                 return;
107         }
108
109         if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post')) {
110                 $jotnets_fields[] = [
111                         'type'  => 'checkbox',
112                         'field' => [
113                                 'bluesky_enable',
114                                 DI::l10n()->t('Post to Bluesky'),
115                                 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'bluesky', 'post_by_default')
116                         ]
117                 ];
118         }
119 }
120
121 function bluesky_hook_fork(array &$b)
122 {
123         if ($b['name'] != 'notifier_normal') {
124                 return;
125         }
126
127         $post = $b['data'];
128
129         if (($post['created'] !== $post['edited']) && !$post['deleted']) {
130                 DI::logger()->info('Editing is not supported by the addon');
131                 $b['execute'] = false;
132                 return;
133         }
134
135         if (!strstr($post['postopts'] ?? '', 'bluesky') || ($post['parent'] != $post['id']) || $post['private']) {
136                 $b['execute'] = false;
137                 return;
138         }
139 }
140
141 function bluesky_post_local(array &$b)
142 {
143         if ($b['edit']) {
144                 return;
145         }
146
147         if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
148                 return;
149         }
150
151         if ($b['private'] || $b['parent']) {
152                 return;
153         }
154
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);
157
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'))) {
160                 $bluesky_enable = 1;
161         }
162
163         if (!$bluesky_enable) {
164                 return;
165         }
166
167         if (strlen($b['postopts'])) {
168                 $b['postopts'] .= ',';
169         }
170
171         $b['postopts'] .= 'bluesky';
172 }
173
174 function bluesky_send(array &$b)
175 {
176         if (($b['created'] !== $b['edited']) && !$b['deleted']) {
177                 return;
178         }
179
180         if ($b['gravity'] != Item::GRAVITY_PARENT) {
181                 return;
182         } elseif ($b['private'] || !strstr($b['postopts'], 'bluesky')) {
183                 return;
184         }
185
186         bluesky_create_post($b);
187 }
188
189 function bluesky_create_post(array $item)
190 {
191         $uid = $item['uid'];
192         $token = bluesky_get_token($uid);
193         if (empty($token)) {
194                 return;
195         }
196
197         $did  = DI::pConfig()->get($uid, 'bluesky', 'did');
198
199         $msg = Plaintext::getPost($item, 300, false, BBCode::CONNECTORS);
200         $parent = $root = [];
201         foreach ($msg['parts'] as $key => $part) {
202                 $record = [
203                         'text'      => $part,
204                         'createdAt' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
205                         '$type'     => 'app.bsky.feed.post'
206                 ];
207
208                 if (!empty($root)) {
209                         $record['reply'] = ['root' => $root, 'parent' => $parent];
210                 }
211
212                 if ($key == count($msg['parts']) - 1) {
213                         $record = bluesky_add_embed($uid, $msg, $record);
214                 }
215
216                 $post = [
217                         'collection' => 'app.bsky.feed.post',
218                         'repo'       => $did,
219                         'record'     => $record
220                 ];
221
222                 $parent = bluesky_post($uid, '/xrpc/com.atproto.repo.createRecord', json_encode($post), ['Content-type' => 'application/json', 'Authorization' => ['Bearer ' . $token]]);
223                 if (empty($parent)) {
224                         return;
225                 }
226                 Logger::debug('Posting done', ['return' => $parent]);
227                 if (empty($root)) {
228                         $root = $parent;
229                 }
230         }
231 }
232
233 function bluesky_add_embed(int $uid, array $msg, array $record): array
234 {
235         if (($msg['type'] != 'link') && !empty($msg['images'])) {
236                 $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);
241                         if (!empty($blob)) {
242                                 $images[] = ['alt' => $image['description'], 'image' => $blob];
243                         }
244                 }
245                 if (!empty($images)) {
246                         $record['embed'] = ['$type' => 'app.bsky.embed.images', 'images' => $images];
247                 }
248         } elseif ($msg['type'] == 'link') {
249                 $record['embed'] = [
250                         '$type'    => 'app.bsky.embed.external',
251                         'external' => [
252                                 'uri'         => $msg['url'],
253                                 'title'       => $msg['title'],
254                                 'description' => $msg['description'],
255                         ]
256                 ];
257                 if (!empty($msg['image'])) {
258                         $photo = Photo::createPhotoForExternalResource($msg['image']);
259                         $blob = bluesky_upload_blob($uid, $photo);
260                         if (!empty($blob)) {
261                                 $record['embed']['external']['thumb'] = $blob;
262                         }
263                 }
264         }
265         return $record;
266 }
267
268 function bluesky_upload_blob(int $uid, array $photo): ?stdClass
269 {
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)]]);
272         if (empty($data)) {
273                 return null;
274         }
275
276         Logger::debug('Uploaded blob', ['return' => $data]);
277         return $data->blob;
278 }
279
280 function bluesky_get_timeline(int $uid)
281 {
282         $data = bluesky_get($uid, '/xrpc/app.bsky.feed.getTimeline', HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . bluesky_get_token($uid)]]]);
283         if (empty($data)) {
284                 return;
285         }
286         // TODO Add Functionality to read the timeline
287 }
288
289 function bluesky_get_did(int $uid): string
290 {
291         $data = bluesky_get($uid, '/xrpc/com.atproto.identity.resolveHandle?handle=' . DI::pConfig()->get($uid, 'bluesky', 'handle'));
292         if (empty($data)) {
293                 return '';
294         }
295         Logger::debug('Got DID', ['return' => $data]);
296         return $data->did;
297 }
298
299 function bluesky_get_token(int $uid): string
300 {
301         $token   = DI::pConfig()->get($uid, 'bluesky', 'access_token');
302         $created = DI::pConfig()->get($uid, 'bluesky', 'token_created');
303         if (empty($token)) {
304                 return bluesky_create_token($uid);
305         }
306
307         if ($created + 300 < time()) {
308                 return bluesky_refresh_token($uid);
309         }
310         return $token;
311 }
312
313 function bluesky_refresh_token(int $uid): string
314 {
315         $token = DI::pConfig()->get($uid, 'bluesky', 'refresh_token');
316
317         $data = bluesky_post($uid, '/xrpc/com.atproto.server.refreshSession', '', ['Authorization' => ['Bearer ' . $token]]);
318         if (empty($data)) {
319                 return '';
320         }
321
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;
327 }
328
329 function bluesky_create_token(int $uid): string
330 {
331         $did      = DI::pConfig()->get($uid, 'bluesky', 'did');
332         $password = DI::pConfig()->get($uid, 'bluesky', 'app_password');
333
334         $data = bluesky_post($uid, '/xrpc/com.atproto.server.createSession', json_encode(['identifier' => $did, 'password' => $password]), ['Content-type' => 'application/json']);
335         if (empty($data)) {
336                 return '';
337         }
338
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;
344 }
345
346 function bluesky_post(int $uid, string $url, string $params, array $headers): ?stdClass
347 {
348         try {
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]);
352                 return null;
353         }
354
355         if (!$curlResult->isSuccess()) {
356                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
357                 return null;
358         }
359
360         return json_decode($curlResult->getBody());
361 }
362
363 function bluesky_get(int $uid, string $url, string $accept_content = HttpClientAccept::DEFAULT, array $opts = []): ?stdClass
364 {
365         try {
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]);
369                 return null;
370         }
371
372         if (!$curlResult->isSuccess()) {
373                 Logger::notice('API Error', ['error' => json_decode($curlResult->getBody()) ?: $curlResult->getBody()]);
374                 return null;
375         }
376
377         return json_decode($curlResult->getBody());
378 }