Skip to content
This repository has been archived by the owner on Jan 6, 2025. It is now read-only.

Commit

Permalink
updated docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Meier committed Feb 10, 2016
1 parent 70bfe96 commit 7706945
Show file tree
Hide file tree
Showing 8 changed files with 275 additions and 266 deletions.
14 changes: 2 additions & 12 deletions django_scarface/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Zurich'
TIME_ZONE = 'Europe/London'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'de-ch'
LANGUAGE_CODE = 'en'

SITE_ID = 1

Expand Down Expand Up @@ -195,15 +195,5 @@

INTERNAL_IPS = ('0.0.0.0', '127.0.0.1')

SOUTH_MIGRATION_MODULES = {"scarface": "scarface.migrations"}

SCARFACE_APNS_MODE = u"APNS_SANDBOX"
SCARFACE_SNS_APP_PREFIX = u"Scarface_Test"
SCARFACE_LOGGING_ENABLED = True

AWS_ACCESS_KEY = "<YOUR_AWS_ACCESS_KEY>"
AWS_SECRET_ACCESS_KEY = "<YOUR_AWS_SECRET_ACCESS_KEY>"
AWS_BUCKET = "<YOUR-BUCKET-NAME>"
SCARFACE_GCM_API_KEY = "<YOUR-GCM-API-KEY>"
SCARFACE_APNS_CERTIFICATE = "<YOUR-APNS-CERTIFICATE-KEY>"
SCARFACE_APNS_PRIVATE_KEY = "<YOUR-APNS-PRIVATE-KEY>"
239 changes: 116 additions & 123 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,162 +4,155 @@

Send push notifications to mobile devices using Amazon SNS.

**!!! Warning!!**

Version >3.0 is not compatible with versions <3.0! Migrations have changed!

## Getting Started

### Setup
You can install Scarface directly from pypi using pip::

$ pip install django-scarface

### Installation

Edit your settings.py file::
You can install Scarface directly from pypi using pip:
```zsh
pip install django-scarface
```

INSTALLED_APPS = (
...
"scarface",
)

Edit your settings.py file:

```python
INSTALLED_APPS = (
...
"scarface",
)
```

## Settings
The following settings are required:

The credentials of your AWS user. We expect the user to have all the priviliges to create Applications, Endpoints and Topics

AWS_ACCESS_KEY = "<YOUR_AWS_ACCESS_KEY>"
AWS_SECRET_ACCESS_KEY = "<YOUR_AWS_SECRET_ACCESS_KEY>"

The mode for Apple Push Notifications. Either "APNS" for production or "APNS_SANDBOX" for the sandbox environment.

SCARFACE_APNS_MODE = u"APNS_SANDBOX"

The name of the application that will be created. This name is later postfixed with the platform, for example the Application name will be 'Scarface_Test_gcm' or 'Scarface_Test_apns'

SCARFACE_SNS_APP_PREFIX = u"Scarface_Test"

Your Google Cloud Messaging Key. It is expected to be a Server-Key

SCARFACE_GCM_API_KEY = "<YOUR-GCM-API-KEY>"

The APNS certificate and private key as a string. you can create this settings by using the "manage.py extract_keys" command and a P12 file.

SCARFACE_APNS_CERTIFICATE = "<YOUR-APNS-CERTIFICATE-KEY>"
SCARFACE_APNS_PRIVATE_KEY = "<YOUR-APNS-PRIVATE-KEY>"

Enable/Disable Push message logging

