# Message Wrapper 4Sure #

This is a Django application that can be added to a project to add an easy interface into sending and receiving
messages via various message brokers.

### Currently implemented ###
* AWS SNS

### What is this repository for? ###

* Easily register a message topic
* Publish a message to a topic
* Create an endpoint to receive messages that auto-confirms subscriptions
* Manage subscriptions through Django Admin
* Provide a place to record all outbound messages.

### How do I get set up? ###

Assuming you have a supported version of Python, you can first set up your virtual environment with:
```shell
$ python -m venv .venv
...
$ . .venv/bin/activate
```
Then, you can install message-wrapper-4sure with:
```shell
pip install --index-url https://pypi.4-sure.net message-wrapper-4sure
```
### Configuring Boto3 ###
To use SNS you will require AWS credentials\
Set up credentials (in e.g. `~/.aws/credentials`):
```ini
[default]
aws_access_key_id = YOUR_KEY
aws_secret_access_key = YOUR_SECRET
```
Then, set up a default region (in e.g. `~/.aws/config`):
```ini
[default]
region=af-south-1
```
Alternatively you can also use environment variables:
```shell
AWS_ACCESS_KEY_ID - The access key for your AWS account.
AWS_SECRET_ACCESS_KEY - The secret key for your AWS account.
AWS_DEFAULT_REGION - The default AWS Region to use
```
### Configure your setting.py file ###
add messiging into INSTALLED_APPS: 
```python
INSTALLED_APPS = [
    ...,
    'messaging',
]
```
Migrate the database for Message Wrapper:
```shell
python manage.py migrate 
```
## Usage ##
### For outbound ###
To publish a message:
```python
from messaging.topic_providers import MessageWrapper

mw = MessageWrapper.get('sns')
mw.publish('topic', 'message')
```
It is preferred that the message is a json serializable.

### Inbound messaging ###
To receive messages from SNS is a 2-step process.

#### Step 1: Create an API endpoint to receive the message. ####
Create a ViewsetClass in your `views.py`:
```python
from messaging.views import SNSActionAPIView
from messaging.decorators import validate_sns_message_signature

    
class SharedDataMessageReceiver(SNSActionAPIView):
    @validate_sns_message_signature
    def generic_handler(self, request, params, *args, **kwargs):
        topic = params['TopicArn'].split('_')[1:]
        print(f"{topic}: {params['Message']}")
        # ...
        return ""

```
Don't forget to register it in your `urls.py`:
```python
urlpatterns = [
    ...
    re_path(
        '^api/v1/message_receiver/(?P<action>[^/.]+)', SharedDataMessageReceiver.as_view(),
        name='message_receiver'),
]
```


#### Step 2: Subscribe a endpoint to a topic. ####
Click on Topic Callback in Django Admin:\
![img.png](img.png)

Add a callback

![img_1.png](img_1.png)


AWS SNS will automatically attempt to send a confirmation message to the endpoint.\
If using the provided SNSActionAPI and decorators this proces will happen automatically.