Skip to content

Commit e241192

Browse files
author
Nitin Raturi
committed
Push working
2 parents 7cf4906 + d948a07 commit e241192

File tree

7 files changed

+103
-34
lines changed

7 files changed

+103
-34
lines changed

__pycache__/main.cpython-35.pyc

185 Bytes
Binary file not shown.
251 Bytes
Binary file not shown.

main.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import json, os
3+
from solidwebpush import Pusher
34

45
from flask import request, Response, render_template, Blueprint, redirect, url_for
56
from flask import jsonify
@@ -36,10 +37,6 @@ def subscription():
3637
def push_to_all_users():
3738
token = request.form.get('sub_token')
3839
message = request.form.get('message')
39-
40-
token = '{"endpoint":"https://fcm.googleapis.com/fcm/send/cn2zZ1wyZmU:APA91bEBokYMmP36-gLljRWai79Uc6WOxqjum1ztj-Wm6JTkIf6DbtO05R2uXe7O1RfKYZqp0uRZR3K36-7UP-X3FeVR2Wy4NIGYHjiVLSWML8ETGdHA8UNhv5hMJWI7WJcEv1tpce0v","expirationTime":null,"keys":{"p256dh":"BDRC9vUDGoGzt8gefuR5qTPsT3_st_bU8sPj970T5xmY7RjtAVf6Yof1AwS3D6p3U3JmAqpukF7V_VC5uQw5Nec","auth":"MJNVm_d4GJblbEb9PuirJA"}}'
41-
message = "hello"
42-
4340
print("token",token)
4441
print("message",message)
4542
try:
@@ -48,3 +45,24 @@ def push_to_all_users():
4845
print("error",e)
4946

5047
return redirect(url_for('main.index'))
48+
49+
50+
@main.route("/push_v1/",methods=['POST'])
51+
def push_v1():
52+
pusher = Pusher()
53+
message = "Push Test v1"
54+
print("is_json",request.is_json)
55+
56+
if not request.json or not request.json.get('sub_token'):
57+
return jsonify({'failed':1})
58+
59+
print("request.json",request.json)
60+
61+
token = request.json.get('sub_token')
62+
try:
63+
pusher.sendNotification(token, message)
64+
# send_web_push(json.loads(token), message)
65+
return jsonify({'success':1})
66+
except Exception as e:
67+
print("error",e)
68+
return jsonify({'failed':str(e)})

settings.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,28 @@
1+
from solidwebpush import Pusher
12
import os
23

3-
DER_BASE64_ENCODED_PRIVATE_KEY_FILE_PATH = os.path.join(os.getcwd(),"private_key.txt")
4-
DER_BASE64_ENCODED_PUBLIC_KEY_FILE_PATH = os.path.join(os.getcwd(),"public_key.txt")
4+
# DER_BASE64_ENCODED_PRIVATE_KEY_FILE_PATH = os.path.join(os.getcwd(),"vapid","private_key.txt")
5+
# DER_BASE64_ENCODED_PUBLIC_KEY_FILE_PATH = os.path.join(os.getcwd(),"vapid","public_key.txt")
6+
#
7+
#
8+
# print("private_key",DER_BASE64_ENCODED_PRIVATE_KEY_FILE_PATH)
9+
# print("public_key",DER_BASE64_ENCODED_PUBLIC_KEY_FILE_PATH)
10+
# VAPID_PRIVATE_KEY = open(DER_BASE64_ENCODED_PRIVATE_KEY_FILE_PATH, "r+").readline().strip("\n")
11+
# VAPID_PUBLIC_KEY = open(DER_BASE64_ENCODED_PUBLIC_KEY_FILE_PATH, "r+").read().strip("\n")
512

6-
VAPID_PRIVATE_KEY = open(DER_BASE64_ENCODED_PRIVATE_KEY_FILE_PATH, "r+").readline().strip("\n")
7-
VAPID_PUBLIC_KEY = open(DER_BASE64_ENCODED_PUBLIC_KEY_FILE_PATH, "r+").read().strip("\n")
13+
def generate_public_key():
14+
pusher = Pusher()
15+
key = pusher.getB64PublicKey()
16+
print("public key",key)
17+
return key
18+
19+
def save_key_file():
20+
path = os.path.join(BASE_DIR,"vapid","public_key.txt")
21+
key = generate_public_key()
22+
with open(path,'w') as f:
23+
f.write(key)
24+
25+
26+
if __name__ == "__main__":
27+
BASE_DIR = os.getcwd()
28+
save_key_file()

static/main.js

Lines changed: 49 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
'use strict';
22

3+
const applicationServerPublicKey = "BNbxGYNMhEIi9zrneh7mqV4oUanjLUK3m+mYZBc62frMKrEoMk88r3Lk596T0ck9xlT+aok0fO1KXBLV4+XqxYM=";
4+
const pushButton = document.querySelector('.js-push-btn');
35

6+
let isSubscribed = false;
7+
let swRegistration = null;
48

