]> git.mxchange.org Git - friendica.git/blob - src/Factory/Api/Mastodon/Status.php
Merge pull request #12802 from nupplaphil/feat/system_url_handling
[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\Protocol\Activity;
37 use Friendica\Protocol\ActivityPub;
38 use ImagickException;
39 use Psr\Log\LoggerInterface;
40
41 class Status extends BaseFactory
42 {
43         /** @var Database */
44         private $dba;
45         /** @var Account */
46         private $mstdnAccountFactory;
47         /** @var Mention */
48         private $mstdnMentionFactory;
49         /** @var Tag */
50         private $mstdnTagFactory;
51         /** @var Card */
52         private $mstdnCardFactory;
53         /** @var Attachment */
54         private $mstdnAttachementFactory;
55         /** @var Error */
56         private $mstdnErrorFactory;
57         /** @var Poll */
58         private $mstdnPollFactory;
59         /** @var ContentItem */
60         private $contentItem;
61
62         public function __construct(LoggerInterface $logger, Database $dba,
63                 Account $mstdnAccountFactory, Mention $mstdnMentionFactory,
64                 Tag $mstdnTagFactory, Card $mstdnCardFactory,
65                 Attachment $mstdnAttachementFactory, Error $mstdnErrorFactory,
66                 Poll $mstdnPollFactory, ContentItem $contentItem)
67         {
68                 parent::__construct($logger);
69                 $this->dba                     = $dba;
70                 $this->mstdnAccountFactory     = $mstdnAccountFactory;
71                 $this->mstdnMentionFactory     = $mstdnMentionFactory;
72                 $this->mstdnTagFactory         = $mstdnTagFactory;
73                 $this->mstdnCardFactory        = $mstdnCardFactory;
74                 $this->mstdnAttachementFactory = $mstdnAttachementFactory;
75                 $this->mstdnErrorFactory       = $mstdnErrorFactory;
76                 $this->mstdnPollFactory        = $mstdnPollFactory;
77                 $this->contentItem             = $contentItem;
78         }
79
80         /**
81          * @param int  $uriId           Uri-ID of the item
82          * @param int  $uid             Item user
83          * @param bool $display_quote   Display quoted posts
84          * @param bool $reblog          Check for reblogged post
85          * @param bool $in_reply_status Add an "in_reply_status" element
86          *
87          * @return \Friendica\Object\Api\Mastodon\Status
88          * @throws HTTPException\InternalServerErrorException
89          * @throws ImagickException|HTTPException\NotFoundException
90          */
91         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
92         {
93                 $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',
94                         'created', 'network', 'thr-parent-id', 'parent-author-id', 'language', 'uri', 'plink', 'private', 'vid', 'gravity', 'featured', 'has-media', 'quote-uri-id'];
95                 $item = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
96                 if (!$item) {
97                         $mail = DBA::selectFirst('mail', ['id'], ['uri-id' => $uriId, 'uid' => $uid]);
98                         if ($mail) {
99                                 return $this->createFromMailId($mail['id']);
100                         }
101                         throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
102                 }
103
104                 $activity_fields = ['uri-id', 'thr-parent-id', 'uri', 'author-id', 'author-uri-id', 'author-link', 'app', 'created', 'network', 'parent-author-id', 'private'];
105
106                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['vid'] == Verb::getID(Activity::ANNOUNCE))) {
107                         $is_reshare = true;
108                         $account    = $this->mstdnAccountFactory->createFromUriId($item['author-uri-id'], $uid);
109                         $uriId      = $item['thr-parent-id'];
110                         $activity   = $item;
111                         $item       = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
112                         if (!$item) {
113                                 throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
114                         }
115                         foreach ($activity_fields as $field) {
116                                 $item[$field] = $activity[$field];
117                         }
118                 } else {
119                         $is_reshare = $reblog && !is_null($item['causer-uri-id']) && ($item['causer-id'] != $item['author-id']) && ($item['post-reason'] == Item::PR_ANNOUNCEMENT);
120                         $account    = $this->mstdnAccountFactory->createFromUriId($is_reshare ? $item['causer-uri-id'] : $item['author-uri-id'], $uid);
121                         if ($is_reshare) {
122                                 $activity = Post::selectFirstPost($activity_fields, ['thr-parent-id' => $item['uri-id'], 'author-id' => $item['causer-id'], 'verb' => Activity::ANNOUNCE]);
123                                 if ($activity) {
124                                         $item = array_merge($item, $activity);
125                                 }
126                         }
127                 }
128
129                 $count_announce = Post::countPosts([
130                         'thr-parent-id' => $uriId,
131                         'gravity'       => Item::GRAVITY_ACTIVITY,
132                         'vid'           => Verb::getID(Activity::ANNOUNCE),
133                         'deleted'       => false
134                 ]) + Post::countPosts([
135                         'quote-uri-id' => $uriId,
136                         'body'         => '',
137                         'deleted'      => false
138                 ]);
139
140                 $count_like = Post::countPosts([
141                         'thr-parent-id' => $uriId,
142                         'gravity'       => Item::GRAVITY_ACTIVITY,
143                         'vid'           => Verb::getID(Activity::LIKE),
144                         'deleted'       => false
145                 ]);
146
147                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts(
148                         Post::countPosts(['thr-parent-id' => $uriId, 'gravity' => Item::GRAVITY_COMMENT, 'deleted' => false], []),
149                         $count_announce,
150                         $count_like
151                 );
152
153                 $origin_like = ($count_like == 0) ? false : Post::exists([
154                         'thr-parent-id' => $uriId,
155                         'uid'           => $uid,
156                         'origin'        => true,
157                         'gravity'       => Item::GRAVITY_ACTIVITY,
158                         'vid'           => Verb::getID(Activity::LIKE),
159                         'deleted'     => false
160                 ]);
161                 $origin_announce = ($count_announce == 0) ? false : Post::exists([
162                         'thr-parent-id' => $uriId,
163                         'uid'           => $uid,
164                         'origin'        => true,
165                         'gravity'       => Item::GRAVITY_ACTIVITY,
166                         'vid'           => Verb::getID(Activity::ANNOUNCE),
167                         'deleted'       => false
168                 ]) || Post::exists([
169                         'quote-uri-id' => $uriId,
170                         'uid'           => $uid,
171                         'origin'        => true,
172                         'body'          => '',
173                         'deleted'       => false
174                 ]);
175                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(
176                         $origin_like,
177                         $origin_announce,
178                         Post\ThreadUser::getIgnored($uriId, $uid),
179                         (bool)($item['starred'] && ($item['gravity'] == Item::GRAVITY_PARENT)),
180                         $item['featured']
181                 );
182
183                 $sensitive   = $this->dba->exists('tag-view', ['uri-id' => $uriId, 'name' => 'nsfw', 'type' => TagModel::HASHTAG]);
184                 $application = new \Friendica\Object\Api\Mastodon\Application($item['app'] ?: ContactSelector::networkToName($item['network'], $item['author-link']));
185
186                 $mentions    = $this->mstdnMentionFactory->createFromUriId($uriId)->getArrayCopy();
187                 $tags        = $this->mstdnTagFactory->createFromUriId($uriId);
188                 if ($item['has-media']) {
189                         $card        = $this->mstdnCardFactory->createFromUriId($uriId);
190                         $attachments = $this->mstdnAttachementFactory->createFromUriId($uriId);
191                 } else {
192                         $card        = new \Friendica\Object\Api\Mastodon\Card([]);
193                         $attachments = [];
194                 }
195
196                 if (!empty($item['question-id'])) {
197                         $poll = $this->mstdnPollFactory->createFromId($item['question-id'], $uid)->toArray();
198                 } else {
199                         $poll = null;
200                 }
201
202                 if ($display_quote) {
203                         $quote = self::createQuote($item, $uid);
204
205                         $item['body'] = BBCode::removeSharedData($item['body']);
206
207                         if (!is_null($item['raw-body'])) {
208                                 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
209                         }
210                 } else {
211                         // We can always safely add attached activities. Real quotes are added to the body via "addSharedPost".
212                         if (empty($item['quote-uri-id'])) {
213                                 $quote = self::createQuote($item, $uid);
214                         } else {
215                                 $quote = [];
216                         }
217
218                         $shared = $this->contentItem->getSharedPost($item, ['uri-id']);
219                         if (!empty($shared)) {
220                                 $shared_uri_id = $shared['post']['uri-id'];
221
222                                 foreach ($this->mstdnMentionFactory->createFromUriId($shared_uri_id)->getArrayCopy() as $mention) {
223                                         if (!in_array($mention, $mentions)) {
224                                                 $mentions[] = $mention;
225                                         }
226                                 }
227
228                                 foreach ($this->mstdnTagFactory->createFromUriId($shared_uri_id) as $tag) {
229                                         if (!in_array($tag, $tags)) {
230                                                 $tags[] = $tag;
231                                         }
232                                 }
233
234                                 foreach ($this->mstdnAttachementFactory->createFromUriId($shared_uri_id) as $attachment) {
235                                         if (!in_array($attachment, $attachments)) {
236                                                 $attachments[] = $attachment;
237                                         }
238                                 }
239
240                                 if (empty($card->toArray())) {
241                                         $card = $this->mstdnCardFactory->createFromUriId($shared_uri_id);
242                                 }
243                         }
244
245                         $item['body'] = $this->contentItem->addSharedPost($item);
246
247                         if (!is_null($item['raw-body'])) {
248                                 $item['raw-body'] = $this->contentItem->addSharedPost($item, $item['raw-body']);
249                         }
250                 }
251
252                 if ($is_reshare) {
253                         try {
254                                 $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray();
255                         } catch (\Throwable $th) {
256                                 Logger::info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
257                                 $reshare = [];
258                         }
259                 } else {
260                         $reshare = [];
261                 }
262
263                 if ($in_reply_status && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
264                         try {
265                                 $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray();
266                         } catch (\Throwable $th) {
267                                 Logger::info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
268                                 $in_reply = [];
269                         }
270                 } else {
271                         $in_reply = [];
272                 }
273
274                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $quote, $poll);
275         }
276
277         /**
278          * Create a quote status object
279          *
280          * @param array $item
281          * @param integer $uid
282          * @return array
283          */
284         private function createQuote(array $item, int $uid): array
285         {
286                 if (empty($item['quote-uri-id'])) {
287                         $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
288                         if (!empty($media) && $shared_item = Post::selectFirst(['uri-id'], ['plink' => $media[0]['url'], 'uid' => [$uid, 0]])) {
289                                 $quote_id = $shared_item['uri-id'];
290                         }
291                 } else {
292                         $quote_id = $item['quote-uri-id'];
293                 }
294
295                 if (!empty($quote_id)) {
296                         try {
297                                 $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray();
298                         } catch (\Throwable $th) {
299                                 Logger::info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
300                                 $quote = [];
301                         }
302                 } else {
303                         $quote = [];
304                 }
305                 return $quote;
306         }
307
308         /**
309          * @param int $uriId id of the mail
310          *
311          * @return \Friendica\Object\Api\Mastodon\Status
312          * @throws HTTPException\InternalServerErrorException
313          * @throws ImagickException|HTTPException\NotFoundException
314          */
315         public function createFromMailId(int $id): \Friendica\Object\Api\Mastodon\Status
316         {
317                 $item = ActivityPub\Transmitter::getItemArrayFromMail($id, true);
318                 if (empty($item)) {
319                         $this->mstdnErrorFactory->RecordNotFound();
320                 }
321
322                 $account = $this->mstdnAccountFactory->createFromContactId($item['author-id']);
323
324                 $replies = $this->dba->count('mail', ['thr-parent-id' => $item['uri-id'], 'reply' => true]);
325
326                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts($replies, 0, 0);
327
328                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(false, false, false, false, false);
329
330                 $sensitive   = false;
331                 $application = new \Friendica\Object\Api\Mastodon\Application('');
332                 $mentions    = [];
333                 $tags        = [];
334                 $card        = new \Friendica\Object\Api\Mastodon\Card([]);
335                 $attachments = [];
336                 $in_reply    = [];
337                 $reshare     = [];
338
339                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare);
340         }
341 }