Giter Club home page Giter Club logo

fcm-django's Introduction

fcm-django

image

Django app for Firebase Cloud Messaging. Used as an unified platform for sending push notifications to mobile devices & browsers (android / ios / chrome / firefox / ...).

Supports Firebase Cloud Messaging HTTP v1 API. If you're looking for the legacy API, use fcm-django<1!

FCMDevice model fields
  • registration_id (required - is FCM token)
  • name (optional)
  • active (default: true)
  • user (optional)
  • device_id (optional - can be used to uniquely identify devices)
  • type ('android', 'web', 'ios')
Functionality:
  • all necessary migrations
  • model admins for django admin
  • admin actions for testing single and bulk notification sending
  • automatic device pruning: devices to which notifications fail to send are marked as inactive
  • devices marked as inactive will not be sent notifications
  • Django rest framework viewsets

Demo javascript client project

Unsure how to use this project? Check out the demo at: https://github.com/xtrinch/fcm-django-web-demo

Migration to v1.0

We've replaced Python package pyfcm for Firebase's own package firebase-admin. Thus, we no longer use an API key. Instead, you'll need an environment variable GOOGLE_APPLICATION_CREDENTIALS which is a path pointing to your JSON-file stored credentials. To learn more or view other options to input credentials, visit the Google Cloud docs.

Finally, in your settings.py (or whatever imported file), add:

from firebase_admin import initialize_app
FIREBASE_APP = initialize_app()
# Or just
initialize_app()

The API for sending messages is now under the firebase-admin package; hence, we removed the methods send_data_message from the QuerySet and class instance methods. Instead, everything is under a single method: send_message

from firebase_admin.messaging import Message, Notification
FCMDevice.objects.send_message(Message(data=dict()))
# Note: You can also combine the data and notification kwarg
FCMDevice.objects.send_message(
    Message(notification=Notification(title="title", body="body", image="image_url"))
)
device = FCMDevice.objects.first()
device.send_message(Message(...))

Additionally, we've added Firebase's new Topic API, allowing for easier sending of bulk messages.

from firebase_admin.messaging import Message, Notification
topic = "A topic"
FCMDevice.objects.handle_subscription(True, topic)
FCMDevice.send_topic_message(Message(data={...}), "TOPIC NAME")

There are two additional parameters to both methods: skip_registration_id_lookup and additional_registration_ids. Visit Sending Messages to learn more.

Note: registration_ids is actually incorrect terminology as it should actually be called registration tokens. However, to be consistent with django-push-notifications, we've refrained from switching to stay backwards compatible in the docs and with the sister package.

Setup

You can install the library directly from pypi using pip:

pip install fcm-django

Edit your settings.py file:

from firebase_admin import initialize_app

INSTALLED_APPS = (
    ...
    "fcm_django"
    ...
)

# Optional ONLY IF you have initialized a firebase app already:
# Visit https://firebase.google.com/docs/admin/setup/#python
# for more options for the following:
# Store an environment variable called GOOGLE_APPLICATION_CREDENTIALS
# which is a path that point to a json file with your credentials.
# Additional arguments are available: credentials, options, name
FIREBASE_APP = initialize_app()
# To learn more, visit the docs here:
# https://cloud.google.com/docs/authentication/getting-started>

FCM_DJANGO_SETTINGS = {
     # an instance of firebase_admin.App to be used as default for all fcm-django requests
     # default: None (the default Firebase app)
    "DEFAULT_FIREBASE_APP": None,
     # default: _('FCM Django')
    "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]",
     # true if you want to have only one active device per registered user at a time
     # default: False
    "ONE_DEVICE_PER_USER": True/False,
     # devices to which notifications cannot be sent,
     # are deleted upon receiving error response from FCM
     # default: False
    "DELETE_INACTIVE_DEVICES": True/False,
}

Native Django migrations are in use. manage.py migrate will install and migrate all models.

Messages

