django-push-notifications
=========================
.. image:: https://jazzband.co/static/img/badge.svg
:target: https://jazzband.co/
:alt: Jazzband
.. image:: https://github.com/jazzband/django-push-notifications/workflows/Test/badge.svg
:target: https://github.com/jazzband/django-push-notifications/actions
:alt: GitHub Actions
.. image:: https://codecov.io/gh/jazzband/django-push-notifications/branch/master/graph/badge.svg?token=PcC594rhI4
:target: https://codecov.io/gh/jazzband/django-push-notifications
:alt: Code coverage
A minimal Django app that implements Device models that can send messages through APNS, FCM/GCM, WNS and WebPush.
The app implements four models: ``GCMDevice``, ``APNSDevice``, ``WNSDevice`` and ``WebPushDevice``. Those models share the same attributes:
- ``name`` (optional): A name for the device.
- ``active`` (default True): A boolean that determines whether the device will be sent notifications.
- ``user`` (optional): A foreign key to auth.User, if you wish to link the device to a specific user.
- ``device_id`` (optional): A UUID for the device obtained from Android/iOS/Windows APIs, if you wish to uniquely identify it.
- ``registration_id`` (required): The FCM/GCM registration id or the APNS token for the device.
The app also implements an admin panel, through which you can test single and bulk notifications. Select one or more
FCM/GCM, APNS, WNS or WebPush devices and in the action dropdown, select "Send test message" or "Send test message in bulk", accordingly.
Note that sending a non-bulk test message to more than one device will just iterate over the devices and send multiple
single messages.
UPDATE_ON_DUPLICATE_REG_ID: Transform create of an existing Device (based on registration id) into a update. See below Update of device with duplicate registration ID for more details.
Dependencies
------------
- Python 3.6+
- Django 2.2+
- For the API module, Django REST Framework 3.7+ is required.
- For WebPush (WP), pywebpush 1.3.0+ is required (optional). py-vapid 1.3.0+ is required for generating the WebPush private key; however this
step does not need to occur on the application server.
- For Apple Push (APNS), apns2 0.3+ is required (optional).
Setup
-----
You can install the library directly from pypi using pip:
.. code-block:: shell
$ pip install django-push-notifications[WP,APNS]
Edit your settings.py file:
.. code-block:: python
INSTALLED_APPS = (
...
"push_notifications"
)
PUSH_NOTIFICATIONS_SETTINGS = {
"FCM_API_KEY": "[your api key]",
"GCM_API_KEY": "[your api key]",
"APNS_CERTIFICATE": "/path/to/your/certificate.pem",
"APNS_TOPIC": "com.example.push_test",
"WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']",
"WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']",
"WP_PRIVATE_KEY": "/path/to/your/private.pem",
"WP_CLAIMS": {'sub': "mailto:development@example.com"}
}
.. note::
If you need to support multiple mobile applications from a single Django application, see `Multiple Application Support <https://github.com/jazzband/django-push-notifications/wiki/Multiple-Application-Support>`_ for details.
.. note::
If you are planning on running your project with ``APNS_USE_SANDBOX=True``, then make sure you have set the
*development* certificate as your ``APNS_CERTIFICATE``. Otherwise the app will not be able to connect to the correct host. See settings_ for details.
For more information about how to generate certificates, see `docs/APNS <https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst>`_.
You can learn more about APNS certificates `here <https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html>`_.
Native Django migrations are in use. ``manage.py migrate`` will install and migrate all models.
.. _settings:
Settings list
-------------
All settings are contained in a ``PUSH_NOTIFICATIONS_SETTINGS`` dict.
In order to use FCM/GCM, you are required to include ``FCM_API_KEY`` or ``GCM_API_KEY``.
For APNS, you are required to include ``APNS_CERTIFICATE``.
For WNS, you need both the ``WNS_PACKAGE_SECURITY_KEY`` and the ``WNS_SECRET_KEY``.
**General settings**
- ``USER_MODEL``: Your user model of choice. Eg. ``myapp.User``. Defaults to ``settings.AUTH_USER_MODEL``.
- ``UPDATE_ON_DUPLICATE_REG_ID``: Transform create of an existing Device (based on registration id) into a update. See below `Update of device with duplicate registration ID`_ for more details.
- ``UNIQUE_REG_ID``: Forces the ``registration_id`` field on all device models to be unique.
**APNS settings**
- ``APNS_CERTIFICATE``: Absolute path to your APNS certificate file. Certificates with passphrases are not supported. If iOS application was build with "Release" flag, you need to use production certificate, otherwise debug. Read more about `Generation of an APNS PEM file <https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst>`_.
- ``APNS_AUTH_KEY_PATH``: Absolute path to your APNS signing key file for `Token-Based Authentication <https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns>`_ . Use this instead of ``APNS_CERTIFICATE`` if you are using ``.p8`` signing key certificate.
- ``APNS_AUTH_KEY_ID``: The 10-character Key ID you obtained from your Apple developer account
- ``APNS_TEAM_ID``: 10-character Team ID you use for developing your company’s apps for iOS.
- ``APNS_TOPIC``: The topic of the remote notification, which is typically the bundle ID for your app. If you omit this header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate’s Subject as the default topic.
- ``APNS_USE_ALTERNATIVE_PORT``: Use port 2197 for APNS, instead of default port 443.
- ``APNS_USE_SANDBOX``: Use 'api.development.push.apple.com', instead of default host 'api.push.apple.com'. Default value depends on ``DEBUG`` setting of your environment: if ``DEBUG`` is True and you use production certificate, you should explicitly set ``APNS_USE_SANDBOX`` to False.
**FCM/GCM settings**
- ``FCM_API_KEY``: Your API key for Firebase Cloud Messaging.
- ``FCM_POST_URL``: The full url that FCM notifications will be POSTed to. Defaults to https://fcm.googleapis.com/fcm/send.
- ``FCM_MAX_RECIPIENTS``: The maximum amount of recipients that can be contained per bulk message. If the ``registration_ids`` list is larger than that number, multiple bulk messages will be sent. Defaults to 1000 (the maximum amount supported by FCM).
- ``FCM_ERROR_TIMEOUT``: The timeout on FCM POSTs.
- ``GCM_API_KEY``, ``GCM_POST_URL``, ``GCM_MAX_RECIPIENTS``, ``GCM_ERROR_TIMEOUT``: Same parameters for GCM
**WNS settings**
- ``WNS_PACKAGE_SECURITY_KEY``: TODO
- ``WNS_SECRET_KEY``: TODO
**WP settings**
- ``WP_PRIVATE_KEY``: Absolute path to your private certificate file: os.path.join(BASE_DIR, "private_key.pem")
- ``WP_CLAIMS``: Dictionary with default value for the sub, (subject), sent to the webpush service, This would be used by the service if they needed to reach out to you (the sender). Could be a url or mailto e.g. {'sub': "mailto:development@example.com"}.
- ``WP_ERROR_TIMEOUT``: The timeout on WebPush POSTs. (Optional)
For more information about how to configure WebPush, see `docs/WebPush <https://github.com/jazzband/django-push-notifications/blob/master/docs/WebPush.rst>`_.
Sending messages
----------------
FCM/GCM and APNS services have slightly different semantics. The app tries to offer a common interface for both when using the models.
.. code-block:: python
from push_notifications.models import APNSDevice, GCMDevice
device = GCMDevice.objects.get(registration_id=gcm_reg_id)
# The first argument will be sent as "message" to the intent extras Bundle
# Retrieve it with intent.getExtras().getString("message")
device.send_message("You've got mail")
# If you want to customize, send an extra dict and a None message.
# the extras dict will be mapped into the intent extras Bundle.
# For dicts where all values are keys this will be sent as url parameters,
# but for more complex nested collections the extras dict will be sent via
# the bulk message api.
device.send_message(None, extra={"foo": "bar"})
device = APNSDevice.objects.get(registration_id=apns_token)
device.send_message("You've got mail") # Alert message may only be sent as text.
device.send_message(None, badge=5) # No alerts but with badge.
device.send_message(None, content_available=1, extra={"foo": "bar"}) # Silent message with custom data.
# alert with title and body.
device.send_message(message={"title" : "Game Request", "body" : "Bob wants to play poker"}, extra={"foo": "bar"})
device.send_message("Hello again", thread_id="123", extra={"foo": "bar"}) # set thread-id to allow iOS to merge notifications
.. note::
APNS does not support sending payloads that exceed 2048 bytes (increased from 256 in 2014).
The message is only one part of the payload, if
once constructed the payload exceeds the maximum size, an ``APNSDataOverflow`` exception will be raised before anything is sent.
Reference: `Apple Payload Documentation <https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1>`_
Web Push accepts only one variable (``message``), which is passed directly to pywebpush. This message can be a simple string, which will be used as your notification's body, or it can be contain `any data supported by pywebpush<https://github.com/web-push-libs/pywebpush>`.
Simple example:
.. code-block:: python
from push_notifications.models import WebPushDevice
device = WebPushDevice.objects.get(registration_id=wp_reg_id)
device.send_message("You've got mail")
.. note::
To customize the notification title using this method, edit the ``"TITLE DEFAULT"`` string in your ``navigatorPush.service.js`` file.
JSON example:
.. code-block:: python
import json
from push_notifications.models import WebPushDevice
device = WebPushDevice.objects.get(registration_id=wp_reg_id)
title = "Message Received"
message = "You've got mail"
data = json.dumps({"title": title, "message": message})
device.send_message(data)
Sending messages in bulk
------------------------
.. code-block:: python
from push_notifications.models import APNSDevice, GCMDevice
devices = GCMDevice.objects.filter(user__first_name="James")
devices.send_message("Happy name day!")
Sending messages in bulk makes use of the bulk mechanics offered by GCM and APNS. It is almost always preferable to send
bulk notifications instead of single ones.
It's also possible to pass badge parameter as a function which accepts token parameter in order to set different badge
value per user. Assuming User model has a method get_badge returning badge count for a user:
.. code-block:: python
devices.send_message(
"Happy name day!",
badge=lambda token: APNSDevice.objects.get(registration_id=token).user.get_badge()
)
Firebase vs Google Cloud Messaging
----------------------------------
``django-push-notifications`` supports both Google Cloud Messaging and Firebase Cloud Messaging (which is now the officially supported messaging platform from Google). When registering a device, you must pass the ``cloud_message_type`` parameter to set the cloud type that matches the device needs.
This is currently defaulting to ``'GCM'``, but may change to ``'FCM'`` at some point. You are encouraged to use the `officially supported library <https://developers.google.com/cloud-messaging/faq>`_.
When using FCM, ``django-push-notifications`` will automatically use the `notification and data messages format <https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages>`_ to be conveniently handled by Firebase devices. You may want to check the payload to see if it matches your needs, and review your notification statuses in `FCM Diagnostic console <https://support.google.com/googleplay/android-developer/answer/2663268?hl=en>`_.
.. code-block:: python
# Create a FCM device
fcm_device = GCMDevice.objects.create(registration_id="token", cloud_message_type="FCM", user=the_user)
# Send a notification message
fcm_device.send_message("This is a message")
# Send a notification message with additionnal payload
fcm_device.send_message("This is a enriched message", extra={"title": "Notification title", "icon": "icon_ressource"})
# Send a notification message with additionnal payload (alternative syntax)
fcm_device.send_message("This is a enriched message", title="Notification title", badge=6)
# Send a notification message with extra data
fcm_device.send_message("This is a message with data", extra={"other": "content", "misc": "data"})
# Send a notification message with options
fcm_device.send_message("This is a message", time_to_live=3600)
# Send a data message only
fcm_device.send_message(None, extra={"other": "content", "misc": "data"})
You can disable this default behaviour by setting ``use_fcm_notifications`` to ``False``.
.. code-block:: python
fcm_device = GCMDevice.objects.create(registration_id="token", cloud_message_type="FCM", user=the_user)
# Send a data message with classic format
fcm_device.send_message("This is a message", use_fcm_notifications=False)
Sending FCM/GCM messages to topic members
-----------------------------------------
FCM/GCM topic messaging allows your app server to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app. Developers can choose any topic name that matches the regular expression, "/topics/[a-zA-Z0-9-_.~%]+".
Note: gcm_send_bulk_message must be used when sending messages to topic subscribers, and setting the first param to any value other than None will result in a 400 Http error.
.. code-block:: python
from push_notifications.gcm import send_message
# First param is "None" because no Registration_id is needed, the message will be sent to all devices subscribed to the topic.
send_message(None, {"body": "Hello members of my_topic!"}, cloud_type="FCM", to="/topics/my_topic")
Reference: `FCM Documentation <https://firebase.google.com/docs/cloud-messaging/android/topic-messaging>`_
Exceptions
----------
- ``NotificationError(Exception)``: Base exception for all notification-related errors.
- ``gcm.GCMError(NotificationError)``: An error was returned by GCM. This is never raised when using bulk notifications.
- ``apns.APNSError(NotificationError)``: Something went wrong upon sending APNS notifications.
- ``apns.APNSDataOverflow(APNSError)``: The APNS payload exceeds its maximum size and cannot be sent.
Django REST Framework (DRF) support
-----------------------------------
ViewSets are available for both APNS and GCM devices in two permission flavors:
- ``APNSDeviceViewSet`` and ``GCMDeviceViewSet``
- Permissions as specified in settings (``AllowAny`` by default, which is not recommended)
- A device may be registered without associating it with a user
- ``APNSDeviceAuthorizedViewSet`` and ``GCMDeviceAuthorizedViewSet``
- Permissions are ``IsAuthenticated`` and custom permission ``IsOwner``, which will only allow the ``request.user`` to get and update devices that belong to that user
- Requires a user to be authenticated, so all devices will be associated with a user
When creating an ``APNSDevice``, the ``registration_id`` is validated to be a 64-character or 200-character hexadecimal string. Since 2016, device tokens are to be increased from 32 bytes to 100 bytes.
Routes can be added one of two ways:
- Routers_ (include all views)
.. _Routers: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers#using-routers
::
from push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet, GCMDeviceAuthorizedViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'device/apns', APNSDeviceAuthorizedViewSet)
router.register(r'device/gcm', GCMDeviceAuthorizedViewSet)
urlpatterns = patterns('',
# URLs will show up at <api_root>/device/apns
url(r'^', include(router.urls)),
# ...
)
- Using as_view_ (specify which views to include)
.. _as_view: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers#binding-viewsets-to-urls-explicitly
::
from push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet
urlpatterns = patterns('',
# Only allow creation of devices by authenticated users
url(r'^device/apns/?$', APNSDeviceAuthorizedViewSet.as_view({'post': 'create'}), name='create_apns_device'),
# ...
)
Update of device with duplicate registration ID
-----------------------------------------------
The DRF viewset enforce the uniqueness of the registration ID. In same use case it
may cause issue: If an already registered mobile change its user and it will
fail to register because the registration ID already exist.
When option ``UPDATE_ON_DUPLICATE_REG_ID`` is set to True, then any creation of
device with an already existing registration ID will be transformed into an update.
The ``UPDATE_ON_DUPLICATE_REG_ID`` only works with DRF.
.. [1] Any devices which are not selected, but are not receiving notifications will not be deactivated on a subsequent call to "prune devices" unless another attempt to send a message to the device fails after the call to the feedback service.
Raw data
{
"_id": null,
"home_page": "https://github.com/silverlogic/django-push-notifications",
"name": "baseapp-django-push-notifications",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.6",
"maintainer_email": null,
"keywords": null,
"author": "Jerome Leclanche",
"author_email": "jerome@leclan.ch",
"download_url": "https://files.pythonhosted.org/packages/ea/1e/ad766029463ba6dec51691b21550ebee717336b90971e99470d1f2906d5f/baseapp-django-push-notifications-3.0.3rc2.tar.gz",
"platform": null,
"description": "django-push-notifications\n=========================\n\n.. image:: https://jazzband.co/static/img/badge.svg\n :target: https://jazzband.co/\n :alt: Jazzband\n\n.. image:: https://github.com/jazzband/django-push-notifications/workflows/Test/badge.svg\n :target: https://github.com/jazzband/django-push-notifications/actions\n :alt: GitHub Actions\n\n.. image:: https://codecov.io/gh/jazzband/django-push-notifications/branch/master/graph/badge.svg?token=PcC594rhI4\n :target: https://codecov.io/gh/jazzband/django-push-notifications\n :alt: Code coverage\n\nA minimal Django app that implements Device models that can send messages through APNS, FCM/GCM, WNS and WebPush.\n\nThe app implements four models: ``GCMDevice``, ``APNSDevice``, ``WNSDevice`` and ``WebPushDevice``. Those models share the same attributes:\n - ``name`` (optional): A name for the device.\n - ``active`` (default True): A boolean that determines whether the device will be sent notifications.\n - ``user`` (optional): A foreign key to auth.User, if you wish to link the device to a specific user.\n - ``device_id`` (optional): A UUID for the device obtained from Android/iOS/Windows APIs, if you wish to uniquely identify it.\n - ``registration_id`` (required): The FCM/GCM registration id or the APNS token for the device.\n\n\nThe app also implements an admin panel, through which you can test single and bulk notifications. Select one or more\nFCM/GCM, APNS, WNS or WebPush devices and in the action dropdown, select \"Send test message\" or \"Send test message in bulk\", accordingly.\nNote that sending a non-bulk test message to more than one device will just iterate over the devices and send multiple\nsingle messages.\nUPDATE_ON_DUPLICATE_REG_ID: Transform create of an existing Device (based on registration id) into a update. See below Update of device with duplicate registration ID for more details.\n\nDependencies\n------------\n- Python 3.6+\n- Django 2.2+\n- For the API module, Django REST Framework 3.7+ is required.\n- For WebPush (WP), pywebpush 1.3.0+ is required (optional). py-vapid 1.3.0+ is required for generating the WebPush private key; however this\n step does not need to occur on the application server.\n- For Apple Push (APNS), apns2 0.3+ is required (optional).\n\nSetup\n-----\nYou can install the library directly from pypi using pip:\n\n.. code-block:: shell\n\n\t$ pip install django-push-notifications[WP,APNS]\n\n\nEdit your settings.py file:\n\n.. code-block:: python\n\n\tINSTALLED_APPS = (\n\t\t...\n\t\t\"push_notifications\"\n\t)\n\n\tPUSH_NOTIFICATIONS_SETTINGS = {\n\t\t\"FCM_API_KEY\": \"[your api key]\",\n\t\t\"GCM_API_KEY\": \"[your api key]\",\n\t\t\"APNS_CERTIFICATE\": \"/path/to/your/certificate.pem\",\n\t\t\"APNS_TOPIC\": \"com.example.push_test\",\n\t\t\"WNS_PACKAGE_SECURITY_ID\": \"[your package security id, e.g: 'ms-app://e-3-4-6234...']\",\n\t\t\"WNS_SECRET_KEY\": \"[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']\",\n\t\t\"WP_PRIVATE_KEY\": \"/path/to/your/private.pem\",\n\t\t\"WP_CLAIMS\": {'sub': \"mailto:development@example.com\"}\n\t}\n\n.. note::\n If you need to support multiple mobile applications from a single Django application, see `Multiple Application Support <https://github.com/jazzband/django-push-notifications/wiki/Multiple-Application-Support>`_ for details.\n\n.. note::\n\tIf you are planning on running your project with ``APNS_USE_SANDBOX=True``, then make sure you have set the\n\t*development* certificate as your ``APNS_CERTIFICATE``. Otherwise the app will not be able to connect to the correct host. See settings_ for details.\n\n\nFor more information about how to generate certificates, see `docs/APNS <https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst>`_.\n\nYou can learn more about APNS certificates `here <https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html>`_.\n\nNative Django migrations are in use. ``manage.py migrate`` will install and migrate all models.\n\n.. _settings:\n\nSettings list\n-------------\nAll settings are contained in a ``PUSH_NOTIFICATIONS_SETTINGS`` dict.\n\nIn order to use FCM/GCM, you are required to include ``FCM_API_KEY`` or ``GCM_API_KEY``.\nFor APNS, you are required to include ``APNS_CERTIFICATE``.\nFor WNS, you need both the ``WNS_PACKAGE_SECURITY_KEY`` and the ``WNS_SECRET_KEY``.\n\n**General settings**\n\n- ``USER_MODEL``: Your user model of choice. Eg. ``myapp.User``. Defaults to ``settings.AUTH_USER_MODEL``.\n- ``UPDATE_ON_DUPLICATE_REG_ID``: Transform create of an existing Device (based on registration id) into a update. See below `Update of device with duplicate registration ID`_ for more details.\n- ``UNIQUE_REG_ID``: Forces the ``registration_id`` field on all device models to be unique.\n\n**APNS settings**\n\n- ``APNS_CERTIFICATE``: Absolute path to your APNS certificate file. Certificates with passphrases are not supported. If iOS application was build with \"Release\" flag, you need to use production certificate, otherwise debug. Read more about `Generation of an APNS PEM file <https://github.com/jazzband/django-push-notifications/blob/master/docs/APNS.rst>`_.\n- ``APNS_AUTH_KEY_PATH``: Absolute path to your APNS signing key file for `Token-Based Authentication <https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/establishing_a_token-based_connection_to_apns>`_ . Use this instead of ``APNS_CERTIFICATE`` if you are using ``.p8`` signing key certificate.\n- ``APNS_AUTH_KEY_ID``: The 10-character Key ID you obtained from your Apple developer account\n- ``APNS_TEAM_ID``: 10-character Team ID you use for developing your company\u2019s apps for iOS.\n- ``APNS_TOPIC``: The topic of the remote notification, which is typically the bundle ID for your app. If you omit this header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate\u2019s Subject as the default topic.\n- ``APNS_USE_ALTERNATIVE_PORT``: Use port 2197 for APNS, instead of default port 443.\n- ``APNS_USE_SANDBOX``: Use 'api.development.push.apple.com', instead of default host 'api.push.apple.com'. Default value depends on ``DEBUG`` setting of your environment: if ``DEBUG`` is True and you use production certificate, you should explicitly set ``APNS_USE_SANDBOX`` to False.\n\n**FCM/GCM settings**\n\n- ``FCM_API_KEY``: Your API key for Firebase Cloud Messaging.\n- ``FCM_POST_URL``: The full url that FCM notifications will be POSTed to. Defaults to https://fcm.googleapis.com/fcm/send.\n- ``FCM_MAX_RECIPIENTS``: The maximum amount of recipients that can be contained per bulk message. If the ``registration_ids`` list is larger than that number, multiple bulk messages will be sent. Defaults to 1000 (the maximum amount supported by FCM).\n- ``FCM_ERROR_TIMEOUT``: The timeout on FCM POSTs.\n- ``GCM_API_KEY``, ``GCM_POST_URL``, ``GCM_MAX_RECIPIENTS``, ``GCM_ERROR_TIMEOUT``: Same parameters for GCM\n\n**WNS settings**\n\n- ``WNS_PACKAGE_SECURITY_KEY``: TODO\n- ``WNS_SECRET_KEY``: TODO\n\n**WP settings**\n\n- ``WP_PRIVATE_KEY``: Absolute path to your private certificate file: os.path.join(BASE_DIR, \"private_key.pem\")\n- ``WP_CLAIMS``: Dictionary with default value for the sub, (subject), sent to the webpush service, This would be used by the service if they needed to reach out to you (the sender). Could be a url or mailto e.g. {'sub': \"mailto:development@example.com\"}.\n- ``WP_ERROR_TIMEOUT``: The timeout on WebPush POSTs. (Optional)\n\nFor more information about how to configure WebPush, see `docs/WebPush <https://github.com/jazzband/django-push-notifications/blob/master/docs/WebPush.rst>`_.\n\n\nSending messages\n----------------\nFCM/GCM and APNS services have slightly different semantics. The app tries to offer a common interface for both when using the models.\n\n.. code-block:: python\n\n\tfrom push_notifications.models import APNSDevice, GCMDevice\n\n\tdevice = GCMDevice.objects.get(registration_id=gcm_reg_id)\n\t# The first argument will be sent as \"message\" to the intent extras Bundle\n\t# Retrieve it with intent.getExtras().getString(\"message\")\n\tdevice.send_message(\"You've got mail\")\n\t# If you want to customize, send an extra dict and a None message.\n\t# the extras dict will be mapped into the intent extras Bundle.\n\t# For dicts where all values are keys this will be sent as url parameters,\n\t# but for more complex nested collections the extras dict will be sent via\n\t# the bulk message api.\n\tdevice.send_message(None, extra={\"foo\": \"bar\"})\n\n\tdevice = APNSDevice.objects.get(registration_id=apns_token)\n\tdevice.send_message(\"You've got mail\") # Alert message may only be sent as text.\n\tdevice.send_message(None, badge=5) # No alerts but with badge.\n\tdevice.send_message(None, content_available=1, extra={\"foo\": \"bar\"}) # Silent message with custom data.\n\t# alert with title and body.\n\tdevice.send_message(message={\"title\" : \"Game Request\", \"body\" : \"Bob wants to play poker\"}, extra={\"foo\": \"bar\"})\n\tdevice.send_message(\"Hello again\", thread_id=\"123\", extra={\"foo\": \"bar\"}) # set thread-id to allow iOS to merge notifications\n\n.. note::\n\tAPNS does not support sending payloads that exceed 2048 bytes (increased from 256 in 2014).\n\tThe message is only one part of the payload, if\n\tonce constructed the payload exceeds the maximum size, an ``APNSDataOverflow`` exception will be raised before anything is sent.\n\tReference: `Apple Payload Documentation <https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1>`_\n\nWeb Push accepts only one variable (``message``), which is passed directly to pywebpush. This message can be a simple string, which will be used as your notification's body, or it can be contain `any data supported by pywebpush<https://github.com/web-push-libs/pywebpush>`.\n\nSimple example:\n\n.. code-block:: python\n\n\tfrom push_notifications.models import WebPushDevice\n\n\tdevice = WebPushDevice.objects.get(registration_id=wp_reg_id)\n\n\tdevice.send_message(\"You've got mail\")\n\n.. note::\n\tTo customize the notification title using this method, edit the ``\"TITLE DEFAULT\"`` string in your ``navigatorPush.service.js`` file.\n\nJSON example:\n\n.. code-block:: python\n\n\timport json\n\tfrom push_notifications.models import WebPushDevice\n\n\tdevice = WebPushDevice.objects.get(registration_id=wp_reg_id)\n\n\ttitle = \"Message Received\"\n\tmessage = \"You've got mail\"\n\tdata = json.dumps({\"title\": title, \"message\": message})\n\n\tdevice.send_message(data)\n\n\nSending messages in bulk\n------------------------\n.. code-block:: python\n\n\tfrom push_notifications.models import APNSDevice, GCMDevice\n\n\tdevices = GCMDevice.objects.filter(user__first_name=\"James\")\n\tdevices.send_message(\"Happy name day!\")\n\nSending messages in bulk makes use of the bulk mechanics offered by GCM and APNS. It is almost always preferable to send\nbulk notifications instead of single ones.\n\nIt's also possible to pass badge parameter as a function which accepts token parameter in order to set different badge\nvalue per user. Assuming User model has a method get_badge returning badge count for a user:\n\n.. code-block:: python\n\n\tdevices.send_message(\n\t\t\"Happy name day!\",\n\t\tbadge=lambda token: APNSDevice.objects.get(registration_id=token).user.get_badge()\n\t)\n\nFirebase vs Google Cloud Messaging\n----------------------------------\n\n``django-push-notifications`` supports both Google Cloud Messaging and Firebase Cloud Messaging (which is now the officially supported messaging platform from Google). When registering a device, you must pass the ``cloud_message_type`` parameter to set the cloud type that matches the device needs.\nThis is currently defaulting to ``'GCM'``, but may change to ``'FCM'`` at some point. You are encouraged to use the `officially supported library <https://developers.google.com/cloud-messaging/faq>`_.\n\nWhen using FCM, ``django-push-notifications`` will automatically use the `notification and data messages format <https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages>`_ to be conveniently handled by Firebase devices. You may want to check the payload to see if it matches your needs, and review your notification statuses in `FCM Diagnostic console <https://support.google.com/googleplay/android-developer/answer/2663268?hl=en>`_.\n\n\n.. code-block:: python\n\n\t# Create a FCM device\n\tfcm_device = GCMDevice.objects.create(registration_id=\"token\", cloud_message_type=\"FCM\", user=the_user)\n\n\t# Send a notification message\n\tfcm_device.send_message(\"This is a message\")\n\n\t# Send a notification message with additionnal payload\n\tfcm_device.send_message(\"This is a enriched message\", extra={\"title\": \"Notification title\", \"icon\": \"icon_ressource\"})\n\n\t# Send a notification message with additionnal payload (alternative syntax)\n\tfcm_device.send_message(\"This is a enriched message\", title=\"Notification title\", badge=6)\n\n\t# Send a notification message with extra data\n\tfcm_device.send_message(\"This is a message with data\", extra={\"other\": \"content\", \"misc\": \"data\"})\n\n\t# Send a notification message with options\n\tfcm_device.send_message(\"This is a message\", time_to_live=3600)\n\n\t# Send a data message only\n\tfcm_device.send_message(None, extra={\"other\": \"content\", \"misc\": \"data\"})\n\nYou can disable this default behaviour by setting ``use_fcm_notifications`` to ``False``.\n\n.. code-block:: python\n\n\tfcm_device = GCMDevice.objects.create(registration_id=\"token\", cloud_message_type=\"FCM\", user=the_user)\n\n\t# Send a data message with classic format\n\tfcm_device.send_message(\"This is a message\", use_fcm_notifications=False)\n\n\nSending FCM/GCM messages to topic members\n-----------------------------------------\nFCM/GCM topic messaging allows your app server to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app. Developers can choose any topic name that matches the regular expression, \"/topics/[a-zA-Z0-9-_.~%]+\".\nNote: gcm_send_bulk_message must be used when sending messages to topic subscribers, and setting the first param to any value other than None will result in a 400 Http error.\n\n.. code-block:: python\n\n\tfrom push_notifications.gcm import send_message\n\n # First param is \"None\" because no Registration_id is needed, the message will be sent to all devices subscribed to the topic.\n send_message(None, {\"body\": \"Hello members of my_topic!\"}, cloud_type=\"FCM\", to=\"/topics/my_topic\")\n\nReference: `FCM Documentation <https://firebase.google.com/docs/cloud-messaging/android/topic-messaging>`_\n\nExceptions\n----------\n\n- ``NotificationError(Exception)``: Base exception for all notification-related errors.\n- ``gcm.GCMError(NotificationError)``: An error was returned by GCM. This is never raised when using bulk notifications.\n- ``apns.APNSError(NotificationError)``: Something went wrong upon sending APNS notifications.\n- ``apns.APNSDataOverflow(APNSError)``: The APNS payload exceeds its maximum size and cannot be sent.\n\nDjango REST Framework (DRF) support\n-----------------------------------\n\nViewSets are available for both APNS and GCM devices in two permission flavors:\n\n- ``APNSDeviceViewSet`` and ``GCMDeviceViewSet``\n\n\t- Permissions as specified in settings (``AllowAny`` by default, which is not recommended)\n\t- A device may be registered without associating it with a user\n\n- ``APNSDeviceAuthorizedViewSet`` and ``GCMDeviceAuthorizedViewSet``\n\n\t- Permissions are ``IsAuthenticated`` and custom permission ``IsOwner``, which will only allow the ``request.user`` to get and update devices that belong to that user\n\t- Requires a user to be authenticated, so all devices will be associated with a user\n\nWhen creating an ``APNSDevice``, the ``registration_id`` is validated to be a 64-character or 200-character hexadecimal string. Since 2016, device tokens are to be increased from 32 bytes to 100 bytes.\n\nRoutes can be added one of two ways:\n\n- Routers_ (include all views)\n\n.. _Routers: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers#using-routers\n\n::\n\n\tfrom push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet, GCMDeviceAuthorizedViewSet\n\tfrom rest_framework.routers import DefaultRouter\n\n\trouter = DefaultRouter()\n\trouter.register(r'device/apns', APNSDeviceAuthorizedViewSet)\n\trouter.register(r'device/gcm', GCMDeviceAuthorizedViewSet)\n\n\turlpatterns = patterns('',\n\t\t# URLs will show up at <api_root>/device/apns\n\t\turl(r'^', include(router.urls)),\n\t\t# ...\n\t)\n\n- Using as_view_ (specify which views to include)\n\n.. _as_view: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers#binding-viewsets-to-urls-explicitly\n\n::\n\n\tfrom push_notifications.api.rest_framework import APNSDeviceAuthorizedViewSet\n\n\turlpatterns = patterns('',\n\t\t# Only allow creation of devices by authenticated users\n\t\turl(r'^device/apns/?$', APNSDeviceAuthorizedViewSet.as_view({'post': 'create'}), name='create_apns_device'),\n\t\t# ...\n\t)\n\nUpdate of device with duplicate registration ID\n-----------------------------------------------\n\nThe DRF viewset enforce the uniqueness of the registration ID. In same use case it\nmay cause issue: If an already registered mobile change its user and it will\nfail to register because the registration ID already exist.\n\nWhen option ``UPDATE_ON_DUPLICATE_REG_ID`` is set to True, then any creation of\ndevice with an already existing registration ID will be transformed into an update.\n\nThe ``UPDATE_ON_DUPLICATE_REG_ID`` only works with DRF.\n\n\n.. [1] Any devices which are not selected, but are not receiving notifications will not be deactivated on a subsequent call to \"prune devices\" unless another attempt to send a message to the device fails after the call to the feedback service.\n",
"bugtrack_url": null,
"license": null,
"summary": "Send push notifications to mobile devices through GCM, APNS or WNS and to WebPush (Chrome, Firefox and Opera) in Django",
"version": "3.0.3rc2",
"project_urls": {
"Download": "https://github.com/silverlogic/django-push-notifications/tarball/master",
"Homepage": "https://github.com/silverlogic/django-push-notifications"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "b5feb1303e8ddb885c787a9de0c635a7dbd9b35531f3c4347084e693c6f7de14",
"md5": "ba1e88cc057fa2cf6cccdedde5d92085",
"sha256": "176b6e089f106bd53277a4b410d4672d3a6051fd8b385938a67df54fd62cf180"
},
"downloads": -1,
"filename": "baseapp_django_push_notifications-3.0.3rc2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "ba1e88cc057fa2cf6cccdedde5d92085",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6",
"size": 43632,
"upload_time": "2024-04-11T18:51:31",
"upload_time_iso_8601": "2024-04-11T18:51:31.851091Z",
"url": "https://files.pythonhosted.org/packages/b5/fe/b1303e8ddb885c787a9de0c635a7dbd9b35531f3c4347084e693c6f7de14/baseapp_django_push_notifications-3.0.3rc2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ea1ead766029463ba6dec51691b21550ebee717336b90971e99470d1f2906d5f",
"md5": "d6d7fad48a3f84b05dce4e38cbe9e513",
"sha256": "b98adfb001937c54a17d97daeb385fe6c1f8c2218c8300f39f86817576363be6"
},
"downloads": -1,
"filename": "baseapp-django-push-notifications-3.0.3rc2.tar.gz",
"has_sig": false,
"md5_digest": "d6d7fad48a3f84b05dce4e38cbe9e513",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 59724,
"upload_time": "2024-04-11T18:51:33",
"upload_time_iso_8601": "2024-04-11T18:51:33.720191Z",
"url": "https://files.pythonhosted.org/packages/ea/1e/ad766029463ba6dec51691b21550ebee717336b90971e99470d1f2906d5f/baseapp-django-push-notifications-3.0.3rc2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-04-11 18:51:33",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "silverlogic",
"github_project": "django-push-notifications",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "baseapp-django-push-notifications"
}