]> git.mxchange.org Git - friendica.git/blob - src/Worker/APDelivery.php
Merge pull request #11503 from annando/bulk-delivery
[friendica.git] / src / Worker / APDelivery.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Worker;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Worker;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\GServer;
29 use Friendica\Model\Post;
30 use Friendica\Protocol\ActivityPub;
31 use Friendica\Util\HTTPSignature;
32
33 class APDelivery
34 {
35         /**
36          * Delivers ActivityPub messages
37          *
38          * @param string  $cmd       One of the Worker\Delivery constant values
39          * @param integer $item_id   0 if no item is involved (like Delivery::REMOVAL and Delivery::PROFILEUPDATE)
40          * @param string  $inbox     The URL of the recipient profile
41          * @param integer $uid       The ID of the user who triggered this delivery
42          * @param array   $receivers The contact IDs related to the inbox URL for contact archival housekeeping
43          * @param int     $uri_id    URI-ID of item to be transmitted
44          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
45          * @throws \ImagickException
46          */
47         public static function execute(string $cmd, int $item_id, string $inbox, int $uid, array $receivers = [], int $uri_id = 0)
48         {
49                 if (ActivityPub\Transmitter::archivedInbox($inbox)) {
50                         Logger::info('Inbox is archived', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]);
51                         if (empty($uri_id) && !empty($item_id)) {
52                                 $item = Post::selectFirst(['uri-id'], ['id' => $item_id]);
53                                 $uri_id = $item['uri-id'] ?? 0;
54                         }
55                         if (empty($uri_id)) {
56                                 $posts   = Post\Delivery::selectForInbox($inbox);
57                                 $uri_ids = array_column($posts, 'uri-id');
58                         } else {
59                                 $uri_ids = [$uri_id];
60                         }
61
62                         foreach ($uri_ids as $uri_id) {
63                                 Post\Delivery::remove($uri_id, $inbox);
64                                 Post\DeliveryData::incrementQueueFailed($uri_id);
65                         }
66                         return;
67                 }
68
69                 Logger::debug('Invoked', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]);
70
71                 if (empty($uri_id)) {
72                         $result  = self::deliver($inbox);
73                         $success = $result['success'];
74                         $uri_ids = $result['uri_ids'];
75                 } else {
76                         $result  = self::deliverToInbox($cmd, $item_id, $inbox, $uid, $receivers, $uri_id);
77                         $success = $result['success'];
78                         $uri_ids = [$uri_id];
79                 }
80
81                 if (!$success && !Worker::defer() && !empty($uri_ids)) {
82                         foreach ($uri_ids as $uri_id) {
83                                 Post\Delivery::remove($uri_id, $inbox);
84                                 Post\DeliveryData::incrementQueueFailed($uri_id);
85                         }
86                 }
87         }
88
89         private static function deliver(string $inbox):array
90         {
91                 $uri_ids    = [];
92                 $posts      = Post\Delivery::selectForInbox($inbox);
93                 $serverfail = false;
94
95                 foreach ($posts as $post) {
96                         if (!$serverfail) {
97                                 $result = self::deliverToInbox($post['command'], 0, $inbox, $post['uid'], $post['receivers'], $post['uri-id']);
98
99                                 if ($result['serverfailure']) {
100                                         // In a timeout situation we assume that every delivery to that inbox will time out.
101                                         // So we set the flag and try all deliveries at a later time.
102                                         Logger::info('Inbox delivery has a server failure', ['inbox' => $inbox]);
103                                         $serverfail = true;
104                                 }
105                         }
106
107                         if ($serverfail || !$result['success']) {
108                                 $uri_ids[] = $post['uri-id'];
109                         }
110                 }
111
112                 Logger::debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]);
113                 return ['success' => empty($uri_ids), 'uri_ids' => $uri_ids];
114         }
115
116         private static function deliverToInbox(string $cmd, int $item_id, string $inbox, int $uid, array $receivers, int $uri_id): array
117         {
118                 if (empty($item_id) && !empty($uri_id) && !empty($uid)) {
119                         $item = Post::selectFirst(['id', 'parent', 'origin'], ['uri-id' => $uri_id, 'uid' => [$uid, 0]], ['order' => ['uid' => true]]);
120                         if (empty($item['id'])) {
121                                 Logger::notice('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]);
122                                 Post\Delivery::remove($uri_id, $inbox);
123                                 return true;
124                         } else {
125                                 $item_id = $item['id'];
126                         }
127                 }
128
129                 $success    = true;
130                 $serverfail = false;
131
132                 if ($cmd == Delivery::MAIL) {
133                         $data = ActivityPub\Transmitter::createActivityFromMail($item_id);
134                         if (!empty($data)) {
135                                 $success = HTTPSignature::transmit($data, $inbox, $uid);
136                         }
137                 } elseif ($cmd == Delivery::SUGGESTION) {
138                         $success = ActivityPub\Transmitter::sendContactSuggestion($uid, $inbox, $item_id);
139                 } elseif ($cmd == Delivery::RELOCATION) {
140                         // @todo Implementation pending
141                 } elseif ($cmd == Delivery::POKE) {
142                         // Implementation not planned
143                 } elseif ($cmd == Delivery::REMOVAL) {
144                         $success = ActivityPub\Transmitter::sendProfileDeletion($uid, $inbox);
145                 } elseif ($cmd == Delivery::PROFILEUPDATE) {
146                         $success = ActivityPub\Transmitter::sendProfileUpdate($uid, $inbox);
147                 } else {
148                         $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id);
149                         if (!empty($data)) {
150                                 $timestamp  = microtime(true);
151                                 $response   = HTTPSignature::post($data, $inbox, $uid);
152                                 $runtime    = microtime(true) - $timestamp;
153                                 $success    = $response->isSuccess();
154                                 $serverfail = $response->isTimeout();
155                                 if (!$success) {
156                                         if (!$serverfail && ($response->getReturnCode() >= 500) && ($response->getReturnCode() <= 599)) {
157                                                 $serverfail = true;
158                                         }
159
160                                         $xrd_timeout = DI::config()->get('system', 'xrd_timeout');
161                                         if (!$serverfail && $xrd_timeout && ($runtime > $xrd_timeout)) {
162                                                 $serverfail = true;
163                                         }
164                                         $curl_timeout = DI::config()->get('system', 'curl_timeout');
165                                         if (!$serverfail && $curl_timeout && ($runtime > $curl_timeout)) {
166                                                 $serverfail = true;
167                                         }
168
169                                         Logger::info('Delivery failed', ['retcode' => $response->getReturnCode(), 'serverfailure' => $serverfail, 'runtime' => round($runtime, 3), 'uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox]);
170                                 }
171                                 if ($uri_id) {
172                                         if ($success) {
173                                                 Post\Delivery::remove($uri_id, $inbox);
174                                         } else {
175                                                 Post\Delivery::incrementFailed($uri_id, $inbox);
176                                         }
177                                 }
178                         }
179                 }
180
181                 self::setSuccess($receivers, $success);
182
183                 Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success]);
184
185                 if ($success && in_array($cmd, [Delivery::POST])) {
186                         Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB);
187                 }
188
189                 return ['success' => $success, 'serverfailure' => $serverfail];
190         }
191
192         private static function setSuccess(array $receivers, bool $success)
193         {
194                 $gsid = null;
195
196                 foreach ($receivers as $receiver) {
197                         $contact = Contact::getById($receiver);
198                         if (empty($contact)) {
199                                 continue;
200                         }
201
202                         $gsid = $gsid ?: $contact['gsid'];
203
204                         if ($success) {
205                                 Contact::unmarkForArchival($contact);
206                         } else {
207                                 Contact::markForArchival($contact);
208                         }
209                 }
210
211                 if (!empty($gsid)) {
212                         GServer::setProtocol($gsid, Post\DeliveryData::ACTIVITYPUB);
213                 }
214         }
215 }