]> git.mxchange.org Git - friendica.git/blob - src/Factory/Api/Mastodon/Status.php
Fix missing attached links in posts
[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', 'edited', 'commented', 'received', 'changed', '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                         $item['body'] = Post\Media::addHTMLAttachmentToBody($uriId, $item['body']);
264
265                         if (!is_null($item['raw-body'])) {
266                                 $item['raw-body'] = $this->contentItem->addSharedPost($item, $item['raw-body']);
267                                 $item['raw-body'] = Post\Media::addHTMLLinkToBody($uriId, $item['raw-body']);
268                         }
269                 }
270
271                 if ($is_reshare) {
272                         try {
273                                 $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray();
274                         } catch (\Exception $exception) {
275                                 Logger::info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
276                                 $reshare = [];
277                         }
278                 } else {
279                         $reshare = [];
280                 }
281
282                 if ($in_reply_status && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
283                         try {
284                                 $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray();
285                         } catch (\Exception $exception) {
286                                 Logger::info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
287                                 $in_reply = [];
288                         }
289                 } else {
290                         $in_reply = [];
291                 }
292
293                 $delivery_data = new FriendicaDeliveryData($item['delivery_queue_count'], $item['delivery_queue_done'], $item['delivery_queue_failed']);
294                 $friendica     = new FriendicaExtension($item['title'], $item['changed'], $item['commented'], $item['received'], $counts->dislikes, $delivery_data);
295
296                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica, $quote, $poll);
297         }
298
299         /**
300          * Create a quote status object
301          *
302          * @param array $item
303          * @param integer $uid
304          * @return array
305          */
306         private function createQuote(array $item, int $uid): array
307         {
308                 if (empty($item['quote-uri-id'])) {
309                         $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
310                         if (!empty($media) && $shared_item = Post::selectFirst(['uri-id'], ['plink' => $media[0]['url'], 'uid' => [$uid, 0]])) {
311                                 $quote_id = $shared_item['uri-id'];
312                         }
313                 } else {
314                         $quote_id = $item['quote-uri-id'];
315                 }
316
317                 if (!empty($quote_id)) {
318                         try {
319                                 $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray();
320                         } catch (\Exception $exception) {
321                                 Logger::info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
322                                 $quote = [];
323                         }
324                 } else {
325                         $quote = [];
326                 }
327                 return $quote;
328         }
329
330         /**
331          * @param int $uriId id of the mail
332          *
333          * @return \Friendica\Object\Api\Mastodon\Status
334          * @throws HTTPException\InternalServerErrorException
335          * @throws ImagickException|HTTPException\NotFoundException
336          */
337         public function createFromMailId(int $id): \Friendica\Object\Api\Mastodon\Status
338         {
339                 $item = ActivityPub\Transmitter::getItemArrayFromMail($id, true);
340                 if (empty($item)) {
341                         $this->mstdnErrorFactory->RecordNotFound();
342                 }
343
344                 $account = $this->mstdnAccountFactory->createFromContactId($item['author-id']);
345
346                 $replies = $this->dba->count('mail', ['thr-parent-id' => $item['uri-id'], 'reply' => true]);
347
348                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts($replies, 0, 0, 0);
349
350                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(false, false, false, false, false);
351
352                 $sensitive   = false;
353                 $application = new \Friendica\Object\Api\Mastodon\Application('');
354                 $mentions    = [];
355                 $tags        = [];
356                 $card        = new \Friendica\Object\Api\Mastodon\Card([]);
357                 $attachments = [];
358                 $in_reply    = [];
359                 $reshare     = [];
360                 $friendica   = new FriendicaExtension('', null, null, null, 0, new FriendicaDeliveryData(0, 0, 0));
361
362                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica);
363         }
364 }