GithubHelp home page GithubHelp logo

br0ken- / web_push_api Goto Github PK

View Code? Open in Web Editor NEW
0.0 3.0 0.0 73 KB

Mirrors https://git.drupalcode.org/project/web_push_api

Home Page: https://drupal.org/project/web_push_api

PHP 100.00%
drupal-8 drupal-8-module

web_push_api's Introduction

Web Push API

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/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.

    <?php
    
    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;
    use Drupal\web_push_api\Component\WebPushNotificationAction;
    
    $logger = \Drupal::logger('web-push-notification');
    $webpush = new WebPush(\Drupal::entityTypeManager(), new WebPushAuthVapid('/path/to/public.key', '/path/to/private.key'));
    $storage = $webpush->getSubscriptionsStorage();
    $notification = (string) (new WebPushNotification('Hello, buddy!'))
      ->addAction(new WebPushNotificationAction('Test action', 'go-go'))
      ->setBody('This is a test notification.');
    
    foreach ($storage->loadMultiple() as $subscription) {
      $webpush->queueNotification($subscription, $notification);
    
      foreach ($webpush->flush(100) as $report) {
        if ($report->isSuccess()) {
          $logger->info('ok');
        }
        else {
          $logger->error('fail');
    
          try {
            $storage->delete([$subscription]);
            $logger->debug('subscription deleted');
          }
          catch (\Exception $e) {
            $logger->debug('unable to delete subscription');
            $logger->error(Error::renderExceptionSafe($e));
          }
        }
      }
    }

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

web_push_api's People

Contributors

br0ken- avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.