This project provides an API for sending notifications to Push API subscriptions. That's it. It only gives an endpoint for creating/updating/deleting Push API subscriptions and the tools for sending notifications to them. Nothing else.

Do not expect this project to have something from this list:

  • A client-side implementation for requesting notification permission and/or subscription to push notifications.
  • A UI for creating and/or sending notifications.
  • A UI for managing configurations that might be needed for API.
  • A queue and a worker to handle notifications dispatch.

Requirements

Installation

  • Download the module and its dependencies.

    composer require drupal/web_push_api
    
  • Install the module (e.g. drush en web_push_api).

Usage

  • Generate a key-pair for Voluntary Application Server Identification (VAPID) for Web Push. Store public.key and private.key outside of your document root.

    openssl ecparam -genkey -name prime256v1 -out private.pem
    openssl ec -in private.pem -pubout -outform DER|tail -c 65|base64|tr -d '=' |tr '/+' '_-' >> public.key
    openssl ec -in private.pem -outform DER|tail -c +8|head -c 32|base64|tr -d '=' |tr '/+' '_-' >> private.key
    
  • Do a client-side implementation (like https://github.com/BR0kEN-/web-push-api or https://github.com/Minishlink/web-push-php-example) and send a created subscription to the /web-push-api/subscription (POST, PATCH or DELETE).

    The subscription on a client should be created with contents from public.key you've generated before.

    /**
     * @param {ArrayBuffer} buffer
     *
     * @return {string}
     */
    function encodeKey(buffer) {
      return btoa(String.fromCharCode(...new Uint8Array(buffer)));
    }
    
    /**
     * @param {('POST'|'PATCH'|'DELETE')} method
     * @param {PushSubscription} pushSubscription
     */
    async function sync(method, pushSubscription) {
      fetch('https://example.com/web-push-api/subscription', {
        method,
        body: {
          user_agent: navigator.userAgent,
          // The UTC offset in hours.
          utc_offset: new Date().getTimezoneOffset() / 60,
          encoding: (PushManager.supportedContentEncodings || ['aesgcm'])[0],
          endpoint: pushSubscription.endpoint,
          p256dh: encodeKey(pushSubscription.getKey('p256dh')),
          auth: encodeKey(pushSubscription.getKey('p256dh')),
        },
      });
    }
    

    The endpoint returns the {"errors": string[]} JSON structure. The errors will contain violations messages if an action you've undertaken didn't succeed. Otherwise empty.

  • Visit /admin/config/services/web-push-api/subscriptions and ensure the subscription was stored in Drupal DB.

  • Use the module's API to craft and dispatch the notification.

    namespace Drupal\MODULE;
    
    use Drupal\Component\Serialization\Json;
    use Drupal\Core\Entity\EntityTypeManagerInterface;
    use Drupal\Core\Logger\LoggerChannelFactoryInterface;
    use Drupal\Core\Logger\LoggerChannelInterface;
    use Drupal\Core\Site\Settings;
    use Drupal\Core\Utility\Error;
    use Drupal\web_push_api\Component\WebPush;
    use Drupal\web_push_api\Component\WebPushAuthVapid;
    use Drupal\web_push_api\Component\WebPushNotification;
    
    /**
     * The client for dispatching Push API notifications.
     */
    class WebPushClient {
    
      protected const BATCH_SIZE = 500;
    
      /**
       * An instance of the "entity_type.manager" service.
       *
       * @var \Drupal\Core\Entity\EntityTypeManagerInterface
       */
      protected EntityTypeManagerInterface $entityTypeManager;
    
      /**
       * The logger channel.
       *
       * @var \Drupal\Core\Logger\LoggerChannelInterface
       */
      protected LoggerChannelInterface $loggerChannel;
    
      /**
       * The Push API VAPID authorization.
       *
       * @var \Drupal\web_push_api\Component\WebPushAuthVapid
       */
      protected WebPushAuthVapid $webPushAuth;
    
      /**
       * {@inheritdoc}
       */
      public function __construct(EntityTypeManagerInterface $entity_type_manager, LoggerChannelFactoryInterface $logger_factory) {
        $settings = Settings::get('web_push_api', []);
    
        $this->entityTypeManager = $entity_type_manager;
        $this->loggerChannel = $logger_factory->get('web-push-notification');
        $this->webPushAuth = new WebPushAuthVapid($settings['public_key'] ?? '', $settings['private_key'] ?? '');
      }
    
      /**
       * Sends the notification to given subscriptions.
       *
       * @param \Drupal\web_push_api\Component\WebPush $webpush
       *   The dispatcher.
       * @param \Drupal\web_push_api\Entity\WebPushSubscription[] $subscriptions
       *   The list of subscriptions.
       * @param string $notification
       *   The notification to send.
       *
       * @throws \ErrorException
       */
      public function send(WebPush $webpush, iterable $subscriptions, string $notification): void {
        $storage = $webpush->getSubscriptionsStorage();
    
        foreach ($subscriptions as $subscription) {
          $webpush->queueNotification($subscription, $notification);
        }
    
        foreach ($webpush->flush(static::BATCH_SIZE) as $report) {
          if (!$report->isSuccess()) {
            $this->loggerChannel->error('[fail] @report', [
              '@report' => Json::encode($report),
            ]);
    
            try {
              $storage->deleteByEndpoint($report->getEndpoint());
            }
            catch (\Exception $e) {
              $this->loggerChannel->error(Error::renderExceptionSafe($e));
            }
          }
        }
      }
    
      /**
       * Sends the notification to all subscriptions.
       *
       * @param \Drupal\web_push_api\Component\WebPushNotification $notification
       *   The notification to send.
       *
       * @throws \ErrorException
       */
      public function sendToAll(WebPushNotification $notification): void {
        $webpush = new WebPush($this->entityTypeManager, $this->webPushAuth);
        $storage = $webpush->getSubscriptionsStorage();
        $count = $storage
          ->getQuery()
          ->count()
          ->execute();
    
        $batches_count = $count > static::BATCH_SIZE ? \ceil($count / static::BATCH_SIZE) : 1;
        $notification_string = (string) $notification;
    
        for ($batch_number = 0; $batch_number < $batches_count; $batch_number++) {
          $ids = $storage
            ->getQuery()
            ->range($batch_number * static::BATCH_SIZE, static::BATCH_SIZE)
            ->execute();
    
          $this->send($webpush, $storage->loadMultiple($ids), $notification_string);
        }
      }
    
      /**
       * Sends the notification to the given user.
       *
       * @param int $uid
       *   The ID of a Drupal user.
       * @param \Drupal\web_push_api\Component\WebPushNotification $notification
       *   The notification to send.
       *
       * @throws \ErrorException
       */
      public function sendToUser(int $uid, WebPushNotification $notification): void {
        $webpush = new WebPush($this->entityTypeManager, $this->webPushAuth);
    
        $this->send($webpush, $webpush->getSubscriptionsStorage()->loadByUserId($uid), (string) $notification);
      }
    
    }
    

Testing

At the moment tests could not run on Drupal.org CI due to missing gmp PHP extension. However, there is a project mirror on Github to run tests on Travis CI.

Similar projects

Supporting organizations: 

Project information

Releases