]> git.mxchange.org Git - friendica.git/blob - src/Model/PushSubscriber.php
Merge pull request #13161 from annando/bluesky-activities
[friendica.git] / src / Model / PushSubscriber.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\Model;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Worker;
26 use Friendica\Database\DBA;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29
30 class PushSubscriber
31 {
32         /**
33          * Send subscription notifications for the given user
34          *
35          * @param integer $uid User ID
36          * @param int     $default_priority
37          * @return void
38          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39          */
40         public static function publishFeed(int $uid, int $default_priority = Worker::PRIORITY_HIGH)
41         {
42                 $condition = ['push' => 0, 'uid' => $uid];
43                 DBA::update('push_subscriber', ['push' => 1, 'next_try' => DBA::NULL_DATETIME], $condition);
44
45                 self::requeue($default_priority);
46         }
47
48         /**
49          * start workers to transmit the feed data
50          *
51          * @param int $default_priority
52          * @return void
53          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54          */
55         public static function requeue(int $default_priority = Worker::PRIORITY_HIGH)
56         {
57                 // We'll push to each subscriber that has push > 0,
58                 // i.e. there has been an update (set in notifier.php).
59                 $subscribers = DBA::select('push_subscriber', ['id', 'push', 'callback_url', 'nickname'], ["`push` > 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
60
61                 while ($subscriber = DBA::fetch($subscribers)) {
62                         // We always handle retries with low priority
63                         if ($subscriber['push'] > 1) {
64                                 $priority = Worker::PRIORITY_LOW;
65                         } else {
66                                 $priority = $default_priority;
67                         }
68
69                         Logger::info('Publish feed to ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' with priority ' . $priority);
70                         Worker::add($priority, 'PubSubPublish', (int)$subscriber['id']);
71                 }
72
73                 DBA::close($subscribers);
74         }
75
76         /**
77          * Renew the feed subscription
78          *
79          * @param integer $uid          User ID
80          * @param string  $nick         Priority for push workers
81          * @param integer $subscribe    Subscribe (Unsubscribe = false)
82          * @param string  $hub_callback Callback address
83          * @param string  $hub_topic    Feed topic
84          * @param string  $hub_secret   Subscription secret
85          * @return void
86          * @throws \Exception
87          */
88         public static function renew(int $uid, string $nick, int $subscribe, string $hub_callback, string $hub_topic, string $hub_secret)
89         {
90                 // fetch the old subscription if it exists
91                 $subscriber = DBA::selectFirst('push_subscriber', ['last_update', 'push'], ['callback_url' => $hub_callback]);
92
93                 // delete old subscription if it exists
94                 DBA::delete('push_subscriber', ['callback_url' => $hub_callback]);
95
96                 if ($subscribe) {
97                         // if we are just updating an old subscription, keep the
98                         // old values for last_update but reset the push
99                         if (DBA::isResult($subscriber)) {
100                                 $last_update = $subscriber['last_update'];
101                                 $push_flag = min($subscriber['push'], 1);
102                         } else {
103                                 $last_update = DateTimeFormat::utcNow();
104                                 $push_flag = 0;
105                         }
106
107                         // subscribe means adding the row to the table
108                         $fields = ['uid' => $uid, 'callback_url' => $hub_callback,
109                                 'topic' => $hub_topic, 'nickname' => $nick, 'push' => $push_flag,
110                                 'last_update' => $last_update, 'renewed' => DateTimeFormat::utcNow(),
111                                 'secret' => $hub_secret];
112                         DBA::insert('push_subscriber', $fields);
113
114                         Logger::notice("Successfully subscribed [$hub_callback] for $nick");
115                 } else {
116                         Logger::notice("Successfully unsubscribed [$hub_callback] for $nick");
117                         // we do nothing here, since the row was already deleted
118                 }
119         }
120
121         /**
122          * Delay the push subscriber
123          *
124          * @param integer $id Subscriber ID
125          * @return void
126          * @throws \Exception
127          */
128         public static function delay(int $id)
129         {
130                 $subscriber = DBA::selectFirst('push_subscriber', ['push', 'callback_url', 'renewed', 'nickname'], ['id' => $id]);
131                 if (!DBA::isResult($subscriber)) {
132                         return;
133                 }
134
135                 $retrial = $subscriber['push'];
136
137                 if ($retrial > 14) {
138                         // End subscriptions if they weren't renewed for more than two months
139                         $days = round((time() -  strtotime($subscriber['renewed'])) / (60 * 60 * 24));
140
141                         if ($days > 60) {
142                                 DBA::update('push_subscriber', ['push' => -1, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]);
143                                 Logger::info('Delivery error: Subscription ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as ended.');
144                         } else {
145                                 DBA::update('push_subscriber', ['push' => 0, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]);
146                                 Logger::info('Delivery error: Giving up ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' for now.');
147                         }
148                 } else {
149                         // Calculate the delay until the next trial
150                         $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
151                         $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
152
153                         $retrial = $retrial + 1;
154
155                         DBA::update('push_subscriber', ['push' => $retrial, 'next_try' => $next], ['id' => $id]);
156                         Logger::info('Delivery error: Next try (' . $retrial . ') ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' at ' . $next);
157                 }
158         }
159
160         /**
161          * Reset the push subscriber
162          *
163          * @param integer $id          Subscriber ID
164          * @param string  $last_update Date of last transmitted item
165          * @return void
166          * @throws \Exception
167          */
168         public static function reset(int $id, string $last_update)
169         {
170                 $subscriber = DBA::selectFirst('push_subscriber', ['callback_url', 'nickname'], ['id' => $id]);
171                 if (!DBA::isResult($subscriber)) {
172                         return;
173                 }
174
175                 // set last_update to the 'created' date of the last item, and reset push=0
176                 $fields = ['push' => 0, 'next_try' => DBA::NULL_DATETIME, 'last_update' => $last_update];
177                 DBA::update('push_subscriber', $fields, ['id' => $id]);
178                 Logger::info('Subscriber ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as vital');
179
180                 $parts = parse_url($subscriber['callback_url']);
181                 unset($parts['path']);
182                 $server_url = Network::unparseURL($parts);
183                 $gsid = GServer::getID($server_url, true);
184                 if (!empty($gsid)) {
185                         GServer::setProtocol($gsid, Post\DeliveryData::OSTATUS);
186                 }
187         }
188 }