├── .dockerignore ├── .flake8 ├── .gitignore ├── .travis.yml ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── django_sloop ├── __init__.py ├── admin.py ├── apps.py ├── exceptions.py ├── handlers.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_change_meta.py │ └── __init__.py ├── models.py ├── serializers.py ├── settings.py ├── tasks.py ├── templates │ └── django_sloop │ │ └── push_notification.html ├── tests.py ├── urls.py ├── utils.py └── views.py ├── docs └── img │ ├── splash.jpg │ └── splash.psd ├── manage.py ├── pytest.ini ├── requirements.txt ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── test_app ├── __init__.py ├── celery.py ├── devices │ ├── __init__.py │ ├── admin.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ └── models.py ├── settings │ ├── __init__.py │ ├── base.py │ └── local.py ├── urls.py ├── users │ ├── __init__.py │ ├── admin.py │ └── models.py └── wsgi.py └── tox.ini /.dockerignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | env/ 3 | *.egg-info 4 | .idea 5 | .pypirc 6 | .tox/ 7 | .cache/ 8 | .coverage 9 | coverage.xml 10 | .coverage 11 | *.pyc 12 | __pycache__ 13 | .DS_Store 14 | *.sqlite* -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E501,F403,F405,E126,E121,W503 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | !.gitignore 3 | dist/ 4 | env/ 5 | dist/ 6 | *.egg-info 7 | .idea 8 | .pypirc 9 | .tox/ 10 | .cache/ 11 | coverage.xml 12 | .coverage 13 | __pycache__ 14 | .DS_Store 15 | *.sqlite* -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | dist: xenial 4 | 5 | python: 6 | - "2.7" 7 | - "3.5" 8 | - "3.6" 9 | - "3.7" 10 | 11 | install: 12 | - pip install tox-travis 13 | - pip install codecov 14 | - sudo apt-get install gdal-bin 15 | 16 | script: 17 | - tox 18 | 19 | notifications: 20 | email: false 21 | 22 | after_success: 23 | - codecov 24 | 25 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | 3 | # Needed to be able to install python versions. 4 | RUN apt-get update && apt-get install -y software-properties-common 5 | RUN add-apt-repository ppa:deadsnakes/ppa 6 | 7 | RUN apt-get update && apt-get install -y \ 8 | python3.5 \ 9 | python3.6 \ 10 | python3.7 \ 11 | libpq-dev \ 12 | gdal-bin \ 13 | python3-distutils \ 14 | python3-pip 15 | 16 | WORKDIR /app 17 | 18 | COPY requirements.txt . 19 | COPY requirements_dev.txt . 20 | 21 | RUN pip3 install --upgrade pip 22 | RUN pip3 install tox 23 | RUN pip3 install -r requirements_dev.txt -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | graft django_sloop 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Sloop](/docs/img/splash.jpg?raw=true "Django-Sloop") 2 | 3 | This package contains some tools that will ease the implementation of push notifications using AWS SNS and other backends into django projects. 4 | 5 | # Django-Sloop 6 | 7 | ## Installation 8 | 9 | 1. Install the package via Github or PIP (pip install django-sloop) 10 | 11 | 2. Add **django_sloop** to the INSTALLED_APPS list in the settings file. 12 | 13 | 3. Extend the django_sloop.models.AbstractSNSDevice class and create your own push token device model. 14 | 15 | ```python 16 | # models.py 17 | 18 | from django_sloop.models import AbstractSNSDevice 19 | 20 | 21 | class Device(AbstractSNSDevice): 22 | pass 23 | 24 | # (Optional) if you need to override Meta. 25 | class Meta(AbstractSNSDevice.Meta): 26 | pass 27 | ``` 28 | 29 | 4. Make sure that you fill necessary information at the settings file: 30 | 31 | ```python 32 | # settings.py 33 | 34 | DJANGO_SLOOP_SETTINGS = { 35 | "AWS_REGION_NAME": "", 36 | "AWS_ACCESS_KEY_ID": "", 37 | "AWS_SECRET_ACCESS_KEY": "", 38 | "SNS_IOS_APPLICATION_ARN": "test_ios_arn", 39 | "SNS_IOS_SANDBOX_ENABLED": False, 40 | "SNS_ANDROID_APPLICATION_ARN": "test_android_arn", 41 | "LOG_SENT_MESSAGES": False, # False by default. 42 | "DEFAULT_SOUND": "", 43 | "DEVICE_MODEL": "module_name.Device", 44 | } 45 | ``` 46 | 47 | You cannot change the DEVICE_MODEL setting during the lifetime of a project (i.e. once you have made and migrated models that depend on it) without serious effort. The model it refers to must be available in the first migration of 48 | the app that it lives in. 49 | 50 | 5. Create migrations for newly created Device model and migrate. 51 | 52 | **Note:** django_sloop's migrations must run after your Device is created. If you run into a problem while running migrations add following to the your migration file where the Device is created. 53 | ``` 54 | run_before = [ 55 | ('django_sloop', '0001_initial'), 56 | ] 57 | ``` 58 | 59 | 6. Add django_sloop.models.PushNotificationMixin to your User model. 60 | ```python 61 | class User(PushNotificationMixin, ...): 62 | pass 63 | 64 | user.send_push_notification_async(message="Sample push notification.") 65 | 66 | ``` 67 | 68 | 69 | 7. Add django_sloop.admin.SloopAdminMixin to your UserAdmin to enable sending push messages to users from Django admin panel. 70 | 71 | ```python 72 | # admin.py 73 | 74 | from django_sloop.admin import SloopAdminMixin 75 | from django.contrib import admin 76 | 77 | class UserAdmin(SloopAdminMixin, admin.ModelAdmin): 78 | 79 | actions = ("send_push_notification", ) 80 | 81 | ``` 82 | 83 | 8. Add django rest framework urls to create and delete device. 84 | 85 | ```python 86 | # urls.py 87 | from django.urls import path 88 | from django.urls import include 89 | 90 | urlpatterns = [ 91 | # ... 92 | path('api/devices/', include('django_sloop.urls')), 93 | # ... 94 | ] 95 | ``` 96 | 97 | Done! 98 | -------------------------------------------------------------------------------- /django_sloop/__init__.py: -------------------------------------------------------------------------------- 1 | import django 2 | 3 | if django.VERSION < (3, 2): 4 | default_app_config = 'django_sloop.apps.DjangoSloopConfig' 5 | -------------------------------------------------------------------------------- /django_sloop/admin.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from django.contrib import admin 3 | from django.contrib import messages 4 | from django.urls import reverse 5 | from django.utils.http import urlencode 6 | from django.views.generic import FormView 7 | from django.template.response import TemplateResponse 8 | from django import forms 9 | 10 | import json 11 | 12 | from django_sloop.models import PushMessage 13 | 14 | 15 | class PushNotificationForm(forms.Form): 16 | 17 | message = forms.CharField(max_length=255, label='Message:') 18 | extra = forms.CharField(max_length=255, widget=forms.Textarea, required=False, initial=json.dumps(dict()), label='Extra data as JSON:') 19 | url = forms.CharField(max_length=255, required=False, label='URL:') 20 | receivers = forms.CharField(widget=forms.HiddenInput) 21 | 22 | def clean(self): 23 | try: 24 | self.cleaned_data['extra'] = json.loads(self.cleaned_data['extra']) 25 | if self.cleaned_data['url']: 26 | self.cleaned_data['extra']["url"] = self.cleaned_data['url'] 27 | self.cleaned_data['receivers'] = json.loads(self.cleaned_data['receivers']) 28 | except (TypeError, ValueError) as ex: 29 | self.add_error('extra', ex.message) 30 | except KeyError: 31 | self.add_error(None, 'Could not retrieve push notification receivers, please try again.') 32 | 33 | return self.cleaned_data 34 | 35 | 36 | class PushNotificationView(FormView): 37 | 38 | template_name = 'django_sloop/push_notification.html' 39 | form_class = PushNotificationForm 40 | 41 | def form_valid(self, form): 42 | self.receivers = form.cleaned_data['receivers'] 43 | model_admin = self.kwargs.get('model_admin') 44 | receiver_ids = model_admin.get_receivers_queryset(self.receivers) 45 | for receiver_id in receiver_ids: 46 | user = model_admin.model.objects.get(pk=receiver_id) 47 | user.send_push_notification_async(form.cleaned_data['message'], extra=form.cleaned_data['extra']) 48 | 49 | return super(PushNotificationView, self).form_valid(form) 50 | 51 | def get_initial(self): 52 | initial = super(PushNotificationView, self).get_initial() 53 | if not initial.get("receivers") and self.request.GET.get("receivers"): 54 | initial["receivers"] = json.loads(self.request.GET.get("receivers")) 55 | return initial 56 | 57 | def get_success_url(self): 58 | messages.info(self.request, "Push notification has been sent.") 59 | model_admin = self.kwargs.get('model_admin') 60 | url = reverse('admin:%s_%s_send_push_notification' % (model_admin.model._meta.app_label, model_admin.model._meta.model_name)) 61 | url += "?" + urlencode({ 62 | 'receivers': json.dumps(self.receivers) 63 | }) 64 | return url 65 | 66 | def get_context_data(self, **kwargs): 67 | context = super(PushNotificationView, self).get_context_data(**kwargs) 68 | model_admin = self.kwargs.get('model_admin') 69 | admin_site = model_admin.admin_site 70 | opts = model_admin.model._meta 71 | 72 | context.update({ 73 | 'admin_site': admin_site.name, 74 | 'title': 'Send Push Notification', 75 | 'opts': opts, 76 | 'app_label': opts.app_label, 77 | 'view_url': reverse('admin:%s_%s_send_push_notification' % (opts.app_label, opts.model_name)) 78 | }) 79 | 80 | return context 81 | 82 | 83 | class SloopAdminMixin(object): 84 | """ 85 | Sloop admin mixin for sending push notifications 86 | """ 87 | def get_urls(self): 88 | urls = super(SloopAdminMixin, self).get_urls() 89 | return [ 90 | path('send-push-notification/', self.admin_site.admin_view(self.push_notification_view), 91 | name='%s_%s_send_push_notification' % (self.model._meta.app_label, self.model._meta.model_name)) 92 | ] + urls 93 | 94 | def get_receivers_queryset(self, receiver_ids): 95 | """ 96 | Filter your queryset as you want, then return it. 97 | """ 98 | return receiver_ids 99 | 100 | def push_notification_view(self, request): 101 | push_notification_view = PushNotificationView.as_view() 102 | return push_notification_view(request, model_admin=self) 103 | 104 | def send_push_notification(self, request, queryset): 105 | # Action method. 106 | 107 | admin_site = self.admin_site 108 | opts = self.model._meta 109 | receivers = list(queryset.values_list('id', flat=True)) 110 | form = PushNotificationForm(initial={'receivers': json.dumps(receivers)}) 111 | 112 | context = { 113 | 'form': form, 114 | 'admin_site': admin_site.name, 115 | 'title': 'Send Push Notification', 116 | 'opts': opts, 117 | 'app_label': opts.app_label, 118 | 'view_url': reverse('admin:%s_%s_send_push_notification' % (opts.app_label, opts.model_name)) 119 | } 120 | 121 | return TemplateResponse(request, 'django_sloop/push_notification.html', context=context) 122 | 123 | 124 | class PushMessageAdmin(admin.ModelAdmin): 125 | 126 | search_fields = ["body", "sns_message_id"] 127 | list_display = ["id", "body", "error_message", "device", "sns_message_id", "date_created", "date_updated"] 128 | readonly_fields = ["id", "device", "body", "data", "sns_message_id", "sns_response", "date_created", "date_updated"] 129 | 130 | def error_message(self, obj): 131 | error = json.loads(obj.sns_response).get("Error") 132 | if error: 133 | return error.get("Message") 134 | 135 | admin.site.register(PushMessage, PushMessageAdmin) 136 | -------------------------------------------------------------------------------- /django_sloop/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DjangoSloopConfig(AppConfig): 5 | name = "django_sloop" 6 | verbose_name = "Sloop" 7 | -------------------------------------------------------------------------------- /django_sloop/exceptions.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class DeviceIsNotActive(Exception): 4 | pass 5 | -------------------------------------------------------------------------------- /django_sloop/handlers.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import boto3 4 | from botocore.exceptions import ClientError 5 | from django.conf import settings 6 | 7 | from .settings import DJANGO_SLOOP_SETTINGS 8 | 9 | from .models import AbstractSNSDevice 10 | 11 | 12 | class SNSHandler(object): 13 | 14 | client = None 15 | 16 | def __init__(self, device): 17 | self.device = device 18 | self.client = self.get_client() 19 | 20 | def get_client(self): 21 | if self.client: 22 | return self.client 23 | 24 | client = boto3.client( 25 | 'sns', 26 | region_name=DJANGO_SLOOP_SETTINGS.get("AWS_REGION_NAME") or None, 27 | aws_access_key_id=DJANGO_SLOOP_SETTINGS.get("AWS_ACCESS_KEY_ID") or None, 28 | aws_secret_access_key=DJANGO_SLOOP_SETTINGS.get("AWS_SECRET_ACCESS_KEY") or None 29 | ) 30 | 31 | return client 32 | 33 | @property 34 | def application_arn(self): 35 | if self.device.platform == AbstractSNSDevice.PLATFORM_IOS: 36 | application_arn = DJANGO_SLOOP_SETTINGS.get("SNS_IOS_APPLICATION_ARN") 37 | elif self.device.platform == AbstractSNSDevice.PLATFORM_ANDROID: 38 | application_arn = DJANGO_SLOOP_SETTINGS.get("SNS_ANDROID_APPLICATION_ARN") 39 | else: 40 | assert False 41 | 42 | return application_arn 43 | 44 | def send_push_notification(self, message, url, badge_count, sound, extra, category, **kwargs): 45 | 46 | if self.device.platform == AbstractSNSDevice.PLATFORM_IOS: 47 | data = self.generate_apns_push_notification_message(message, url, badge_count, sound, extra, category, **kwargs) 48 | else: 49 | data = self.generate_gcm_push_notification_message(message, url, badge_count, sound, extra, category, **kwargs) 50 | 51 | return self._send_payload(data) 52 | 53 | def send_silent_push_notification(self, extra, badge_count, content_available, **kwargs): 54 | 55 | if self.device.platform == AbstractSNSDevice.PLATFORM_IOS: 56 | data = self.generate_apns_silent_push_notification_message(extra, badge_count, content_available, **kwargs) 57 | else: 58 | data = self.generate_gcm_silent_push_notification_message(extra, badge_count, content_available, **kwargs) 59 | 60 | return self._send_payload(data) 61 | 62 | def generate_gcm_push_notification_message(self, message, url, badge_count, sound, extra, category, **kwargs): 63 | if not extra: 64 | extra = {} 65 | 66 | if url: 67 | extra["url"] = url 68 | 69 | data = { 70 | 'alert': message, 71 | 'sound': sound, 72 | 'custom': extra, 73 | 'badge': badge_count, 74 | 'category': category 75 | } 76 | data.update(kwargs) 77 | 78 | data_bundle = { 79 | 'data': data 80 | } 81 | 82 | data_string = json.dumps(data_bundle, ensure_ascii=False) 83 | 84 | return { 85 | 'GCM': data_string 86 | } 87 | 88 | def generate_gcm_silent_push_notification_message(self, extra, badge_count, content_available, **kwargs): 89 | data = { 90 | 'content-available': content_available, 91 | 'sound': '', 92 | 'badge': badge_count, 93 | 'custom': extra 94 | } 95 | data.update(kwargs) 96 | 97 | data_bundle = { 98 | 'data': data 99 | } 100 | 101 | data_string = json.dumps(data_bundle, ensure_ascii=False) 102 | 103 | return { 104 | 'GCM': data_string 105 | } 106 | 107 | def generate_apns_push_notification_message(self, message, url, badge_count, sound, extra, category, **kwargs): 108 | if not extra: 109 | extra = {} 110 | 111 | if url: 112 | extra["url"] = url 113 | 114 | data = { 115 | 'alert': message, 116 | 'sound': sound, 117 | 'custom': extra, 118 | 'badge': badge_count, 119 | 'category': category 120 | } 121 | data.update(kwargs) 122 | 123 | apns_bundle = { 124 | 'aps': data 125 | } 126 | apns_string = json.dumps(apns_bundle, ensure_ascii=False) 127 | 128 | if DJANGO_SLOOP_SETTINGS.get("SNS_IOS_SANDBOX_ENABLED"): 129 | return { 130 | 'APNS_SANDBOX': apns_string 131 | } 132 | else: 133 | return { 134 | 'APNS': apns_string 135 | } 136 | 137 | def generate_apns_silent_push_notification_message(self, extra, badge_count, content_available, **kwargs): 138 | 139 | data = { 140 | 'content-available': content_available, 141 | 'sound': '', 142 | 'badge': badge_count, 143 | 'custom': extra 144 | } 145 | data.update(kwargs) 146 | 147 | apns_bundle = { 148 | 'aps': data 149 | } 150 | apns_string = json.dumps(apns_bundle, ensure_ascii=False) 151 | 152 | if DJANGO_SLOOP_SETTINGS.get("SNS_IOS_SANDBOX_ENABLED"): 153 | return { 154 | 'APNS_SANDBOX': apns_string 155 | } 156 | else: 157 | return { 158 | 'APNS': apns_string 159 | } 160 | 161 | def get_or_create_platform_endpoint_arn(self): 162 | if self.device.sns_platform_endpoint_arn: 163 | endpoint_arn = self.device.sns_platform_endpoint_arn 164 | else: 165 | endpoint_response = self.client.create_platform_endpoint( 166 | PlatformApplicationArn=self.application_arn, 167 | Token=self.device.push_token, 168 | ) 169 | endpoint_arn = endpoint_response['EndpointArn'] 170 | self.device.sns_platform_endpoint_arn = endpoint_arn 171 | self.device.save(update_fields=["sns_platform_endpoint_arn"]) 172 | 173 | return endpoint_arn 174 | 175 | def _send_payload(self, data): 176 | endpoint_arn = self.get_or_create_platform_endpoint_arn() 177 | message = json.dumps(data, ensure_ascii=False) 178 | 179 | if settings.DEBUG: 180 | print("ARN:" + endpoint_arn) 181 | print(message) 182 | 183 | try: 184 | publish_result = self.client.publish( 185 | TargetArn=endpoint_arn, 186 | Message=message, 187 | MessageStructure='json' 188 | ) 189 | except ClientError as exc: 190 | if exc.response['Error']["Code"] == "EndpointDisabled": 191 | # Push token is not valid anymore. 192 | # App deleted or push notifications are turned off by the user. 193 | self.device.invalidate() 194 | else: 195 | raise 196 | 197 | return message, exc.response 198 | 199 | if settings.DEBUG: 200 | print(publish_result) 201 | return message, publish_result 202 | -------------------------------------------------------------------------------- /django_sloop/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2019-08-09 18:03 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | import django.utils.timezone 6 | 7 | from django_sloop.settings import DJANGO_SLOOP_SETTINGS 8 | 9 | 10 | class Migration(migrations.Migration): 11 | 12 | initial = True 13 | 14 | dependencies = [ 15 | migrations.swappable_dependency(DJANGO_SLOOP_SETTINGS["DEVICE_MODEL"]), 16 | ] 17 | 18 | operations = [ 19 | migrations.CreateModel( 20 | name='PushMessage', 21 | fields=[ 22 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 23 | ('body', models.TextField()), 24 | ('data', models.TextField()), 25 | ('sns_message_id', models.CharField(blank=True, max_length=255, null=True, unique=True)), 26 | ('sns_response', models.TextField()), 27 | ('date_created', models.DateTimeField(default=django.utils.timezone.now)), 28 | ('date_updated', models.DateTimeField(auto_now=True)), 29 | ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='push_messages', to=DJANGO_SLOOP_SETTINGS["DEVICE_MODEL"])), 30 | ], 31 | options={ 32 | 'verbose_name': 'Push Notification', 33 | 'verbose_name_plural': 'Push Notifications', 34 | }, 35 | ), 36 | ] 37 | -------------------------------------------------------------------------------- /django_sloop/migrations/0002_change_meta.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2019-08-14 16:32 2 | 3 | from django.db import migrations 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | dependencies = [ 9 | ('django_sloop', '0001_initial'), 10 | ] 11 | 12 | operations = [ 13 | migrations.AlterModelOptions( 14 | name='pushmessage', 15 | options={'verbose_name': 'Push Message', 'verbose_name_plural': 'Push Messages'}, 16 | ), 17 | ] 18 | -------------------------------------------------------------------------------- /django_sloop/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/django_sloop/migrations/__init__.py -------------------------------------------------------------------------------- /django_sloop/models.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.conf import settings 4 | from django.contrib.gis.db import models 5 | from django.core.exceptions import ObjectDoesNotExist 6 | from django.utils import timezone 7 | from django.utils.encoding import smart_str 8 | from django.utils.translation import gettext_lazy as _ 9 | from django.template.defaultfilters import truncatechars 10 | 11 | from django_sloop.exceptions import DeviceIsNotActive 12 | from .settings import DJANGO_SLOOP_SETTINGS 13 | from . import tasks 14 | 15 | 16 | class PushNotificationMixin(object): 17 | """ 18 | A Mixin that handles push notification sending through the User model. 19 | """ 20 | 21 | def get_badge_count(self): 22 | return 0 23 | 24 | def get_active_pushable_device(self): 25 | """ 26 | Finds and returns the last active device with push token for this user, if available 27 | """ 28 | try: 29 | device = self.devices.filter(deleted_at__isnull=True).order_by("-date_created").first() 30 | except ObjectDoesNotExist: 31 | return None 32 | return device 33 | 34 | def send_push_notification_async(self, message, url=None, sound=None, extra=None, category=None, **kwargs): 35 | device = self.get_active_pushable_device() 36 | if not device: 37 | return False 38 | 39 | # Print message to console if this is a development environment. 40 | if settings.DEBUG: 41 | print("Push notification: %s / Receiver: %s" % (message, self)) 42 | 43 | sound = sound or DJANGO_SLOOP_SETTINGS.get("DEFAULT_SOUND") or None 44 | 45 | tasks.send_push_notification.delay( 46 | device.id, 47 | message, 48 | url, 49 | self.get_badge_count(), 50 | sound, 51 | extra, 52 | category, 53 | **kwargs 54 | ) 55 | 56 | def send_silent_push_notification_async(self, extra=None, content_available=True, **kwargs): 57 | """ 58 | Sends a push notification to the user's last active device 59 | """ 60 | # Print message to console if this is a development environment. 61 | if settings.DEBUG: 62 | print("Silent push notification to: %s" % self) 63 | 64 | device = self.get_active_pushable_device() 65 | if not device: 66 | return False 67 | 68 | tasks.send_silent_push_notification.delay( 69 | device.id, 70 | extra, 71 | self.get_badge_count(), 72 | content_available, 73 | **kwargs 74 | ) 75 | 76 | 77 | class AbstractSNSDevice(models.Model): 78 | 79 | PLATFORM_IOS = "ios" 80 | PLATFORM_ANDROID = "android" 81 | 82 | PLATFORM_CHOICES = ( 83 | (PLATFORM_IOS, "iOS"), 84 | (PLATFORM_ANDROID, "Android"), 85 | ) 86 | 87 | user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="devices", on_delete=models.CASCADE) 88 | locale = models.CharField(max_length=255, default="en_US") 89 | push_token = models.CharField(max_length=255, null=True) 90 | platform = models.CharField(max_length=255, choices=PLATFORM_CHOICES) 91 | model = models.CharField(max_length=255, blank=True) 92 | sns_platform_endpoint_arn = models.CharField(_("SNS Platform Endpoint"), max_length=255, null=True, blank=True, unique=True) 93 | 94 | deleted_at = models.DateTimeField(null=True, blank=True) 95 | 96 | date_created = models.DateTimeField(default=timezone.now) 97 | date_updated = models.DateTimeField(auto_now=True) 98 | 99 | class Meta: 100 | verbose_name = _("Device") 101 | verbose_name_plural = _("Devices") 102 | unique_together = ("push_token", "platform") 103 | ordering = ("-date_updated",) 104 | get_latest_by = "date_updated" 105 | abstract = True 106 | 107 | def __str__(self): 108 | return smart_str(_("Push Token %(push_token)s for %(user)s") % { 109 | "user": str(self.user), 110 | "push_token": self.push_token, 111 | }) 112 | 113 | def invalidate(self): 114 | self.deleted_at = timezone.now() 115 | self.save() 116 | 117 | def prepare_message(self, message): 118 | """ 119 | Prepares message before sending. 120 | """ 121 | return truncatechars(message, 255) 122 | 123 | def send_push_notification(self, message, url=None, badge_count=None, sound=None, extra=None, category=None, **kwargs): 124 | """ 125 | Sends push message using device push token 126 | """ 127 | from .handlers import SNSHandler 128 | 129 | if self.deleted_at: 130 | raise DeviceIsNotActive 131 | 132 | message = self.prepare_message(message) 133 | 134 | handler = SNSHandler(device=self) 135 | message_payload, response = handler.send_push_notification(message, url, badge_count, sound, extra, category, **kwargs) 136 | 137 | if DJANGO_SLOOP_SETTINGS["LOG_SENT_MESSAGES"]: 138 | PushMessage.objects.create( 139 | device=self, 140 | body=message, 141 | data=message_payload, 142 | sns_message_id=response.get("MessageId") or None, # Can be null for failed message. 143 | sns_response=json.dumps(response) 144 | ) 145 | 146 | return response 147 | 148 | def send_silent_push_notification(self, extra=None, badge_count=None, content_available=None, **kwargs): 149 | """ 150 | Sends silent push notification 151 | """ 152 | from .handlers import SNSHandler 153 | 154 | if self.deleted_at: 155 | raise DeviceIsNotActive 156 | 157 | handler = SNSHandler(device=self) 158 | message_payload, response = handler.send_silent_push_notification(extra, badge_count, content_available, **kwargs) 159 | 160 | if DJANGO_SLOOP_SETTINGS["LOG_SENT_MESSAGES"]: 161 | PushMessage.objects.create( 162 | device=self, 163 | data=message_payload, 164 | sns_message_id=response.get("MessageId") or None, # Can be null for failed message. 165 | sns_response=json.dumps(response) 166 | ) 167 | 168 | return response 169 | 170 | 171 | class PushMessage(models.Model): 172 | 173 | device = models.ForeignKey(DJANGO_SLOOP_SETTINGS["DEVICE_MODEL"], related_name="push_messages", on_delete=models.CASCADE) 174 | body = models.TextField() 175 | data = models.TextField() 176 | sns_message_id = models.CharField(max_length=255, unique=True, blank=True, null=True) 177 | sns_response = models.TextField() 178 | 179 | date_created = models.DateTimeField(default=timezone.now) 180 | date_updated = models.DateTimeField(auto_now=True) 181 | 182 | class Meta: 183 | verbose_name = "Push Message" 184 | verbose_name_plural = "Push Messages" 185 | -------------------------------------------------------------------------------- /django_sloop/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from rest_framework.fields import CurrentUserDefault 3 | 4 | from .utils import get_device_model 5 | 6 | 7 | class DeviceSerializer(serializers.Serializer): 8 | 9 | user = serializers.HiddenField(default=CurrentUserDefault()) 10 | push_token = serializers.CharField(required=True) 11 | platform = serializers.CharField(required=True) 12 | model = serializers.CharField(required=False, default="") 13 | locale = serializers.CharField(required=False, default="") 14 | 15 | def create(self, validated_data): 16 | device_model = get_device_model() 17 | user = validated_data["user"] 18 | device, created = device_model._default_manager.update_or_create( 19 | push_token=validated_data["push_token"], 20 | platform=validated_data["platform"], 21 | defaults={ 22 | "user": user, 23 | "locale": validated_data.get("locale"), 24 | "model": validated_data.get("model") 25 | } 26 | ) 27 | return device 28 | -------------------------------------------------------------------------------- /django_sloop/settings.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | DJANGO_SLOOP_SETTINGS = getattr(settings, "DJANGO_SLOOP_SETTINGS", {}) 4 | 5 | # Defaults 6 | DJANGO_SLOOP_SETTINGS.setdefault("AWS_REGION_NAME", None) 7 | DJANGO_SLOOP_SETTINGS.setdefault("AWS_ACCESS_KEY_ID", None) 8 | DJANGO_SLOOP_SETTINGS.setdefault("AWS_SECRET_ACCESS_KEY", None) 9 | DJANGO_SLOOP_SETTINGS.setdefault("SNS_IOS_APPLICATION_ARN", None) 10 | DJANGO_SLOOP_SETTINGS.setdefault("SNS_IOS_SANDBOX_ENABLED", False) 11 | DJANGO_SLOOP_SETTINGS.setdefault("SNS_ANDROID_APPLICATION_ARN", None) 12 | DJANGO_SLOOP_SETTINGS.setdefault("LOG_SENT_MESSAGES", False) 13 | DJANGO_SLOOP_SETTINGS.setdefault("DEFAULT_SOUND", None) 14 | DJANGO_SLOOP_SETTINGS.setdefault("DEVICE_MODEL", None) 15 | 16 | 17 | if not DJANGO_SLOOP_SETTINGS.get("DEVICE_MODEL"): 18 | assert False, "DJANGO_SLOOP_SETTINGS: DEVICE_MODEL is required." 19 | -------------------------------------------------------------------------------- /django_sloop/tasks.py: -------------------------------------------------------------------------------- 1 | from celery import shared_task 2 | 3 | from .utils import get_device_model 4 | 5 | 6 | @shared_task() 7 | def send_push_notification(device_id, message, url, badge_count, sound, extra, category, **kwargs): 8 | """ 9 | Sends a push notification message to the specified tokens 10 | """ 11 | device_model = get_device_model() 12 | device = device_model.objects.get(id=device_id) 13 | device.send_push_notification(message, url, badge_count, sound, extra, category, **kwargs) 14 | return "Message: %s" % message 15 | 16 | 17 | @shared_task() 18 | def send_silent_push_notification(device_id, extra, badge_count, content_available, **kwargs): 19 | """ 20 | Sends a push notification message to the specified tokens 21 | """ 22 | device_model = get_device_model() 23 | device = device_model.objects.get(id=device_id) 24 | device.send_silent_push_notification(extra, badge_count, content_available, **kwargs) 25 | return "Silent push" 26 | -------------------------------------------------------------------------------- /django_sloop/templates/django_sloop/push_notification.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/base.html" %} 2 | {% load i18n %} 3 | 4 | {% block breadcrumbs %} 5 | 6 | 12 | 13 | {% endblock %} 14 | 15 | {% block content %} 16 | 17 |
18 | {% csrf_token %} 19 | {{ form.non_field_errors }} 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 |
{{ form.message.label }}{{ form.message }}{{ form.message.errors }}
{{ form.url.label }}{{ form.url }}{{ form.url.errors }}
{{ form.extra.label }}{{ form.extra }}{{ form.extra.errors }}
37 | {{ form.receivers }} 38 | 39 |
40 | 41 | {% endblock %} -------------------------------------------------------------------------------- /django_sloop/tests.py: -------------------------------------------------------------------------------- 1 | import json 2 | import time 3 | from random import randint 4 | from unittest import skipIf 5 | 6 | from botocore.exceptions import ClientError 7 | from django.conf import settings 8 | from django.contrib.auth import get_user_model 9 | from django.test import TestCase 10 | from django.urls import reverse 11 | from mock import Mock 12 | 13 | from django_sloop.utils import get_device_model 14 | from .handlers import SNSHandler 15 | from .settings import DJANGO_SLOOP_SETTINGS 16 | 17 | User = get_user_model() 18 | 19 | TEST_SNS_ENDPOINT_ARN = "test_sns_endpoint_arn" 20 | TEST_IOS_PUSH_TOKEN = "test_ios_push_token" 21 | TEST_ANDROID_PUSH_TOKEN = "test_android_push_token" 22 | 23 | 24 | Device = get_device_model() 25 | 26 | 27 | class SNSHandlerTests(TestCase): 28 | 29 | def setUp(self): 30 | self.user = User.objects.create_user('username', "username@test.com", "test123") 31 | self.ios_device = Device.objects.create(user=self.user, push_token=TEST_IOS_PUSH_TOKEN, platform=Device.PLATFORM_IOS) 32 | self.android_device = Device.objects.create(user=self.user, push_token=TEST_ANDROID_PUSH_TOKEN, platform=Device.PLATFORM_ANDROID) 33 | 34 | def test_get_ios_application_arn(self): 35 | sns_client = Mock() 36 | SNSHandler.client = sns_client 37 | handler = SNSHandler(self.ios_device) 38 | self.assertEqual(handler.application_arn, DJANGO_SLOOP_SETTINGS["SNS_IOS_APPLICATION_ARN"]) 39 | 40 | def test_get_android_application_arn(self): 41 | sns_client = Mock() 42 | SNSHandler.client = sns_client 43 | handler = SNSHandler(self.android_device) 44 | self.assertEqual(handler.application_arn, DJANGO_SLOOP_SETTINGS["SNS_ANDROID_APPLICATION_ARN"]) 45 | 46 | def test_create_platform_endpoint(self): 47 | sns_client = Mock() 48 | sns_client.create_platform_endpoint.return_value = { 49 | 'EndpointArn': TEST_SNS_ENDPOINT_ARN 50 | } 51 | sns_client.publish.return_value = "" 52 | SNSHandler.client = sns_client 53 | handler = SNSHandler(self.ios_device) 54 | self.assertEqual(handler.get_or_create_platform_endpoint_arn(), TEST_SNS_ENDPOINT_ARN) 55 | 56 | sns_client.create_platform_endpoint.assert_called_once_with( 57 | PlatformApplicationArn=DJANGO_SLOOP_SETTINGS["SNS_IOS_APPLICATION_ARN"], 58 | Token=self.ios_device.push_token, 59 | ) 60 | 61 | self.assertEqual(self.ios_device.sns_platform_endpoint_arn, TEST_SNS_ENDPOINT_ARN) 62 | 63 | def test_get_platform_endpoint(self): 64 | sns_client = Mock() 65 | sns_client.create_platform_endpoint.return_value = { 66 | 'EndpointArn': TEST_SNS_ENDPOINT_ARN 67 | } 68 | SNSHandler.client = sns_client 69 | self.ios_device.sns_platform_endpoint_arn = "test_arn" 70 | self.ios_device.save() 71 | handler = SNSHandler(self.ios_device) 72 | self.assertEqual(handler.get_or_create_platform_endpoint_arn(), "test_arn") 73 | 74 | # create_platform_endpoint() is not called. 75 | self.assertFalse(sns_client.create_platform_endpoint.called) 76 | 77 | 78 | class DeviceTests(TestCase): 79 | 80 | def setUp(self): 81 | self.user = User.objects.create_user("username", "username@test.com", "test123") 82 | self.ios_device = Device.objects.create(user=self.user, push_token=TEST_IOS_PUSH_TOKEN, platform=Device.PLATFORM_IOS) 83 | self.android_device = Device.objects.create(user=self.user, push_token=TEST_ANDROID_PUSH_TOKEN, platform=Device.PLATFORM_ANDROID) 84 | 85 | def test_send_ios_push_notification(self): 86 | sns_client = Mock() 87 | sns_test_message_id = "test_message_" + str(randint(0, 9999)) 88 | sns_client.publish.return_value = { 89 | "MessageId": sns_test_message_id 90 | } 91 | SNSHandler.client = sns_client 92 | 93 | self.ios_device.sns_platform_endpoint_arn = "test_ios_arn" 94 | self.ios_device.save() 95 | 96 | self.ios_device.send_push_notification(message="test_message", url="test_url", badge_count=3, sound="test_sound", extra={"foo": "bar"}, category="test_category", foo="bar") 97 | 98 | sns_client.publish.assert_called_once() 99 | call_args, call_kwargs = sns_client.publish.call_args_list[0] 100 | self.assertEqual(call_kwargs["TargetArn"], self.ios_device.sns_platform_endpoint_arn) 101 | self.assertEqual(call_kwargs["MessageStructure"], "json") 102 | expected_message = { 103 | 'APNS': { 104 | 'aps': { 105 | 'alert': "test_message", 106 | 'sound': 'test_sound', 107 | 'badge': 3, 108 | 'category': "test_category", 109 | 'custom': {"foo": "bar", "url": "test_url"}, 110 | 'foo': 'bar' 111 | } 112 | } 113 | } 114 | 115 | actual_message = json.loads(call_kwargs["Message"]) 116 | actual_message["APNS"] = json.loads(actual_message["APNS"]) 117 | 118 | self.assertDictEqual(expected_message, actual_message) 119 | 120 | push_message = self.ios_device.push_messages.get() 121 | self.assertEqual(push_message.sns_message_id, sns_test_message_id) 122 | self.assertEqual(push_message.sns_response, json.dumps({ 123 | "MessageId": sns_test_message_id 124 | })) 125 | 126 | def test_send_android_push_notification(self): 127 | sns_client = Mock() 128 | sns_test_message_id = "test_message_" + str(randint(0, 9999)) 129 | sns_client.publish.return_value = { 130 | "MessageId": sns_test_message_id 131 | } 132 | SNSHandler.client = sns_client 133 | 134 | self.android_device.sns_platform_endpoint_arn = "test_android_arn" 135 | self.android_device.save() 136 | 137 | self.android_device.send_push_notification(message="test_message", url="test_url", badge_count=3, sound="test_sound", extra={"foo": "bar"}, category="test_category", foo="bar") 138 | 139 | sns_client.publish.assert_called_once() 140 | call_args, call_kwargs = sns_client.publish.call_args_list[0] 141 | self.assertEqual(call_kwargs["TargetArn"], self.android_device.sns_platform_endpoint_arn) 142 | self.assertEqual(call_kwargs["MessageStructure"], "json") 143 | expected_message = { 144 | 'GCM': { 145 | 'data': { 146 | 'alert': "test_message", 147 | 'sound': 'test_sound', 148 | 'badge': 3, 149 | 'category': "test_category", 150 | 'custom': {"foo": "bar", "url": "test_url"}, 151 | 'foo': 'bar' 152 | } 153 | } 154 | } 155 | 156 | actual_message = json.loads(call_kwargs["Message"]) 157 | actual_message["GCM"] = json.loads(actual_message["GCM"]) 158 | 159 | self.assertDictEqual(expected_message, actual_message) 160 | 161 | push_message = self.android_device.push_messages.get() 162 | self.assertEqual(push_message.sns_message_id, sns_test_message_id) 163 | self.assertEqual(push_message.sns_response, json.dumps({ 164 | "MessageId": sns_test_message_id 165 | })) 166 | 167 | def test_send_ios_silent_push_notification(self): 168 | sns_client = Mock() 169 | sns_test_message_id = "test_message_" + str(randint(0, 9999)) 170 | sns_client.publish.return_value = { 171 | "MessageId": sns_test_message_id 172 | } 173 | SNSHandler.client = sns_client 174 | 175 | self.ios_device.sns_platform_endpoint_arn = "test_ios_arn" 176 | self.ios_device.save() 177 | 178 | self.ios_device.send_silent_push_notification(badge_count=0, extra={"foo": "bar"}, content_available=True, foo="bar") 179 | 180 | sns_client.publish.assert_called_once() 181 | call_args, call_kwargs = sns_client.publish.call_args_list[0] 182 | self.assertEqual(call_kwargs["TargetArn"], self.ios_device.sns_platform_endpoint_arn) 183 | self.assertEqual(call_kwargs["MessageStructure"], "json") 184 | expected_message = { 185 | 'APNS': { 186 | 'aps': { 187 | 'content-available': True, 188 | 'sound': '', 189 | 'badge': 0, 190 | 'custom': {"foo": "bar"}, 191 | 'foo': 'bar' 192 | } 193 | } 194 | } 195 | 196 | actual_message = json.loads(call_kwargs["Message"]) 197 | actual_message["APNS"] = json.loads(actual_message["APNS"]) 198 | 199 | self.assertDictEqual(expected_message, actual_message) 200 | 201 | push_message = self.ios_device.push_messages.get() 202 | self.assertEqual(push_message.sns_message_id, sns_test_message_id) 203 | self.assertEqual(push_message.sns_response, json.dumps({ 204 | "MessageId": sns_test_message_id 205 | })) 206 | 207 | def test_send_android_silent_push_notification(self): 208 | sns_client = Mock() 209 | sns_test_message_id = "test_message_" + str(randint(0, 9999)) 210 | sns_client.publish.return_value = { 211 | "MessageId": sns_test_message_id 212 | } 213 | SNSHandler.client = sns_client 214 | 215 | self.android_device.sns_platform_endpoint_arn = "test_android_arn" 216 | self.android_device.save() 217 | 218 | self.android_device.send_silent_push_notification(badge_count=0, extra={"foo": "bar"}, content_available=True, foo="bar") 219 | 220 | sns_client.publish.assert_called_once() 221 | call_args, call_kwargs = sns_client.publish.call_args_list[0] 222 | self.assertEqual(call_kwargs["TargetArn"], self.android_device.sns_platform_endpoint_arn) 223 | self.assertEqual(call_kwargs["MessageStructure"], "json") 224 | expected_message = { 225 | 'GCM': { 226 | 'data': { 227 | 'content-available': True, 228 | 'sound': '', 229 | 'badge': 0, 230 | 'custom': {"foo": "bar"}, 231 | 'foo': 'bar' 232 | } 233 | } 234 | } 235 | 236 | actual_message = json.loads(call_kwargs["Message"]) 237 | actual_message["GCM"] = json.loads(actual_message["GCM"]) 238 | 239 | self.assertDictEqual(expected_message, actual_message) 240 | 241 | push_message = self.android_device.push_messages.get() 242 | self.assertEqual(push_message.sns_message_id, sns_test_message_id) 243 | self.assertEqual(push_message.sns_response, json.dumps({ 244 | "MessageId": sns_test_message_id 245 | })) 246 | 247 | def test_invalidate_device_if_push_message_fails(self): 248 | sns_client = Mock() 249 | SNSHandler.client = sns_client 250 | sns_client.publish.side_effect = ClientError(error_response={ 251 | "Error": { 252 | "Code": "EndpointDisabled" 253 | } 254 | }, operation_name="test") 255 | 256 | self.ios_device.sns_platform_endpoint_arn = "test_ios_arn" 257 | self.ios_device.save() 258 | 259 | self.ios_device.send_push_notification(message="test") 260 | 261 | # Device must be deleted. 262 | self.ios_device.refresh_from_db() 263 | self.assertIsNotNone(self.ios_device.deleted_at) 264 | 265 | push_message = self.ios_device.push_messages.get() 266 | self.assertIsNone(push_message.sns_message_id) 267 | self.assertEqual(push_message.sns_response, json.dumps({ 268 | "Error": { 269 | "Code": "EndpointDisabled" 270 | } 271 | })) 272 | 273 | 274 | @skipIf('rest_framework.authtoken' not in settings.INSTALLED_APPS, "rest_framework.authtoken is not in installed apps.") 275 | class DeviceAPITests(TestCase): 276 | 277 | def setUp(self): 278 | from rest_framework.authtoken.models import Token 279 | from rest_framework.test import APIClient 280 | from rest_framework import status 281 | self.Token = Token 282 | self.APIClient = APIClient 283 | self.status = status 284 | 285 | self.client, self.user = self.create_test_user_client() 286 | self.ios_device = Device.objects.create(user=self.user, push_token=TEST_IOS_PUSH_TOKEN, platform=Device.PLATFORM_IOS) 287 | self.android_device = Device.objects.create(user=self.user, push_token=TEST_ANDROID_PUSH_TOKEN, platform=Device.PLATFORM_ANDROID) 288 | self.create_delete_url = reverse("django_sloop:create-delete-device") 289 | 290 | def create_test_user_client(self, **user_data): 291 | millis = int(round(time.time() * 1000)) 292 | user = User.objects.create_user("username" + str(millis), "username@test.com", "test123") 293 | token, _ = self.Token.objects.get_or_create(user=user) 294 | client = self.APIClient() 295 | client.default_format = 'json' 296 | client.force_authenticate(user=user, token=token.key) 297 | 298 | return client, user 299 | 300 | def test_api_create_device(self): 301 | from .serializers import DeviceSerializer 302 | 303 | data = { 304 | "push_token": "test_ios_push_token2", 305 | "platform": Device.PLATFORM_IOS 306 | } 307 | response = self.client.post(self.create_delete_url, data=data) 308 | self.assertEqual(response.status_code, self.status.HTTP_201_CREATED) 309 | device = self.user.devices.get(**data) 310 | self.assertEqual(response.data, DeviceSerializer(device).data) 311 | 312 | def test_api_delete_device(self): 313 | non_device_owner_client, non_device_owner = self.create_test_user_client() 314 | 315 | data = { 316 | "push_token": self.ios_device.push_token 317 | } 318 | response = non_device_owner_client.delete(self.create_delete_url, data=data) 319 | self.assertEqual(response.status_code, self.status.HTTP_404_NOT_FOUND) 320 | 321 | response = self.client.delete(self.create_delete_url, data=data) 322 | 323 | self.assertEqual(response.status_code, self.status.HTTP_204_NO_CONTENT) 324 | self.ios_device.refresh_from_db() 325 | self.assertIsNotNone(self.ios_device.deleted_at) 326 | -------------------------------------------------------------------------------- /django_sloop/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import CreateDeleteDeviceView 3 | 4 | app_name = 'django_sloop' 5 | 6 | urlpatterns = ( 7 | path('', CreateDeleteDeviceView.as_view(), name="create-delete-device"), 8 | ) 9 | -------------------------------------------------------------------------------- /django_sloop/utils.py: -------------------------------------------------------------------------------- 1 | from django.apps import apps 2 | 3 | from .settings import DJANGO_SLOOP_SETTINGS 4 | 5 | 6 | def get_device_model(): 7 | return apps.get_model(*DJANGO_SLOOP_SETTINGS["DEVICE_MODEL"].split(".")) 8 | -------------------------------------------------------------------------------- /django_sloop/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.generics import CreateAPIView, get_object_or_404 2 | from rest_framework.mixins import DestroyModelMixin 3 | from rest_framework.permissions import IsAuthenticated 4 | 5 | from .utils import get_device_model 6 | from .serializers import DeviceSerializer 7 | 8 | 9 | class CreateDeleteDeviceView(CreateAPIView, DestroyModelMixin): 10 | """ 11 | An endpoint for creating & deleting devices. 12 | """ 13 | serializer_class = DeviceSerializer 14 | permission_classes = (IsAuthenticated,) 15 | 16 | def perform_destroy(self, instance): 17 | instance.invalidate() 18 | 19 | def delete(self, request, *args, **kwargs): 20 | return self.destroy(request, *args, **kwargs) 21 | 22 | def get_object(self): 23 | """ 24 | Override get_object for delete endpoint 25 | """ 26 | device_model = get_device_model() 27 | return get_object_or_404(device_model._default_manager, push_token=self.request.data.get('push_token'), user=self.request.user) 28 | -------------------------------------------------------------------------------- /docs/img/splash.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/docs/img/splash.jpg -------------------------------------------------------------------------------- /docs/img/splash.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/docs/img/splash.psd -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | if __name__ == "__main__": 4 | import os 5 | import sys 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_app.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | DJANGO_SETTINGS_MODULE = test_app.settings.local 3 | # -- recommended but optional: 4 | python_files = tests.py test_*.py *_tests.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django >= 1.11 2 | boto3==1.9.178 3 | celery >= 4 -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | djangorestframework>=3 3 | mock 4 | psycopg2-binary 5 | ipython 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | 4 | with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: 5 | README = readme.read() 6 | 7 | # allow setup.py to be run from any path 8 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 9 | 10 | setup( 11 | name='django-sloop', 12 | version='1.0.7', 13 | packages=['django_sloop'], 14 | include_package_data=True, 15 | license='Apache-2.0', 16 | description='Django application to send push notifications to IOS and Android devices using Amazon SNS.', 17 | long_description=README, 18 | long_description_content_type="text/markdown", 19 | author='hipo', 20 | author_email='pypi@hipolabs.com', 21 | url='https://github.com/Hipo/django-sloop', 22 | python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*", 23 | classifiers=[ 24 | 'Environment :: Web Environment', 25 | 'Framework :: Django :: 1.11', 26 | 'Framework :: Django :: 2.0', 27 | 'Framework :: Django :: 2.1', 28 | 'Framework :: Django :: 2.2', 29 | 'Framework :: Django :: 3.2', 30 | 'Framework :: Django :: 4.0', 31 | 'Framework :: Django :: 4.1', 32 | 'Intended Audience :: Developers', 33 | 'Operating System :: OS Independent', 34 | 'License :: OSI Approved :: BSD License', 35 | 'Programming Language :: Python', 36 | 'Programming Language :: Python :: 2', 37 | 'Programming Language :: Python :: 2.7', 38 | 'Programming Language :: Python :: 3', 39 | 'Programming Language :: Python :: 3.5', 40 | 'Programming Language :: Python :: 3.6', 41 | 'Programming Language :: Python :: 3.7', 42 | 'Topic :: Internet :: WWW/HTTP', 43 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 44 | ], 45 | ) 46 | -------------------------------------------------------------------------------- /test_app/__init__.py: -------------------------------------------------------------------------------- 1 | from .celery import app as celery_app 2 | 3 | __all__ = ['celery_app'] 4 | -------------------------------------------------------------------------------- /test_app/celery.py: -------------------------------------------------------------------------------- 1 | from celery import Celery 2 | 3 | app = Celery('test_app') 4 | 5 | app.config_from_object('django.conf:settings', namespace='CELERY') 6 | 7 | # Load task modules from all registered Django app configs. 8 | app.autodiscover_tasks() 9 | -------------------------------------------------------------------------------- /test_app/devices/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/test_app/devices/__init__.py -------------------------------------------------------------------------------- /test_app/devices/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from test_app.devices.models import Device 3 | 4 | admin.site.register(Device) 5 | -------------------------------------------------------------------------------- /test_app/devices/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.4 on 2019-08-09 18:03 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | import django.utils.timezone 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='Device', 20 | fields=[ 21 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 22 | ('locale', models.CharField(default='en_US', max_length=255)), 23 | ('push_token', models.CharField(max_length=255, null=True)), 24 | ('platform', models.CharField(choices=[('ios', 'iOS'), ('android', 'Android')], max_length=255)), 25 | ('model', models.CharField(blank=True, max_length=255)), 26 | ('sns_platform_endpoint_arn', models.CharField(blank=True, max_length=255, null=True, unique=True, verbose_name='SNS Platform Endpoint')), 27 | ('deleted_at', models.DateTimeField(blank=True, null=True)), 28 | ('date_created', models.DateTimeField(default=django.utils.timezone.now)), 29 | ('date_updated', models.DateTimeField(auto_now=True)), 30 | ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='devices', to=settings.AUTH_USER_MODEL)), 31 | ], 32 | options={ 33 | 'verbose_name': 'Device', 34 | 'verbose_name_plural': 'Devices', 35 | 'ordering': ('-date_updated',), 36 | 'get_latest_by': 'date_updated', 37 | 'abstract': False, 38 | 'unique_together': {('push_token', 'platform')}, 39 | }, 40 | ), 41 | ] 42 | -------------------------------------------------------------------------------- /test_app/devices/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/test_app/devices/migrations/__init__.py -------------------------------------------------------------------------------- /test_app/devices/models.py: -------------------------------------------------------------------------------- 1 | from django_sloop.models import AbstractSNSDevice 2 | 3 | 4 | class Device(AbstractSNSDevice): 5 | pass 6 | -------------------------------------------------------------------------------- /test_app/settings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/test_app/settings/__init__.py -------------------------------------------------------------------------------- /test_app/settings/base.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for test_app project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.11.21. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.11/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'cqbjez8m6zp*skl83cfvadsq3uf)hhjc)s-(h$5+lq3m%r=yvz' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | ] 41 | 42 | MIDDLEWARE = [ 43 | 'django.middleware.security.SecurityMiddleware', 44 | 'django.contrib.sessions.middleware.SessionMiddleware', 45 | 'django.middleware.common.CommonMiddleware', 46 | 'django.middleware.csrf.CsrfViewMiddleware', 47 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 48 | 'django.contrib.messages.middleware.MessageMiddleware', 49 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 50 | ] 51 | 52 | ROOT_URLCONF = 'test_app.urls' 53 | 54 | TEMPLATES = [ 55 | { 56 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 57 | 'DIRS': [], 58 | 'APP_DIRS': True, 59 | 'OPTIONS': { 60 | 'context_processors': [ 61 | 'django.template.context_processors.debug', 62 | 'django.template.context_processors.request', 63 | 'django.contrib.auth.context_processors.auth', 64 | 'django.contrib.messages.context_processors.messages', 65 | ], 66 | }, 67 | }, 68 | ] 69 | 70 | WSGI_APPLICATION = 'test_app.wsgi.application' 71 | 72 | 73 | # Database 74 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 75 | 76 | DATABASES = { 77 | 'default': { 78 | 'ENGINE': 'django.db.backends.sqlite3', 79 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 80 | } 81 | } 82 | 83 | 84 | # Password validation 85 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 86 | 87 | AUTH_PASSWORD_VALIDATORS = [ 88 | { 89 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 90 | }, 91 | { 92 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 93 | }, 94 | { 95 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 99 | }, 100 | ] 101 | 102 | 103 | # Internationalization 104 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 105 | 106 | LANGUAGE_CODE = 'en-us' 107 | 108 | TIME_ZONE = 'UTC' 109 | 110 | USE_I18N = True 111 | 112 | USE_L10N = True 113 | 114 | USE_TZ = True 115 | 116 | 117 | # Static files (CSS, JavaScript, Images) 118 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 119 | 120 | STATIC_URL = '/static/' 121 | -------------------------------------------------------------------------------- /test_app/settings/local.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | 3 | INSTALLED_APPS += [ 4 | 'rest_framework', 5 | "rest_framework.authtoken", 6 | 'django_sloop', 7 | 'test_app.devices', 8 | 'test_app.users', 9 | ] 10 | 11 | DJANGO_SLOOP_SETTINGS = { 12 | "AWS_REGION_NAME": "", 13 | "AWS_ACCESS_KEY_ID": "", 14 | "AWS_SECRET_ACCESS_KEY": "", 15 | "SNS_IOS_APPLICATION_ARN": "test_ios_arn", 16 | "SNS_IOS_SANDBOX_ENABLED": False, 17 | "SNS_ANDROID_APPLICATION_ARN": "test_android_arn", 18 | "DEFAULT_SOUND": "", 19 | "DEVICE_MODEL": "devices.Device", 20 | "LOG_SENT_MESSAGES": True, 21 | } 22 | 23 | CELERY_TASK_ALWAYS_EAGER = True 24 | CELERY_TASK_EAGER_PROPAGATES = True 25 | -------------------------------------------------------------------------------- /test_app/urls.py: -------------------------------------------------------------------------------- 1 | """test_app URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import url, include 14 | 2. Add a URL to urlpatterns: path('', include('blog.urls')) 15 | """ 16 | from django.urls import path 17 | from django.contrib import admin 18 | 19 | try: 20 | from django.urls import include 21 | except ImportError: 22 | from django.conf.urls import include 23 | 24 | 25 | urlpatterns = [ 26 | path('admin/', admin.site.urls), 27 | path('api/devices/', include('django_sloop.urls')), 28 | ] 29 | -------------------------------------------------------------------------------- /test_app/users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hipo/django-sloop/9e34f8a6d72f5da964f1ef6de8a0862f217371fa/test_app/users/__init__.py -------------------------------------------------------------------------------- /test_app/users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.auth.admin import UserAdmin 3 | from django.contrib.auth.models import User 4 | 5 | from django_sloop.admin import SloopAdminMixin 6 | 7 | 8 | class CustomUserAdmin(SloopAdminMixin, UserAdmin): 9 | actions = ("send_push_notification", ) 10 | 11 | 12 | admin.site.unregister(User) 13 | admin.site.register(User, CustomUserAdmin) 14 | -------------------------------------------------------------------------------- /test_app/users/models.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import User 2 | 3 | from django_sloop.models import PushNotificationMixin 4 | 5 | User.add_to_class("send_push_notification_async", PushNotificationMixin.send_push_notification_async) 6 | User.add_to_class("get_active_pushable_device", PushNotificationMixin.get_active_pushable_device) 7 | User.add_to_class("send_silent_push_notification_async", PushNotificationMixin.send_silent_push_notification_async) 8 | User.add_to_class("get_badge_count", lambda x: 0) 9 | -------------------------------------------------------------------------------- /test_app/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for test_app project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_app.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | 3 | # https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django 4 | envlist = 5 | py27-drf3-django111, 6 | py{35,36,37}-drf3-django{111,20,21,22}, 7 | lint 8 | 9 | [testenv] 10 | deps = 11 | django111: Django>=1.11,<2.0 12 | django20: Django>=2.0,<2.1 13 | django21: Django>=2.1,<2.2 14 | django22: Django>=2.2,<2.3 15 | drf3: djangorestframework>=3 16 | pytest-django 17 | pytest-cov 18 | boto3==1.9.178 19 | celery >= 4 20 | mock 21 | psycopg2-binary 22 | commands = 23 | pytest {posargs} --cov-report=xml --cov 24 | passenv = 25 | CI 26 | TRAVIS 27 | TRAVIS_* 28 | 29 | [testenv:lint] 30 | skip_install = true 31 | deps = 32 | flake8 33 | commands = 34 | flake8 django_sloop test_app setup.py --------------------------------------------------------------------------------