GithubHelp home page GithubHelp logo

xtrinch / fcm-django Goto Github PK

View Code? Open in Web Editor NEW
750.0 17.0 189.0 292 KB

FCM Django: Send push notifications via django to websites, iOS & android mobile devices through FCM (Firebase Cloud Messaging)

Home Page: http://fcm-django.readthedocs.io/

License: MIT License

Python 100.00%
fcm-notifications django django-rest-framework push-notifications fcm firebase-cloud-messaging

fcm-django's Issues

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.

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.

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'

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 :)

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')

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.

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

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

"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.

'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

[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?

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

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?

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()

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 ?

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":"..." 
}

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)

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 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

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.

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.

[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: 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

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

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?

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

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')

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'

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.

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

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.

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!

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"

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.

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.

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.

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?

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

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

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.