You can read more about different types of messages here.

In short, there are two types: notifications and data messages.

Notification:

from firebase_admin.messaging import Message, Notification
Message(
    notification=Notification(title="title", body="text", image="url"),
    topic="Optional topic parameter: Whatever you want",
)

Data message:

from firebase_admin.messaging import Message
Message(
    data={
        "Nick" : "Mario",
        "body" : "great match!",
        "Room" : "PortugalVSDenmark"
   },
   topic="Optional topic parameter: Whatever you want",
)

As in the following example, you can send either a notification, a data message, or both. You can also customize the Android, iOS, and Web configuration along with additional FCM conditions. Visit firebase_admin.messaging.Message to learn more about those configurations.

Sending messages

Additional parameters are additional_registration_ids and skip_registration_id_lookup. View the "Additional Parameters" section for more information.

from firebase_admin.messaging import Message
from fcm_django.models import FCMDevice

# You can still use .filter() or any methods that return QuerySet (from the chain)
device = FCMDevice.objects.all().first()
# send_message parameters include: message, dry_run, app
device.send_message(Message(data={...}))

Sending messages in bulk

from firebase_admin.messaging import Message
from fcm_django.models import FCMDevice

# You can still use .filter() or any methods that return QuerySet (from the chain)
devices = FCMDevice.objects.all()
devices.send_message(Message(data={...}))
# Or (send_message parameters include: messages, dry_run, app)
FCMDevice.objects.send_message(Message(...))

Sending messages raises all the errors that firebase-admin raises, so make sure they are caught and dealt with in your application code:

  • FirebaseError – If an error occurs while sending the message to the FCM service.
  • ValueError – If the input arguments are invalid.

For more info, see https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging#firebase_admin.messaging.BatchResponse

Subscribing or Unsubscribing Users to topic

from fcm_django.models import FCMDevice

# Subscribing
FCMDevice.objects.all().handle_topic_subscription(True, topic="TOPIC NAME"))
device = FCMDevice.objects.all().first()
device.handle_topic_subscription(True, topic="TOPIC NAME"))

# Finally you can send a message to that topic
from firebase_admin.messaging import Message
message = Message(..., topic="A topic")
# You can still use .filter() or any methods that return QuerySet (from the chain)
FCMDevice.objects.send_message(message)

# Unsubscribing
FCMDevice.objects.all().handle_topic_subscription(False, topic="TOPIC NAME"))
device = FCMDevice.objects.all().first()
device.handle_topic_subscription(False, topic="TOPIC NAME"))

Sending messages to topic

from fcm_django.models import FCMDevice

FCMDevice.send_topic_message(Message(data={...}), "TOPIC NAME")

Additional Parameters

You can add additional_registration_ids (Sequence) for manually sending registration IDs. It will append these IDs to the queryset lookup's returned registration IDs.

You can also add skip_registration_id_lookup (bool) to skip database lookup that goes along with your query.

from firebase_admin.messaging import Message
from fcm_django.models import FCMDevice
FCMDevice.objects.send_message(Message(...), False, ["registration_ids"])

Using multiple FCM apps

By default the message will be sent using the default FCM firebase_admin.App (we initialized this in our settings), or the one specified with the DEFAULT_FIREBASE_APP setting.

This default can be overridden by specifying an app when calling send_message. This can be used to send messages using different firebase projects.

from firebase_app import App
from firebase_app.messaging import Notification
from fcm_django.models import FCMDevice

device = FCMDevice.objects.all().first()
device.send_message(notification=Notification(...), app=App(...))

Setting a default Firebase app for FCM

If you want to use a specific Firebase app for all fcm-django requests, you can create an instance of firebase_admin.App and pass it to fcm-django with the DEFAULT_FIREBASE_APP setting.

The DEFAULT_FIREBASE_APP will be used for all send / subscribe / unsubscribe requests, include FCMDevice's admin actions.

