Push notifications - what are they with and how to configure them in Django?

Push notifications - what are they with and how to configure them in Django?

Push notifications - these are notifications that we receive immediately after someone, for example, sends us a message via a messenger, such as: Messenger, slack or bitrix. They are supported by various operating systems (yes, current Windows 10 computers also support this technology) and by various applications, such as: a browser, a game written in Unity or a mobile application).

But how is it that we don't have to worry about messenger being turned on? This is due to the so-called Service Worker - a background service that can also be used for e.g. background data synchronization. Of course, in this case the question arises - what about the security of such a solution? After all, someone could use our equipment when we do not use it, for evil purposes!

We reassure - the security of this technology prevents unauthorized persons from accessing the permissions and functions that allow them to take control of our device.

More technically - that is, Google Firebase

Google Firebase technology gives access to many solutions, e.g. authentication, cloud file support, configuration without the need for deployment and much, much more, including what we are interested in, i.e. handling messages in the application.

 

From the programming point of view, it looks like this - we send a query from the server to Google servers, where Firebase stands, and when the phone is available on the network, Firebase sends a message to it. This eliminates the problem of lack of Internet connectivity - messages (queries) simply group in the Google cloud, which does not require us to write additional code.

Putting the service on the Google server

https://firebase.google.com/docs/cloud-messaging/js/client

 

We need to go to the Firebase console and create a project, get the server key, application name and sender ID from it - this is needed to authenticate with the server.

Google cloud app development

 

https://console.developers.google.com/apis/dashboard

What we have just done serves us only to receive messages from the client. If we want to send messages, we must enter the google cloud, create the appropriate interface and unlock the Firebase Messaging API with the appropriate permission (otherwise we will get an insufficient permissions error). I must admit that I did not delve into each type of permissions separately and I just assigned the owner account.

From here we will need a json file with login data such as private key, via the corresponding tab.

Firebase implementation problem in Django - what about firebase-messaging-sw.js?

 

path('firebase-messaging-sw.js', ServiceWorkerView.as_view(), name='service_worker'),

 

Firebase loads firebase-messaging-sw.js from the root directory by default. All we need to do is define a view that will return this file under the url just like the file name.

class ServiceWorkerView(TemplateView):
    def get(self, request, *args, **kwargs):
        service_url = os.path.join(BASE_DIR, 'templates/firebase-messaging-sw.js')
        return render(request, service_url, content_type="application/x-javascript")

What's next?

When we have all the data, we need to code our "service" that will send a message to the token of our device, when a change is detected, e.g. a new article added to the website - for the tests alone, I wrote a command that does exactly this, but without a special trigger:

def send_to_token():
    message = messaging.Message(
        data={
            'score': '850',
            'time': '2:45',
        },
        token='f1TbiTptFfk:APA91bGEyE-aIXaX2A-aOXmgT8syfJJFTVHE0ZuZAzE9xsJYXVltNcKrHIPKkijODGrKXVlueEuIqTHwD1uSKU6kFc0hY-pKxAb_LFgk9_fUT6DhIeUrUhE4ONQ6qOmWMLIeEMgNApsa'
    )

    response = messaging.send(message)
    print('Successfully sent message:', response)


class Command(BaseCommand):
    help = 'Send example message to FireBase app'

    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        send_to_token()

Before that, we need to initialize our application using the appropriate code:

import firebase_admin
from django.core.management.base import BaseCommand
from firebase_admin import credentials, messaging

from project.settings import BASE_DIR

creds = credentials.Certificate(os.path.join(BASE_DIR, 'webtechnika.json'))
default_app = firebase_admin.initialize_app(creds)

Now, we will have to program the message handler in JavaScript or our application - and I leave this task to you,  reader :) We have a lot of possibilities - we have to program the token receiving and forwarding e.g. via Ajax to the server, write an appropriate service worker that will receive messages in the background and that would be all. Everything properly described for various technologies can be found here:         

https://firebase.google.com/docs/cloud-messaging/ 

Everything should be no more than 200 lines of code, and it's nothing complicated. If we want to write it in JavaScript, remember to refer to the firebase and firebase.messaging classes, initialize the application first and write the appropriate event handler.

That's it for Push Notifications. Of course, Firebase allows much more, but more articles on our website will be about that :) I hope I have made it easier to understand this technology and how to use it.