Changeset View
Changeset View
Standalone View
Standalone View
src/applications/webpush/client/PhabricatorWebpushClient.php
- This file was added.
| <?php | |||||
| final class PhabricatorWebpushClient extends Phobject { | |||||
| public static function tryToPostMessage(array $data) { | |||||
| if (!PhabricatorEnv::getEnvConfig('webpush.enabled')) { | |||||
| return; | |||||
| } | |||||
| try { | |||||
| self::postMessage($data); | |||||
| } catch (Exception $ex) { | |||||
| // Just ignore any issues here. | |||||
| phlog($ex); | |||||
| } | |||||
| } | |||||
| private static function postMessage(array $data) { | |||||
| if (empty($data['threadPHID'])) { | |||||
| return; | |||||
| } | |||||
| if (empty($data['subscribers'])) { | |||||
| return; | |||||
| } | |||||
| $subscribers = []; | |||||
| foreach ($data['subscribers'] as $participant) { | |||||
| if ($participant->getParticipantPHID() != $data['userPHID']) { | |||||
| $subscribers[] = $participant->getParticipantPHID(); | |||||
| } | |||||
| } | |||||
| if (empty($subscribers)) { | |||||
| return; | |||||
| } | |||||
| self::sendNotifications($subscribers); | |||||
| } | |||||
| private static function sendNotifications(array $subscribers) { | |||||
| $gcm_api_key = PhabricatorEnv::getEnvConfig('webpush.gcm-api-key'); | |||||
| foreach ($subscribers as $user_phid) { | |||||
| $subscriptions = id(new PhabricatorUserWebPushSubscriber())->loadAllWhere( | |||||
| 'userPHID = %s', | |||||
| $user_phid); | |||||
| if (empty($subscriptions)) { | |||||
| continue; | |||||
| } | |||||
| foreach ($subscriptions as $subscription) { | |||||
| if (strpos($subscription->getEndpoint(), 'android.googleapis.com')) { | |||||
| $message = array( | |||||
| 'to' => $subscription->getSubscriptionId(), | |||||
| 'notification' => array( | |||||
| 'title' => 'Notification', | |||||
| 'body' => 'New Phabricator Activity', | |||||
| ), | |||||
| ); | |||||
| $server_uri = id(new PhutilURI($subscription->getEndpoint())); | |||||
| try { | |||||
| id(new HTTPSFuture($server_uri, json_encode($message))) | |||||
| ->setMethod('POST') | |||||
| ->addHeader('Content-Type', 'application/json') | |||||
| ->addHeader('Authorization', 'key='.$gcm_api_key) | |||||
| ->setTimeout(1) | |||||
| ->resolvex(); | |||||
| } catch (Exception $e) { | |||||
| phlog($e); | |||||
| } | |||||
| } else { | |||||
| $server_uri = id(new PhutilURI($subscription->getEndpoint() | |||||
| .'/'.$subscription->getSubscriptionId())); | |||||
| try { | |||||
| id(new HTTPSFuture($server_uri, | |||||
| 'version='.str_replace('.', '', microtime(true)))) | |||||
| ->setMethod('PUT') | |||||
| ->setTimeout(2) | |||||
| ->resolvex(); | |||||
| } catch (Exception $e) { | |||||
| phlog($e); | |||||
| } | |||||
| } | |||||
| } | |||||
| } | |||||
| } | |||||
| } |