In your settings.py:

from firebase_admin import initialize_app, credentials
from google.auth import load_credentials_from_file
from google.oauth2.service_account import Credentials

# create a custom Credentials class to load a non-default google service account JSON
class CustomFirebaseCredentials(credentials.ApplicationDefault):
    def __init__(self, account_file_path: str):
        super().__init__()
        self._account_file_path = account_file_path

    def _load_credential(self):
        if not self._g_credential:
            self._g_credential, self._project_id = load_credentials_from_file(self._account_file_path,
                                                                              scopes=credentials._scopes)

# init default firebase app
# this loads the default google service account with GOOGLE_APPLICATION_CREDENTIALS env variable
FIREBASE_APP = initialize_app()

# init second firebase app for fcm-django
# the environment variable contains a path to the custom google service account JSON
custom_credentials = CustomFirebaseCredentials(os.getenv('CUSTOM_GOOGLE_APPLICATION_CREDENTIALS'))
FIREBASE_MESSAGING_APP = initialize_app(custom_credentials, name='messaging')

FCM_DJANGO_SETTINGS = {
    "DEFAULT_FIREBASE_APP": FIREBASE_MESSAGING_APP,
    # [...] your other settings
}

Django REST Framework (DRF) support

Viewsets come in two different varieties:

  • FCMDeviceViewSet

    • Permissions as specified in settings (AllowAny by default, which is not recommended)
    • A device may be registered without associating it with a user
    • Will not allow duplicate registration_id's
  • FCMDeviceAuthorizedViewSet

    • 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
    • Will update the device on duplicate registration id

Routes can be added one of two ways:

from fcm_django.api.rest_framework import FCMDeviceAuthorizedViewSet

from rest_framework.routers import DefaultRouter

router = DefaultRouter()

router.register('devices', FCMDeviceAuthorizedViewSet)

urlpatterns = [
    # URLs will show up at <api_root>/devices
    # DRF browsable API which lists all available endpoints
    path('', include(router.urls)),
    # ...
]
  • Using as_view (specify which views to include)
from fcm_django.api.rest_framework import FCMDeviceAuthorizedViewSet

urlpatterns = [
    # Only allow creation of devices by authenticated users
    path('devices', FCMDeviceAuthorizedViewSet.as_view({'post': 'create'}), name='create_fcm_device'),
    # ...
]

Update of device with duplicate registration ID

Tokens are device specific, so if the user e.g. logs out of their account on your device, and another user logins on the same device, you do not wish the old user to receive messages while logged out.

Via DRF, any creation of device with an already existing registration ID will be transformed into an update. If done manually, you are responsible for deleting the old device entry.

Python 3 support

Django version compatibility

Compatible with Django versions 3.0+. For Django version 2.2, use version fcm-django < 1.0.13. For lower django versions, use version fcm-django < 1.0.0.

Acknowledgements

Library relies on firebase-admin-sdk for sending notifications, for more info about all the possible fields, see: https://github.com/firebase/firebase-admin-python

Migration from v0 to v1 was done by Andrew-Chen-Wang

Need help, have any questions, suggestions?

Submit an issue/PR on this project. Please do not send me emails, as then the community has no chance to see your questions / provide answers.

Contributing

To setup the development environment, simply do pip install -r requirements_dev.txt To manually run the pre-commit hook, run pre-commit run --all-files.

fcm-django's People

Contributors

abotte avatar akay7 avatar alfaro28 avatar aliharby12 avatar allprod avatar andrew-chen-wang avatar d1p avatar gabn88 avatar gonczor avatar henriklindgren avatar hornobster avatar insung151 avatar lkh42t avatar mattrowe-mango avatar maximlomakin avatar mhm5000 avatar minjatj avatar mohitcodepy avatar mrcl avatar olzhasar avatar raekkeri avatar romatallinn avatar sdbriney avatar self-maurya avatar serhiyromanov avatar simonphilips avatar sthz31 avatar unknownplatypus avatar xtrinch avatar ziima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fcm-django's Issues

