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