SCARFACE_LOGGING_ENABLED = True (Default)
| Name | Description | Mandatory | Default |
|------|-------------|-----------|---------|
| ``AWS_ACCESS_KEY`` | Acess key of your AWS user*. | Yes | - |
| ``AWS_SECRET_ACCESS_KEY`` | Secret key of your AWS user. | Yes | - |
| ``SCARFACE_LOGGING_ENABLED`` | If true the push messages are logged to the DB.| | ``True`` |
| ``SCARFACE_PLATFORM_STRATEGIES`` | A list of [additional platform strategies](#register-new-platforms) to integrate other AWS platforms.| No | `[]`|
**We assume that user has all the privileges to create Applications, Endpoints and Topics *
p

## Management Commands
### extract_keys
You can extract the SCARFACE_APNS_CERTIFICATE and SCARFACE_APNS_PRIVATE_KEY settings from a .p12 file exported from Keychain Access. The usage is as simple as the following example:

python manage.py extract_keys --file=Certificate.p12 --password=<MYPASSWORD>

```bash
python manage.py extract_keys --file=Certificate.p12 --password=<MYPASSWORD>
```
The output can be copied and pasted into your settings file.

## Usage
The code it self is good documented. You may also check the unittests (`tests.py`) or implementation details.

### Devices Registration
Create and register the app:

apn_app = APNApplication()
apn_app.register()

Create and register the device:

push_token = "<iOS PushToken>"
ios_device = SNSDevice(apn_app, push_token)
ios_device.register_or_update()

For GCM it's the same approach. Just create an `GCMApplication`.
## Tutorial
This is a tutorial how you create AWS Applications, Platforms etc. programmatically. Alternatively you can create the modeinstances in the django admin area.

### Create Applications and Platforms
First you have to create a new application.
```python
app = Application.objects.create(name='test_application)
```

### Create Platforms
Once you have successfully created an application you can add platforms to that
it. Currently only 'Google Cloud Messaging' and 'Apple Push Notification
Service' are available. If you wish, you can [add further strategies](#register-new-platforms) to support
more platforms.
```python
apns_platform = Platform.objects.create(
platform='APNS',
application=app,
arn=TEST_ARN_TOKEN_APNS
)

gcm_platform = Platform.objects.create(
platform='GCM',
application=app,
arn=TEST_ARN_TOKEN_APNS
)
```
The available values for the platform parameter are:

| Value | Name |
|-------|------|
| ``GCM`` | Google Cloud Messaging |
| ``APNS`` | Apple Push Notification Service |
| ``APNS_SANDBOX`` | Apple Push Notification Service Sandbox |

### Create Platforms
Having a setup platform you are now ready to register new devices to that platform.
```python
apple_device = Device.objects.create(
device_id=<device_id>,
push_token=<device_push_token>,
platform=apns_platform
)
andorid_device = Device.objects.create(
device_id=<device_id>,
push_token=<device_push_token>,
platform=gcm_platform
)

apple_device.register()
android_device.register()
```

### Create Topics
Before you can subscribe a device to a topic we have to create that topic.
```python
topic = Topic.objects.create(
name='test_topic',
application = app,
)

topic.register()
```

### Subscribe to Topic
Once the platforms, devices and topics have been set up you can register the devices to topics.
```python
topic.register_device(arn_device)
```

### Deregsiter
All the above mentioned classes which support the ``register()`` method can be deregistered by using their ``deregister()`` method. Further, when you delete them, they automatically deregister.



### Send Push Notifications

Register a device like seen above.

Send a push message:

message = PushMessage(badge_count=1, context='url_alert', context_id='none',
has_new_content=True, message="Hello world!", sound="default")
ios_device.send(message)
```python
message = PushMessage(
badge_count=1,
context='url_alert',
context_id='none',
has_new_content=True,
message="Hello world!",
sound="default"
)
ios_device.send(message)
```

If logging is enabled, all sent push messages are logged in the table scarface_pushmessage.


## Examples

### Registration
def register(your_device_instance, token):
from scarface.models import SNSDevice, APNApplication, GCMApplication

"""
registers the device to sns
:param your_device_instance: the device
:param token: the push token or the registration id
"""

# get the correct notification plattform
if your_device_instance.is_ios():
application_plattform = APNApplication()
else:
application_plattform = GCMApplication()
## Register New Platforms
If you want to register a new platform create a new subclass of the abstract ``PlatformStrategy`` class. Take a look on an existin implementation for an example.

#register the application
application_plattform.register()
Then add it to the ``SCARFACE_PLATFORM_STRATEGIES`` settings parameter:
```
SCARFACE_PLATFORM_STRATEGIES = [
'path.to.my.PlatformStrategy'
]
```
By giving you own class the same ID as the one of an existing implementation, you overwrite that implementation.

# create the device resource with the token (may be the push token or the registration id)
sns_device = SNSDevice(application_plattform, token)

# register the device with sns or update the token/the attributes
sns_device.register_or_update(new_token=token, custom_user_data="customer_name={0}".format(your_device_instance.customer_name))

# this is importat: after updating or registration, your sns resource should have a arn. save this to your database.
if sns_device.arn:
your_device_instance.arn = sns_device.arn
your_device_instance.save()

### Send Push Notifications
def push(message, badge, targeted_devices):
from scarface.models import SNSDevice, APNApplication, GCMApplication, PushMessage
"""
sends a push to the targeted devices
:param message: the text message
:param badge: the new badge count (only applies to ios
"""


# set up the application. in this scenario we can target both platforms
apns = APNApplication()
gcm = GCMApplication()

# for every targeted device...
for your_device_instance in targeted_devices:
# ...get the correct application
if your_device_instance.is_ios():
application_platform = apns
else:
application_platform = gcm

# and if your device model has a arn....
if your_device_instance.arn:

# ...create the device resource...
sns_device = SNSDevice(application_platform, your_device_instance.push_token, arn=your_device_instance.arn)
# ... and the push message...
message = PushMessage(badge_count=badge, context='push', context_id='none', has_new_content=True,
message=message, sound="default")
# ...and then send it.
sns_device.send(message)

##FAQ
## FAQ

_How do I change the credentials?_

Expand Down
1 change: 1 addition & 0 deletions scarface/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class ApplicationAdmin(admin.ModelAdmin):

class PlatformAdmin(admin.ModelAdmin):
list_display = ['platform', 'application', 'arn']
exclude = ['credential', 'principal']
form = PlatformAdminForm


Expand Down
15 changes: 3 additions & 12 deletions scarface/models.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
import logging
from abc import ABCMeta, abstractmethod, abstractproperty
from abc import abstractmethod, abstractproperty
import json
from boto.exception import BotoServerError
import re
from django.db import models

from scarface.platform_strategy import APNPlatformStrategy, GCMPlatformStrategy, \
get_strategies
from scarface.platform_strategy import get_strategies
from scarface.utils import DefaultConnection, PushLogger
from scarface.exceptions import SNSNotCreatedException, PlatformNotSupported, \
SNSException, NotRegisteredException


logger = logging.getLogger('django_scarface')

# AVAILABLE_PLATFORMS = (
# ('APNS', 'Apple Push Notification Service (APNS)'),
# ('APNS_SANDBOX', 'Apple Push Notification Service Sandbox (APNS_SANDBOX)'),
# ('GCM', 'Google Cloud Messaging (GCM)'),
# )

class SNSCRUDMixin(object):

Expand Down Expand Up @@ -180,7 +174,6 @@ def resource_name(self):
def arn_key(self):
return "EndpointArn"


@DefaultConnection
def register(self, custom_user_data='', connection=None):
'''
Expand Down Expand Up @@ -669,5 +662,3 @@ def deregister(self, connection=None, save=True):
self.arn = None
if save: self.save()
return success


8 changes: 6 additions & 2 deletions scarface/platform_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@

from django.conf import settings

from scarface.settings import DEFAULT_PLATFORM_STRATEGIES
from scarface.settings import SCARFACE_DEFAULT_PLATFORM_STRATEGIES

__author__ = 'janmeier'

def get_strategies():
strategy_modules = deepcopy(DEFAULT_PLATFORM_STRATEGIES)
strategy_modules = deepcopy(SCARFACE_DEFAULT_PLATFORM_STRATEGIES)
if hasattr(settings, 'SCARFACE_PLATFORM_STRATEGIES'):
strategy_modules += settings.SCARFACE_PLATFORM_STRATEGIES

Expand Down Expand Up @@ -41,7 +41,11 @@ def __init__(self, platform_application):
super().__init__()
self.platform = platform_application


''' id which is used to refere to that strategy'''
id = ''

''' Verbose name of that strategie's service'''
service_name = ''

def format_payload(self, data):
Expand Down
2 changes: 1 addition & 1 deletion scarface/settings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
__author__ = 'janmeier'
DEFAULT_PLATFORM_STRATEGIES = [
SCARFACE_DEFAULT_PLATFORM_STRATEGIES = [
'scarface.platform_strategy.APNPlatformStrategy',
'scarface.platform_strategy.APNSSandboxPlatformStrategy',
'scarface.platform_strategy.GCMPlatformStrategy'
Expand Down
Loading

0 comments on commit 7706945

Please sign in to comment.