Please update to using pyfcm 1.4.5

pyfcm 1.4.3 has an issue while installing via pip which transitions to installing fcm-django via pip.
This has been solved in pyfcm 1.4.5, so please update fcm-django to use the latest pyfcm version as soon as possible.

FCMDevice.send_message() method: bug in params

Hello,

There is a bug for sure in FCMDevice.send_message() method: you always provide "None" for "sound" and "badge" params:

result = fcm_send_message(
			registration_id=self.registration_id,
			title=title,
			body=body,
			icon=icon,
			data=data,
			sound=None,
			badge=None,
			**kwargs
		)

As a result - no sound on iOS.

Best regards,
Vadim

Unable to receive the message from server

On sending message/notification for very first time , it displays success and returns the message id back as a response:

device.send_message({"notification":{"title": "SAMS : Profits raised by 10%", "body": "Hello DRasF"}})
[{'failure': 0, 'canonical_ids': 0, 'success': 1, 'multicast_id': 6814660615641113568, 'results': [{u'message_id': u'0:1510052176239497%2fd9afcdf9fd7ecd'}]}]

While sending it the second time I receive this error:

device.send_message({"notification":{"title": "INFY : First Successful Trade", "body": "Hello DRasF"}})
[{'failure': 1, 'canonical_ids': 0, 'success': 0, 'multicast_id': 4697703935609967698, 'results': [{u'error': u'NotRegistered'}]}]

Could you please help me out. Also the documentation is insufficient to address this issue.

How to implement multiple FCK keys

Hello, I have two projects that use FCM, the first one is the store that receives the purchase orders, the second is the buyer who makes the orders, for each I have different projects and different FCK keys, how can I make the server have two Keys and send to my buyer and seller push notifications.

Return Type Error from models

I'm having an issue with send_message. In https://github.com/xtrinch/fcm-django/blob/master/fcm_django/models.py#L55 , a return value from FCM is changed I guess.

Internal Server Error: /admin/notification/
Traceback (most recent call last):
  File "/Users/edward/.venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/Users/edward/.venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/edward/.venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/edward/app/admin/views.py", line 27, in PushNotificationView
    body=request.POST.get('body', None),
  File "/Users/edward/.venv/lib/python3.5/site-packages/fcm_django/models.py", line 56, in send_message
    for (index, item) in enumerate(result['results']):
TypeError: list indices must be integers or slices, not str

Python 3.5.1 (default, Aug 15 2016, 18:12:18)

Django==1.10.3
django-braces==1.10.0
django-crispy-forms==1.6.1
django-filter==1.0.0
django-oauth-toolkit==0.11.0
django-widget-tweaks==1.4.1
djangorestframework==3.5.3
drfdocs==0.0.11
fcm-django==0.2.3
Markdown==2.6.7
oauthlib==1.1.2
pyfcm==1.2.1
requests==2.12.4
six==1.10.0

Question: Need help in understanding

Hi,

I would like to know whether my approach is correct in order to use this wonderful package.

  1. Create an mobile app and ask users to install the app. During the installation the app should communicate to my Django app and update FCM devices model/table with their device id's

  2. Once users register then using the send message option i can send message to their device.

  3. On Firebase I should add my newly built android app details as well so it can communicate to firebase App server.

Is my understanding correct?

Thanks,
Raj

use another model instead of auth user

hi
thanks for your great work
i set USER_MODEL in my source code (according to your code) and its seem to work ok but sometimes i get error and i think it depend on AUTH_USER
but im not wanna to send push to my auth user
how can i do it?

iOS deviice deactivated automatically

fcm_django, works well on Android device and iOS simulator for notification.
But on iOS device active become False

(iOS device deactivated)

automatically. and no notification receives
Can any one please help me.

Only one device by user

