]> git.mxchange.org Git - friendica.git/blob - src/Worker/PushSubscription.php
Merge pull request #11757 from annando/diaspora
[friendica.git] / src / Worker / PushSubscription.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\Content\Text\BBCode;
25 use Friendica\Content\Text\Plaintext;
26 use Friendica\Core\Logger;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Post;
32 use Friendica\Model\Subscription as ModelSubscription;
33 use Friendica\Model\User;
34 use Friendica\Navigation\Notifications;
35 use Friendica\Network\HTTPException\NotFoundException;
36 use Minishlink\WebPush\WebPush;
37 use Minishlink\WebPush\Subscription;
38
39 class PushSubscription
40 {
41         /**
42          * Creates push subscription by subscription and notification ids
43          *
44          * @param int $sid Subscription id
45          * @param int $nid Notification id
46          * @return void
47          */
48         public static function execute(int $sid, int $nid)
49         {
50                 Logger::info('Start', ['subscription' => $sid, 'notification' => $nid]);
51
52                 $subscription = DBA::selectFirst('subscription', [], ['id' => $sid]);
53                 if (empty($subscription)) {
54                         Logger::info('Subscription not found', ['subscription' => $sid]);
55                         return;
56                 }
57
58                 try {
59                         $notification = DI::notification()->selectOneById($nid);
60                 } catch (NotFoundException $e) {
61                         Logger::info('Notification not found', ['notification' => $nid]);
62                         return;
63                 }
64
65                 $application_token = DBA::selectFirst('application-token', [], ['application-id' => $subscription['application-id'], 'uid' => $subscription['uid']]);
66                 if (empty($application_token)) {
67                         Logger::info('Application token not found', ['application' => $subscription['application-id']]);
68                         return;
69                 }
70
71                 $user = User::getById($notification->uid);
72                 if (empty($user)) {
73                         Logger::info('User not found', ['application' => $subscription['uid']]);
74                         return;
75                 }
76
77                 $l10n = DI::l10n()->withLang($user['language']);
78
79                 if ($notification->actorId) {
80                         $actor = Contact::getById($notification->actorId);
81                 }
82
83                 $body = '';
84
85                 if ($notification->targetUriId) {
86                         $post = Post::selectFirst([], ['uri-id' => $notification->targetUriId, 'uid' => [0, $notification->uid]]);
87                         if (!empty($post['body'])) {
88                                 $body = BBCode::toPlaintext($post['body'], false);
89                                 $body = Plaintext::shorten($body, 160, $notification->uid);
90                         }
91                 }
92
93                 $message = DI::notificationFactory()->getMessageFromNotification($notification);
94                 $title = $message['plain'] ?: '';
95
96                 $push = Subscription::create([
97                         'contentEncoding' => 'aesgcm',
98                         'endpoint'        => $subscription['endpoint'],
99                         'keys'            => [
100                                 'p256dh' => $subscription['pubkey'],
101                                 'auth'   => $subscription['secret']
102                         ],
103                 ]);
104
105                 $payload = [
106                         'access_token'      => $application_token['access_token'],
107                         'preferred_locale'  => $user['language'],
108                         'notification_id'   => $nid,
109                         'notification_type' => NotificationFactory::getType($notification),
110                         'icon'              => $actor['thumb'] ?? '',
111                         'title'             => $title ?: $l10n->t('Notification from Friendica'),
112                         'body'              => $body ?: $l10n->t('Empty Post'),
113                 ];
114
115                 Logger::info('Payload', ['payload' => $payload]);
116
117                 $auth = [
118                         'VAPID' => [
119                                 'subject'    => DI::baseUrl()->getHostname(),
120                                 'publicKey'  => ModelSubscription::getPublicVapidKey(),
121                                 'privateKey' => ModelSubscription::getPrivateVapidKey(),
122                         ],
123                 ];
124
125                 $webPush = new WebPush($auth, [], DI::config()->get('system', 'xrd_timeout'));
126
127                 $report = $webPush->sendOneNotification($push, json_encode($payload), ['urgency' => 'normal']);
128
129                 $endpoint = $report->getRequest()->getUri()->__toString();
130
131                 if ($report->isSuccess()) {
132                         Logger::info('Message sent successfully for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint]);
133                 } else {
134                         Logger::info('Message failed to sent for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint, 'reason' => $report->getReason()]);
135                 }
136         }
137 }