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