Hi. By designing my application, each user can only have one active device. What would be the fastest way to implement it?
Thank you.

Endpoints???

Hello,

I love that you guys have created an FCM wrapper for django that supports DRF. However after setting this up I realize that there I don't see any endpoints that I can call to test this tool. Is there any reason for that? Do I need to look into another library to find these endpoints???

Please let me know :)

Iphone X not receiving notifications

From: thameem stud2 [email protected]
Date: Tue, 24 Jul 2018 17:53:16 +0400
Subject: Django Fcm
To: [email protected]

Hi Mojca,

Django Fcm has got some issues with iPhonex. IphoneX not receiving message
that

sent by DjangoFcm but it is receiving from the firebase console.

And i got solution for that from this question

https://stackoverflow.com/questions/51031271/firebase-notifications-fcm-not-received-on-iphone-x

we need to add a parameter called "notification" instead of "data" inorder
to receive the notfication for iPhoneX

This is the sample code that i tried from my system and its working fine
when i add notification instead of data..

So could you please add an extra arguement "notification".

import requests

import json

url = "https://fcm.googleapis.com/fcm/send"

headers = {}

headers["UserAgent"] ="FCM-Server"
headers["Content-Type"] = "application/json"
headers["Authorization"] = "key=%s" %("xxxx")

values = {}

registration_ids = []
notification = {}

notification["title"] = "second test message"

registration_ids.append("xxxx")

values.update({"notification":notification})
values.update({"registration_ids":registration_ids})

def send_not():
resp = requests.post(url=url, data=json.dumps(values), headers=headers)
print resp.status_code
print resp.content

send_not()

How to Send Topic messages

Hi,

I quick question, I couldn't find any way to Send notification to a specific topic. is there any way to do that?

"to": "/topics/general",
"data": {
"message" : "my",
"other_key" : true,
"body":"teste number 3"
},
"notification" : {
"title" : "FCM Message",
"body" : "Still getting pushs",
"content_available" : true
},
"priority": "high"

Python 3.6 support ?

Hi,

Currently evaluating whether Firebase FCM (and by extension fcm-django) could be the right tool for us, I've seen that you mention support for Python 3.4 and 3.5. We're currently on 3.6, therefore I'd like to make sure there won't be any problem on that version. Can you confirm ?

"This field must be unique" error when trying to update device owned by multiple users

In my application, I support multiple users using the same device (and thus having the same registration ID). Create and delete queries work fine this way (the registration ID correctly gets set to inactive for all other users when it's created for one user). But when trying to update an existing registration ID, to make it inactive when the user logs out from the device, I get a "This field must be unique" error on the registration_id field.

Expected behaviour: if the update sets the notification device to active, set notification devices with the same registration ID owned by other users to inactive and then do the update. Otherwise, just do the update.

Cause: in api/rest_framework.py, there's logic to handle this for create queries, starting at line 42. The same logic is missing for update queries (starting at line 39).

Workaround: delete and re-create the notification device instead.

Debug to console

Similar to emails (django.core.mail.backends.console.EmailBackend), it would be useful if we could instead of sending real push notification simply print its content to console.

register mobile users

hi
how can i store user token (firebase token) to database that each mobile user get from firebase ?
like this :
request token and allow firebase to send notifications to your browser (device)

FCMServerError: FCM server is temporarily unavailable

followed the steps, e,g,

INSTALLED_APPS = (
        ...
        "fcm_django"
)

FCM_DJANGO_SETTINGS = {
        "FCM_SERVER_KEY": "[your api key]"
}

migrated and added one device in the table.

now I do

from fcm_django.models import FCMDevice
device = FCMDevice.objects.all().first()
device.send_message("Title", "Message")

this raises an exception saying FCMServerError: FCM server is temporarily unavailable

what could be the reason, am i missing something?

when I debugged it, in pyfcm, the response from google was 500 (in pyfcm/baseapi.py)

'\n\n<TITLE>Internal Server Error</TITLE>\n\n\n

Internal Server Error

\n

Error 500

\n\n\n'

Need "content_available" param to use Data message on iOS

Hi!

Thanks for the great extension!

In order to use Data Messages only (without Notification Message) for both Android and iOS need to add "content_available" param. Please check out documentation about this param here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream-http-messages-json
Also, there is notice about this param here: https://firebase.google.com/docs/cloud-messaging/concept-options

Note: If you want to send messages consisting of only custom key-values to an iOS device when the app is in the background, set custom key-value pairs in the data key and set content_available to true.

Best regards,
Vadim

Is there a way to know the device type?

I want to send data message if the device is android and a notification message if it´s iOS, is there a way to get the device type after this:

device = FCMDevice.objects.get(user=my_user)

something like

if device.type == "android"
    # Send a data message
elif device.type == "ios"
    # Send a notification message

send_message returns InvalidRegistration

Hi Guys!

For unknown reason when I try to send a message I have this response:
{'multicast_ids': [7427671007952509285], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None}

My django settings:
FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "<API_KEY>", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, }

