]> git.mxchange.org Git - friendica.git/blob - src/Factory/Api/Mastodon/Status.php
Adding and removing of pictures via API is now possible
[friendica.git] / src / Factory / Api / Mastodon / Status.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Factory\Api\Mastodon;
23
24 use Friendica\BaseFactory;
25 use Friendica\Content\ContactSelector;
26 use Friendica\Content\Item as ContentItem;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\Model\Item;
32 use Friendica\Model\Post;
33 use Friendica\Model\Tag as TagModel;
34 use Friendica\Model\Verb;
35 use Friendica\Network\HTTPException;
36 use Friendica\Object\Api\Mastodon\Status\FriendicaDeliveryData;
37 use Friendica\Object\Api\Mastodon\Status\FriendicaExtension;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use ImagickException;
41 use Psr\Log\LoggerInterface;
42
43 class Status extends BaseFactory
44 {
45         /** @var Database */
46         private $dba;
47         /** @var Account */
48         private $mstdnAccountFactory;
49         /** @var Mention */
50         private $mstdnMentionFactory;
51         /** @var Tag */
52         private $mstdnTagFactory;
53         /** @var Card */
54         private $mstdnCardFactory;
55         /** @var Attachment */
56         private $mstdnAttachementFactory;
57         /** @var Error */
58         private $mstdnErrorFactory;
59         /** @var Poll */
60         private $mstdnPollFactory;
61         /** @var ContentItem */
62         private $contentItem;
63
64         public function __construct(
65                 LoggerInterface $logger,
66                 Database $dba,
67                 Account $mstdnAccountFactory,
68                 Mention $mstdnMentionFactory,
69                 Tag $mstdnTagFactory,
70                 Card $mstdnCardFactory,
71                 Attachment $mstdnAttachementFactory,
72                 Error $mstdnErrorFactory,
73                 Poll $mstdnPollFactory,
74                 ContentItem $contentItem
75         ) {
76                 parent::__construct($logger);
77                 $this->dba                     = $dba;
78                 $this->mstdnAccountFactory     = $mstdnAccountFactory;
79                 $this->mstdnMentionFactory     = $mstdnMentionFactory;
80                 $this->mstdnTagFactory         = $mstdnTagFactory;
81                 $this->mstdnCardFactory        = $mstdnCardFactory;
82                 $this->mstdnAttachementFactory = $mstdnAttachementFactory;
83                 $this->mstdnErrorFactory       = $mstdnErrorFactory;
84                 $this->mstdnPollFactory        = $mstdnPollFactory;
85                 $this->contentItem             = $contentItem;
86         }
87
88         /**
89          * @param int  $uriId           Uri-ID of the item
90          * @param int  $uid             Item user
91          * @param bool $display_quote   Display quoted posts
92          * @param bool $reblog          Check for reblogged post
93          * @param bool $in_reply_status Add an "in_reply_status" element
94          *
95          * @return \Friendica\Object\Api\Mastodon\Status
96          * @throws HTTPException\InternalServerErrorException
97          * @throws ImagickException|HTTPException\NotFoundException
98          */
99         public function createFromUriId(int $uriId, int $uid = 0, bool $display_quote = false, bool $reblog = true, bool $in_reply_status = true): \Friendica\Object\Api\Mastodon\Status
100         {
101                 $fields = ['uri-id', 'uid', 'author-id', 'causer-id', 'author-uri-id', 'author-link', 'causer-uri-id', 'post-reason', 'starred', 'app', 'title', 'body', 'raw-body', 'content-warning', 'question-id',
102                         'created', 'network', 'thr-parent-id', 'parent-author-id', 'language', 'uri', 'plink', 'private', 'vid', 'gravity', 'featured', 'has-media', 'quote-uri-id',
103                         'delivery_queue_count', 'delivery_queue_done','delivery_queue_failed'];
104                 $item = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
105                 if (!$item) {
106                         $mail = DBA::selectFirst('mail', ['id'], ['uri-id' => $uriId, 'uid' => $uid]);
107                         if ($mail) {
108                                 return $this->createFromMailId($mail['id']);
109                         }
110                         throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
111                 }
112
113                 $activity_fields = ['uri-id', 'thr-parent-id', 'uri', 'author-id', 'author-uri-id', 'author-link', 'app', 'created', 'network', 'parent-author-id', 'private'];
114
115                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['vid'] == Verb::getID(Activity::ANNOUNCE))) {
116                         $is_reshare = true;
117                         $account    = $this->mstdnAccountFactory->createFromUriId($item['author-uri-id'], $uid);
118                         $uriId      = $item['thr-parent-id'];
119                         $activity   = $item;
120                         $item       = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
121                         if (!$item) {
122                                 throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
123                         }
124                         foreach ($activity_fields as $field) {
125                                 $item[$field] = $activity[$field];
126                         }
127                 } else {
128                         $is_reshare = $reblog && !is_null($item['causer-uri-id']) && ($item['causer-id'] != $item['author-id']) && ($item['post-reason'] == Item::PR_ANNOUNCEMENT);
129                         $account    = $this->mstdnAccountFactory->createFromUriId($is_reshare ? $item['causer-uri-id'] : $item['author-uri-id'], $uid);
130                         if ($is_reshare) {
131                                 $activity = Post::selectFirstPost($activity_fields, ['thr-parent-id' => $item['uri-id'], 'author-id' => $item['causer-id'], 'verb' => Activity::ANNOUNCE]);
132                                 if ($activity) {
133                                         $item = array_merge($item, $activity);
134                                 }
135                         }
136                 }
137
138                 $count_announce = Post::countPosts([
139                         'thr-parent-id' => $uriId,
140                         'gravity'       => Item::GRAVITY_ACTIVITY,
141                         'vid'           => Verb::getID(Activity::ANNOUNCE),
142                         'deleted'       => false
143                 ]) + Post::countPosts([
144                         'quote-uri-id' => $uriId,
145                         'body'         => '',
146                         'deleted'      => false
147                 ]);
148
149                 $count_like = Post::countPosts([
150                         'thr-parent-id' => $uriId,
151                         'gravity'       => Item::GRAVITY_ACTIVITY,
152                         'vid'           => Verb::getID(Activity::LIKE),
153                         'deleted'       => false
154                 ]);
155
156                 $count_dislike = Post::countPosts([
157                         'thr-parent-id' => $uriId,
158                         'gravity'       => Item::GRAVITY_ACTIVITY,
159                         'vid'           => Verb::getID(Activity::DISLIKE),
160                         'deleted'       => false
161                 ]);
162
163                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts(
164                         Post::countPosts(['thr-parent-id' => $uriId, 'gravity' => Item::GRAVITY_COMMENT, 'deleted' => false], []),
165                         $count_announce,
166                         $count_like,
167                         $count_dislike
168                 );
169
170                 $origin_like = ($count_like == 0) ? false : Post::exists([
171                         'thr-parent-id' => $uriId,
172                         'uid'           => $uid,
173                         'origin'        => true,
174                         'gravity'       => Item::GRAVITY_ACTIVITY,
175                         'vid'           => Verb::getID(Activity::LIKE),
176                         'deleted'     => false
177                 ]);
178                 $origin_announce = ($count_announce == 0) ? false : Post::exists([
179                         'thr-parent-id' => $uriId,
180                         'uid'           => $uid,
181                         'origin'        => true,
182                         'gravity'       => Item::GRAVITY_ACTIVITY,
183                         'vid'           => Verb::getID(Activity::ANNOUNCE),
184                         'deleted'       => false
185                 ]) || Post::exists([
186                         'quote-uri-id' => $uriId,
187                         'uid'           => $uid,
188                         'origin'        => true,
189                         'body'          => '',
190                         'deleted'       => false
191                 ]);
192                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(
193                         $origin_like,
194                         $origin_announce,
195                         Post\ThreadUser::getIgnored($uriId, $uid),
196                         (bool)($item['starred'] && ($item['gravity'] == Item::GRAVITY_PARENT)),
197                         $item['featured']
198                 );
199
200                 $sensitive   = $this->dba->exists('tag-view', ['uri-id' => $uriId, 'name' => 'nsfw', 'type' => TagModel::HASHTAG]);
201                 $application = new \Friendica\Object\Api\Mastodon\Application($item['app'] ?: ContactSelector::networkToName($item['network'], $item['author-link']));
202
203                 $mentions    = $this->mstdnMentionFactory->createFromUriId($uriId)->getArrayCopy();
204                 $tags        = $this->mstdnTagFactory->createFromUriId($uriId);
205                 if ($item['has-media']) {
206                         $card        = $this->mstdnCardFactory->createFromUriId($uriId);
207                         $attachments = $this->mstdnAttachementFactory->createFromUriId($uriId);
208                 } else {
209                         $card        = new \Friendica\Object\Api\Mastodon\Card([]);
210                         $attachments = [];
211                 }
212
213                 if (!empty($item['question-id'])) {
214                         $poll = $this->mstdnPollFactory->createFromId($item['question-id'], $uid)->toArray();
215                 } else {
216                         $poll = null;
217                 }
218
219                 if ($display_quote) {
220                         $quote = self::createQuote($item, $uid);
221
222                         $item['body'] = BBCode::removeSharedData($item['body']);
223
224                         if (!is_null($item['raw-body'])) {
225                                 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
226                         }
227                 } else {
228                         // We can always safely add attached activities. Real quotes are added to the body via "addSharedPost".
229                         if (empty($item['quote-uri-id'])) {
230                                 $quote = self::createQuote($item, $uid);
231                         } else {
232                                 $quote = [];
233                         }
234
235                         $shared = $this->contentItem->getSharedPost($item, ['uri-id']);
236                         if (!empty($shared)) {
237                                 $shared_uri_id = $shared['post']['uri-id'];
238
239                                 foreach ($this->mstdnMentionFactory->createFromUriId($shared_uri_id)->getArrayCopy() as $mention) {
240                                         if (!in_array($mention, $mentions)) {
241                                                 $mentions[] = $mention;
242                                         }
243                                 }
244
245                                 foreach ($this->mstdnTagFactory->createFromUriId($shared_uri_id) as $tag) {
246                                         if (!in_array($tag, $tags)) {
247                                                 $tags[] = $tag;
248                                         }
249                                 }
250
251                                 foreach ($this->mstdnAttachementFactory->createFromUriId($shared_uri_id) as $attachment) {
252                                         if (!in_array($attachment, $attachments)) {
253                                                 $attachments[] = $attachment;
254                                         }
255                                 }
256
257                                 if (empty($card->toArray())) {
258                                         $card = $this->mstdnCardFactory->createFromUriId($shared_uri_id);
259                                 }
260                         }
261
262                         $item['body'] = $this->contentItem->addSharedPost($item);
263
264                         if (!is_null($item['raw-body'])) {
265                                 $item['raw-body'] = $this->contentItem->addSharedPost($item, $item['raw-body']);
266                         }
267                 }
268
269                 if ($is_reshare) {
270                         try {
271                                 $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray();
272                         } catch (\Exception $exception) {
273                                 Logger::info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
274                                 $reshare = [];
275                         }
276                 } else {
277                         $reshare = [];
278                 }
279
280                 if ($in_reply_status && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
281                         try {
282                                 $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray();
283                         } catch (\Exception $exception) {
284                                 Logger::info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
285                                 $in_reply = [];
286                         }
287                 } else {
288                         $in_reply = [];
289                 }
290
291                 $delivery_data = new FriendicaDeliveryData($item['delivery_queue_count'], $item['delivery_queue_done'], $item['delivery_queue_failed']);
292                 $friendica     = new FriendicaExtension($item['title'], $counts->dislikes, $delivery_data);
293
294                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica, $quote, $poll);
295         }
296
297         /**
298          * Create a quote status object
299          *
300          * @param array $item
301          * @param integer $uid
302          * @return array
303          */
304         private function createQuote(array $item, int $uid): array
305         {
306                 if (empty($item['quote-uri-id'])) {
307                         $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
308                         if (!empty($media) && $shared_item = Post::selectFirst(['uri-id'], ['plink' => $media[0]['url'], 'uid' => [$uid, 0]])) {
309                                 $quote_id = $shared_item['uri-id'];
310                         }
311                 } else {
312                         $quote_id = $item['quote-uri-id'];
313                 }
314
315                 if (!empty($quote_id)) {
316                         try {
317                                 $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray();
318                         } catch (\Exception $exception) {
319                                 Logger::info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
320                                 $quote = [];
321                         }
322                 } else {
323                         $quote = [];
324                 }
325                 return $quote;
326         }
327
328         /**
329          * @param int $uriId id of the mail
330          *
331          * @return \Friendica\Object\Api\Mastodon\Status
332          * @throws HTTPException\InternalServerErrorException
333          * @throws ImagickException|HTTPException\NotFoundException
334          */
335         public function createFromMailId(int $id): \Friendica\Object\Api\Mastodon\Status
336         {
337                 $item = ActivityPub\Transmitter::getItemArrayFromMail($id, true);
338                 if (empty($item)) {
339                         $this->mstdnErrorFactory->RecordNotFound();
340                 }
341
342                 $account = $this->mstdnAccountFactory->createFromContactId($item['author-id']);
343
344                 $replies = $this->dba->count('mail', ['thr-parent-id' => $item['uri-id'], 'reply' => true]);
345
346                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts($replies, 0, 0, 0);
347
348                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(false, false, false, false, false);
349
350                 $sensitive   = false;
351                 $application = new \Friendica\Object\Api\Mastodon\Application('');
352                 $mentions    = [];
353                 $tags        = [];
354                 $card        = new \Friendica\Object\Api\Mastodon\Card([]);
355                 $attachments = [];
356                 $in_reply    = [];
357                 $reshare     = [];
358                 $friendica   = new FriendicaExtension('', 0, new FriendicaDeliveryData(0, 0, 0));
359
360                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica);
361         }
362 }