59
function urlB64ToUint8Array(base64String) {
610
const padding = '='.repeat((4 - base64String.length % 4) % 4);
@@ -44,14 +48,14 @@ function updateSubscriptionOnServer(subscription) {
4448
if (subscription) {
4549
subscriptionJson.textContent = JSON.stringify(subscription);
4650
subscriptionDetails.classList.remove('is-invisible');
47-
console.log("subscribe",JSON.stringify(subscription));
4851
} else {
4952
subscriptionDetails.classList.add('is-invisible');
5053
}
5154
}
5255

5356
function subscribeUser() {
54-
const applicationServerKey = urlB64ToUint8Array(document.applicationServerPublicKey);
57+
// const applicationServerPublicKey = localStorage.getItem('applicationServerPublicKey');
58+
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
5559
swRegistration.pushManager.subscribe({
5660
userVisibleOnly: true,
5761
applicationServerKey: applicationServerKey
@@ -60,6 +64,7 @@ function subscribeUser() {
6064
console.log('User is subscribed.');
6165

6266
updateSubscriptionOnServer(subscription);
67+
localStorage.setItem('sub_token',JSON.stringify(subscription));
6368
isSubscribed = true;
6469

6570
updateBtn();
@@ -68,7 +73,7 @@ function subscribeUser() {
6873
console.log('Failed to subscribe the user: ', err);
6974
updateBtn();
7075
});
71-
}push_message
76+
}
7277

7378
function unsubscribeUser() {
7479
swRegistration.pushManager.getSubscription()
@@ -117,27 +122,48 @@ function initializeUI() {
117122
});
118123
}
119124

120-
document.init_push = function(){
121-
const pushButton = document.querySelector('.js-push-btn');
122-
123-
let isSubscribed = false;
124-
let swRegistration = null;
125+
if ('serviceWorker' in navigator && 'PushManager' in window) {
126+
console.log('Service Worker and Push is supported');
125127

126-
if ('serviceWorker' in navigator && 'PushManager' in window) {
127-
console.log('Service Worker and Push is supported');
128+
navigator.serviceWorker.register("/static/sw.js")
129+
.then(function(swReg) {
130+
console.log('Service Worker is registered', swReg);
128131

129-
navigator.serviceWorker.register("/static/sw.js")
130-
.then(function(swReg) {
131-
console.log('Service Worker is registered', swReg);
132+
swRegistration = swReg;
133+
initializeUI();
134+
})
135+
.catch(function(error) {
136+
console.error('Service Worker Error', error);
137+
});
138+
} else {
139+
console.warn('Push meapplicationServerPublicKeyssaging is not supported');
140+
pushButton.textContent = 'Push Not Supported';
141+
}
132142

133-
swRegistration = swReg;
134-
initializeUI();
135-
})
136-
.catch(function(error) {
137-
console.error('Service Worker Error', error);
138-
});
139-
} else {
140-
console.warn('Push messaging is not supported');
141-
pushButton.textContent = 'Push Not Supported';
142-
}
143+
function push_message() {
144+
console.log("sub_token", localStorage.getItem('sub_token'));
145+
$.ajax({
146+
type: "POST",
147+
url: "/push_v1/",
148+
contentType: 'application/json; charset=utf-8',
149+
dataType:'json',
150+
data: JSON.stringify({'sub_token':localStorage.getItem('sub_token')}),
151+
success: function( data ){
152+
console.log("success",data);
153+
},
154+
error: function( jqXhr, textStatus, errorThrown ){
155+
console.log("error",errorThrown);
156+
}
157+
});
143158
}
159+
160+
// $(document).ready(function(){
161+
// $.ajax({
162+
// type:"GET",
163+
// url:'/subscription/',
164+
// success:function(response){
165+
// console.log("response",response);
166+
// localStorage.setItem('applicationServerPublicKey',response.public_key);
167+
// }
168+
// })
169+
// });

static/sw.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
/* eslint-disable max-len */
44

5+
const applicationServerPublicKey = "BNbxGYNMhEIi9zrneh7mqV4oUanjLUK3m+mYZBc62frMKrEoMk88r3Lk596T0ck9xlT+aok0fO1KXBLV4+XqxYM=";
6+
57
/* eslint-enable max-len */
68

79
function urlB64ToUint8Array(base64String) {
@@ -45,7 +47,8 @@ self.addEventListener('notificationclick', function(event) {
4547

4648
self.addEventListener('pushsubscriptionchange', function(event) {
4749
console.log('[Service Worker]: \'pushsubscriptionchange\' event fired.');
48-
const applicationServerKey = urlB64ToUint8Array(document.applicationServerPublicKey);
50+
// const applicationServerPublicKey = localStorage.getItem('applicationServerPublicKey');
51+
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
4952
event.waitUntil(
5053
self.registration.pushManager.subscribe({
5154
userVisibleOnly: true,

templates/index.html

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,16 @@ <h1>WebPush Notification</h1>
3737

3838
<hr>
3939
<p>You can test push notification below.</p>
40+
<button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onclick="push_message()">Test Push Notification</button>
4041

41-
<form action="/push/" method="POST">
42+
<!-- <form action="/push/" method="POST">
4243
<div class="mdl-textfield mdl-js-textfield">
4344
<input required type="hidden" name="sub_token" id="sub_token">
4445
<label class="mdl-textfield__label" for="message">Your message.</label>
4546
<input class="mdl-textfield__input" required type="text" name="message" id="message">
4647
</div>
4748
<button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored">PUSH</button>
48-
</form>
49+
</form> -->
4950
</section>
5051
</main>
5152

0 commit comments

Comments
 (0)