I'm trying to send this message:
device.send_message("title", "hello firebase")

I'm working with:
Django = 1.11.1
fm-django = 0.2.18

Could you help me please?

Get Response from send_message()

Hi! I love this library so far. I was wondering how I can get the response from send_message()? When I run it my notification is sent to my phone but I get an AssertionError:

AssertionError at /api/job/notification/ Expected a 'Response', 'HttpResponse' or 'HttpStreamingResponse' to be returned from the view, but received a <type 'instancemethod'>

I can catch it but I wanted to know what kind of response to expect from the function so I can log it. Any help would be appreciated.

How to structure the the notification correctly?

We are using your library in conjunction with react-native-fcm library. The docs for react-native-fcm says it expects a payload that looks like the following

{
    "to":"your_fcm_device_token",
    "notification": {
        "title": "hello",
        "body": "yo"
    },
    "priority": "high"
  }

We are structuring are message as follows, but are receiving an error on the notification field.

.send_message(
	to=“fcm_device_token”,
	content_available=True,
	notification={
		“title”: value, 
		“body”: value,
		“click_action”: “fcm.ACTION.HELLO”,
	},
	priority=“high”
)

Any help would be appreciated

Error with latest DRF 3.6.2 on new documentation page (rest_framework.documentation)

Traceback:
File "/home//lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home//lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/home//lib/python3.5/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/home//lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)
File "/home//lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)
File "/home//lib/python3.5/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)
File "/home//lib/python3.5/site-packages/rest_framework/schemas.py" in get
  687.         schema = self.schema_generator.get_schema(request, self.public)
File "/home//lib/python3.5/site-packages/rest_framework/schemas.py" in get_schema
  303.         links = self.get_links(None if public else request)
File "/home//lib/python3.5/site-packages/rest_framework/schemas.py" in get_links
  342.             link = self.get_link(path, method, view)
File "/home//lib/python3.5/site-packages/rest_framework/schemas.py" in get_link
  443.         fields += self.get_filter_fields(path, method, view)
File "/home//lib/python3.5/site-packages/rest_framework/schemas.py" in get_filter_fields
  618.             fields += filter_backend().get_schema_fields(view)
File "/home//lib/python3.5/site-packages/django_filters/rest_framework/backends.py" in get_schema_fields
  99.         filter_class = self.get_filter_class(view, view.get_queryset())
File "/home//lib/python3.5/site-packages/fcm_django/api/rest_framework.py" in get_queryset
  91. 		return self.queryset.filter(user=self.request.user)

Exception Type: AttributeError at /api/v2_docs/
Exception Value: 'NoneType' object has no attribute 'user'

Unreliable

I have recently set up FCM with DRF and unfortunately it is very unreliable.

I have followed all of the directions, I have done extensive testing, and made sure this is not a user level issue. I am not sure if something is up with the source code, or with FCM but messages are sent after a long delay or never sent at all. Sometimes only 1/10 of the users will get the notifications where as 10/10 will get them.

Since there are these issues it is very hard to continue to use this framework or to continue to use firebase cloud messaging.

We are using this service paired with a iOS mobile app. Yes we are storing the correct device Registration tokens since this is given to us from firebase. All of the certificates are correct.

My questions are:
Is FCM not reliable for a production level app used at a large scale?
Are there plans for more testing using this framework with a larger data set?

Cheers!

After downloading, less a migrate file 0003_auto_20170313_1314.py

pip install fem-django

fem-django package migrate folder not include 0003_auto_20170313_1314.py

my error message
raise NodeNotFoundError(self.error_message, self.key, origin=self.origin)
django.db.migrations.exceptions.NodeNotFoundError: Migration citizens.0011_auto_20170403_1330 dependencies reference nonexistent parent node ('fcm_django', '0003_auto_20170403_1330')

abstract FCMDevice

I currently want to extend FCMDevice to use BigAutoField instead of regular AutoField, so I was thinking if its posible to move all the code in FCMDevice to "AbstractFCMDevice" and make FCMDevice inherit from AbstractFCMDevice this way FCMDevice will work out of the box as it is now, but with the flexibility to modify it if necessary

Need 'collapse_key' and 'priority' parameters

Hi xtrinch,

Thanks for the library. It's very useful.
Btw, I need 'collapse_key' and 'priority' parameters for sending message in Android. Could you please add them as well? Thanks.

FCMDevice.send_message() parameter missing for iOS Background notification and sound

Hello,
In iOS, to provide a background notification, the JSON sent to firebase MUST have a key "content_available" : true
and other issue there is no sound on notification.
this is my working json with sound and background notification for iOS.

{ 
   "data":{  
      "key":"..."
   },
   "content_available" : true,
   "notification":{ 
       "sound": "default",
       "title": "...",
       "body":"..."
   },
 "to":"..." 
}

Sending messages in bulk not working

Simply don't send. No errors, no messages.

# This not work:
devices = FCMDevice.objects.all():
devices.send_message('Hello', 'World')

# This ugly solution yes, works
for device in FCMDevice.objects.all():
    device.send_message('Hello', 'World')

'bool' object is not callable

project/venv_btg/lib/python3.5/site-packages/fcm_django/api/rest_framework.py in validate, line 62

Request Method: | POST
Request URL: http://xjsjhsjd.com/rest/devices/
Django Version: 2.0
Exception Type: TypeError
Exception Value: 'bool' object is not callable
Exception Location:: project/venv_btg/lib/python3.5/site-packages/fcm_django/api/rest_framework.py in validate, line 62
Python Executable: project/venv_btg/bin/python3.5
Python Version: 3.5.2
Python Path:['project/btg_artciles', 'project/venv_btg/bin', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', 'project/venv_btg/lib/python3.5/site-packages', 'project/btg_artciles']

Server time:Thu, 4 Jan 2018 17:41:31 +0530

New device auto set active=False

Hi,

I'm getting a weird issue, can't seem to find out the reason why, as the default value in device model of active field is set to True.
However when I try to create a new device (without explicitly pass active), active is automatically set to False.

Seems like extra_kwargs = {"active": {"default": True}} doesn't work as expected. Only when active is added to read_only_fields then it works.

Anyone get the same issue?
Thanks

Send rich notifications in iOS

I'm not able to send "mutable_content": True in extra kwargs as an additional keyword argument (which is required to send rich notifications to iOS). I am getting notify_single_device() got an unexpected keyword argument 'mutable_content' error. I looked in PyFCM documentation, it supports this field in additional arguments. Please help.

is_user_authenticated() throws exception

screen shot 2018-05-25 at 1 50 11 am

When I make a request to register device above exception django throws.

Django version I use :
VERSION = (1, 11, 2, 'final', 0)

What happens:
in fcm-django/fcm_django/api/rest_framework.py
is_user_authenticated() function might be wrongly implemented.

How to solve:

For Django 1.10 +
is_authenticated is now an attribute

Solution 1:
we could use rest_framework's
from rest_framework.compat import is_authenticated

and instead of is_user_authenticated(user) we could use is_authenticated(user)

Solution 2
we correct the is_user_authenticated() method below way:

def is_user_authenticated(user):
    if  DJ_VERSION < (1, 10):
        return user.is_authenticated()
    return user.is_authenticated

Note: Please correct me if I am wrong.

[Issue] FCM table saving id of user instead of username

I have a custom user model, however, when i register a device, the fcm-django model registers the id column of the related username or (partner_id in my case) to the user_id column.

I want the user_id to have username and not the id of the particular username

I have attached screenshots of the tables, how can i fix this? I need to send push notifications to a particular username(partner_id) which is my unique identifier for data across other tables.

PS: partner_id == username.

My users table:
screen shot 2017-11-28 at 4 12 27 pm

fcm-django table:
screen shot 2017-11-28 at 4 12 58 pm

[Question] Problems while running migrations

Hi @xtrinch ,

When we run migrations, it shows

Running migrations:
  Applying fcm_django.0003_auto_20170313_1314... OK

Looking into the table- django_migrations, it shows that only the migration 0003_auto has run.
Migration 0001_initial and 0002_auto do not run at all.

Hence, there is no table created in my DB as well.

What can be the solution to this?

Send additional fields in kwargs

extra_kwargs = {
'content_available': True
}
devices.send_message(
title="Syncup",
body=".",
icon="appicon",
data={
"notification type" : 20
},
kwargs=extra_kwargs
)

I am trying to send additional fields in kwargs but I am getting notify_multiple_devices() got an unexpected keyword argument 'kwargs'. Please help.
Also, I don't want to send the key "body" but when I skip it or make it None, the payload gets messed up. So, is it possible it skip this key entirely?

InternalPackageError

When trying to send notification to multiple devices (and only one is in queryset) I get InternalPackageError(u'to\n',) if that device is active=False

The same error through administration

InternalPackageError at /admin/fcm_django/fcmdevice/

to

Request Method: POST
Request URL: http://localhost:8000/admin/fcm_django/fcmdevice/
Django Version: 1.10.1
Exception Type: InternalPackageError
Exception Value:

to

Exception Location: .../lib/python2.7/site-packages/pyfcm/baseapi.py in send_request, line 205

I know you shouldn't try and send a notification to an inactive device, but I think this should be handled.

Might be related to (fix issue?) olucurious/PyFCM#60

FCMDeviceAuthorizedViewSet allows duplicate registrations with same device ID and registration token

I've hooked up FCMDeviceAuthorizedViewSet to Django REST framework using DefaultRouter as described in the manual, and configured my app to POST to my base URL /api/fcm/. Registration seems to be working nicely, except for the fact that the creation view by FCMDeviceAuthorizedViewSet seems to allow for the same device ID to be registered to the same user again, even if the registration token is identical.

The manual states "Will allow duplicate registration_id’s for different users, so you are responsible for cleanup (if that is generally perceived as undesired behaviour or if the package itself should be doing the cleanup, open an issue or email me)". It seems that the most logical behavior would be to allow one user to register multiple unique device IDs, and only update the registration_token for existing device IDs.

Problem when logging in with another account

I have a problem when I follow next steps

1.- When I logout from account A and login with account B, A stays but is disabled

2.- I logout from B and want to login on A again, A already exists but is disabled so I get a conflict and A is not re-enabled

3.- B is disabled because I tried to login with A so now both are disabled and I am not getting any fcm

Is there a way of make both work for the same device or delete the device which is logging out? any of them would be useful

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.