How to send web push notification for all active users - javascript

here I have used the button to send web push notifications. using this button only on the same browser notification came. but I want to send the same push notification to all active users. below is my code.
let applicationServerPublicKey = 'myKey';
var pushButton = document.querySelector('.js-push-btn');
var pushNotiButton = document.querySelector('.push-btn');
let isSubscribed = false;
let swRegistration = null;
function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function updateBtn() {
if (isSubscribed) {
pushButton.textContent = 'Disable Push Messaging';
} else {
pushButton.textContent = 'Enable Push Messaging';
}
pushButton.disabled = false;
}
function updateSubscriptionOnServer(subscription) {
// TODO: Send subscription to application server
console.log('subscription'+JSON.stringify(subscription))
const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');
if (subscription) {
//subscriptionJson.textContent = JSON.stringify(subscription);
//subscriptionDetails.classList.remove('is-invisible');
} else {
//subscriptionDetails.classList.add('is-invisible');
}
}
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
function initializeUI() {
//pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
// TODO: Unsubscribe user
} else {
subscribeUser();
}
//});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('{% url 'sw.js' %}').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
swRegistration = registration;
initializeUI();
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
$(".push-btn").click(function(event) {
console.log('[Service Worker] Push Received.');
//console.log('[Service Worker] Push had this data: ');
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
//icon: 'images/icon.png',
//badge: 'images/badge.png'
};
navigator.serviceWorker.getRegistration().then(reg => {
reg.showNotification(title, options);
});
//event.waitUntil(ServiceWorkerRegistration.registration.showNotification(title, options));
});
let deferredPrompt;
let addBtn = document.querySelector('#add-home-screen-btn');
let homeScreenBlock = document.querySelector("#home-screen-btn-block")
homeScreenBlock.style.display = 'none';
window.addEventListener('beforeinstallprompt',(e)=>{
e.preventDefault();
deferredPrompt = e;
homeScreenBlock.style.display = 'block';
addBtn.addEventListener('click',(e)=>{
homeScreenBlock.style.display='none';
deferredPrompt.prompt();
deferredPrompt.userChoice
.then((choiceResult)=>{
if(choiceResult.outcome === 'accepted'){
console.log('Accepted A2SH')
}else {
console.log('user declined')
}
deferredPrompt = null;
})
})
});

Related

API getting multiple Calls

My program in a nutshell. If the trigger word is detected in the message, my application creates invoices.
The issue: Multiple calls to the trigger function. All of the requests to the API are simultaneous. This causes my data to have problems.
I have added the async and await to wait for the trigger function to complete. But it seems my calls are still being called all together.
// Links to a Facebook Live.
export const fblive = async (liveid) => {
if (liveid != null) {
try {
const reg = new RegExp("\\d{5,}");
const found = liveid.match(reg);
if (found > 0) {
console.log(found, " || ", found[0]);
let activate = false;
var userid = "";
//var accesstoken = ''
var accesstoken =''
var videoID = found;
var live_url =
"https://streaming-graph.facebook.com/" +
videoID +
"/live_comments?access_token=" +
accesstoken +
"&comment_rate=one_hundred_per_second&fields=from{name,id},message";
var source = new EventSource(live_url);
source.onmessage = function (event) {
var result = JSON.parse(event["data"]);
let trigger_word = result["message"].search("#");
// looking at comments
readcomment(result["message"]);
if (result["from"] != null) {
console.log("FROM ! !:", result["from"]);
}
};
} else {
console.log("ZERO FOUND");
}
} catch (error) {
console.log("FB LIVE COMMENT IS NOT RUNNING");
}
} else {
console.log("Live ID not valid");
}
};
// Looking at every comment in a facebook live
export const readcomment = async (the_comment) => {
try {
console.log(" CALLING LIVE READ COMMENT ", the_comment);
let re = await new Promise((resolve) =>
setTimeout(
setTimeout(async function () {
console.log(the_comment);
if (the_comment.includes("#")) {
populatelist();
console.log(the_comment);
let new_string = the_comment.trim().split(" ");
console.log(new_string, " STRING SPLIT");
let customer_found = await findcust(new_string);
let item_found = await finditem(new_string);
console.log(customer_found, item_found, "WE FOUND ");
if (customer_found != false && item_found != false) {
console.log("THERE'S A TRIGGER SALE HERE");
let remove = await find_remov(new_string);
console.log(remove, "WE ARE LOOKING AT RMOVE ");
await comment_trigger(customer_found,item_found,remove)
console.log(the_comment)
console.log("promise for " , the_comment, " has been fullfilled")
}
}
}, 2000)
)
);
} catch (error) {
console.log(error.response)
}
};
// This is when a comment was found to be the triggers words (customer id and a item name)
export const comment_trigger = async (customer, item, rmv) => {
// FIND THE ITEM IN INVOICE.
const client = find(customer, customer_list1);
const real_item = find(item, item_list1);
try {
console.log(client, real_item);
if (client != false && real_item != false) {
let inv = await invoicesbycustomer(client.id);
console.log(inv);
if (inv == undefined || inv.length ==0) {
console.log(customer, item);
console.log(real_item.id);
let new_Invoice = new Invoice("", client);
let new_item = new Product(real_item.id, real_item.name, 1);
await new_Invoice.addItem(new_item);
console.log(new_Invoice);
await createInvoice(new_Invoice);
console.log("NO INVOICE WAS FOUND FOR THIS CLIENT");
} else {
console.log(inv);
// making sure there's a real invoice.
console.log("DATA TYPE IS ", typeof inv);
if (typeof inv !== "undefined") {
console.log(inv, "THIS IS INVOICE WITH CLIENT");
console.log(inv[0].node.items.length);
let oldItems = inv[0].node.items;
let NewInvoice = new Invoice(
inv[0].node.id,
inv[0].node.customer.id
);
let Itemsize = oldItems.length;
let found = false;
if (Itemsize > 0) {
//IF ITEMS EXIST ADD QTY.
// ELSE ADD THIS NEW ITEM.
for (let x in oldItems) {
if (real_item.id == oldItems[x].product.id) {
found = true;
}
}
if (found && rmv == "removeqty") {
await removeqtyitem(customer, item);
} else if (found && rmv == "removeAll") {
await removeitem(customer, item);
} else if (found) {
let aqi = await addqtyitem(customer, item);
} else {
// add item
await additems(customer, item);
}
} else {
await additems(customer, item);
}
}
}
} else {
let errmssg = "";
if (!client) {
errmssg = errmssg.concat(" ", " Client is not valid ");
console.log("client not found", errmssg);
}
if (!real_item) {
errmssg = errmssg.concat("", " Item not found");
}
console.log(errmssg);
console.error(errmssg);
}
} catch (error) {
console.error(error.response.data)
}
};
Here's an example of the api being called. this is using graphql
//DELETING INVOICE API CALL
export const deleteInvoice = async(id) => {
const invoiceId = id;
console.log(invoiceId, "THIS I S INVOICE DELET EDELETE DELETE DELTE ")
try {
const token = "zCtQa00zlorbFFum6I7Rlzc0QwMDoS";
const shema = `
mutation ($input: InvoiceDeleteInput !) {
invoiceDelete(input: $input) {
didSucceed
inputErrors {
path
code
message
}
}
}`;
//About to submit my shema to waveapps
const API_URL="https://gql.waveapps.com/graphql/public"
const bussID = "QnVzaW5lc3M6ZTIyZmVhODEtNjg5OC00N2ZiLTgzOGItYWMyYzllNDZiM2Jk";
let watch = await axios(API_URL, {
method: "POST",
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
data:{
query: shema,
variables: {
input:{
invoiceId: invoiceId,
}
},
},
})
console.log(watch.data)
} catch (error) {
console.log(error.response)
}
//console.log("return delete invoice complete")
};
I have used async/await and promises.
When multiple calls are made. The await and promises are still being called at the same time. Not sure what else to look at? any suggestions please. I have spent a week on this.

Socket.io - shows an argument as "undefined" and randomly stops the app

I'm working on a simple chat app which was originally forked from a GitHub repo.
It works, but there's there's an error that randomly occurs and stops the app from running.
Server side code
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
const botName = 'CCBot';
v = process.env;
// Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ token, username, room }) => {
console.log(token, username, room)
if (token == v.TOKEN_1){username = v.N_1}
else if (token == v.TOKEN_2){username = v.N_2}
else if (token == v.TOKEN_3){username = v.N_3}
else{
socket.emit("redirect"); return
}
const user = userJoin(socket.id, username, room, token, false);
socket.join(user.room);
// Welcome current user
socket.emit('message', formatMessage(botName, 'Welcome!'));
// Broadcast when a user connects
socket.broadcast
.to(user.room)
.emit(
'message',
formatMessage(botName, `${user.username} has joined the chat!`, 'green')
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id)
console.log(user)
//The error originates on the below line
io.to(user.room).emit('message', formatMessage(user.username, msg, )); //The error occurs here
});
socket.on('userLeave', (id) => {
const user = getCurrentUser(id)
console.log(user)
socket.emit("sendMessages", user)
})
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit(
'message',
formatMessage(botName, `${user.username} has left the chat.`, "red")
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(300, () => console.log(`Server running on port 3000`));
Util functions
const users = [];
// Join user to chat
function userJoin(id, username, room, auth, admin ) {
const user = { id, username, room, admin };
users.push(user);
return user;
}
// Get current user
function getCurrentUser(id) {
return users.find(user => user.id === id);
}
// User leaves chat
function userLeave(id) {
const index = users.findIndex(user => user.id === id)
if (index !== -1) {
return users.splice(index, 1)[0];
}
}
// Get room users
function getRoomUsers(room) {
return users.filter(user => user.room === room);
}
module.exports = {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
};
function formatMessage(username, text, color) {
return {
username,
text,
time: moment().tz("My Timezone here.").format('h:mm a'),
color
};
}
module.exports = formatMessage;
Client Side
let notif = undefined;
// Get username and room from URL
const { username, room, token, t2 } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
listUsers = [];
const socket = io();
// Join chatroom
socket.emit('joinRoom', { username, room, token });
// Get room and users
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
socket.on("redirect", () => {
try { window.location = "wrongpassword.html" }
catch (e) {
window.location = "about:blank"
}
})
// Message from server
socket.on('message', (message) => {
console.log(message);
outputMessage(message);
// Scroll down
chatMessages.scrollTop = chatMessages.scrollHeight;
});
socket.on("sendMessages", user => {
banned.push(user.username)
socket.emit("BAN_ALERT")
})
// Message submit
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
// Get message text
let msg = e.target.elements.msg.value;
msg = msg.trim();
if (!msg) {
return false;
}
// Emit message to server
socket.emit('chatMessage', msg);
// Clear input
e.target.elements.msg.value = '';
e.target.elements.msg.focus();
});
function enableNotif(){
notif = true;
}
function disableNotif(){
notif = false;
}
// Output message to DOM
function outputMessage(message) {
if (message.text == ".clear" || message.text ==
".c") {
try {
document.querySelector(".chat-messages").innerHTML = ""
return
}
catch (e) {
window.location.reload(true)
return
}
}
else if (message.text == ".exit" || message.text == ".e"){
location = "about:blank"
}
else if (message.text == ".users"){
console.log(userList)
div = document.createElement('div');
div.classList.add('message');
const p = document.createElement('p');
p.classList.add('meta');
p.innerText = "CCBot";
p.innerHTML += ` <span>${message.time}</span>`;
div.appendChild(p);
const para = document.createElement('p');
para.classList.add('text');
para.innerText = listUsers;
color = "black";
if(color){para.style.color = color}
else{para.style.color = "black"}
div.appendChild(para);
document.querySelector('.chat-messages').appendChild(div);
}
else {
const div = document.createElement('div');
div.classList.add('message');
const p = document.createElement('p');
p.classList.add('meta');
p.innerText = message.username;
p.innerHTML += ` <span>${message.time}</span>`;
div.appendChild(p);
const para = document.createElement('p');
para.classList.add('text');
para.innerText = message.text;
color = message.color;
if(color){para.style.color = color}
else{para.style.color = "black"}
div.appendChild(para);
document.querySelector('.chat-messages').appendChild(div);
if (notif) {
var audio = new Audio('./media/notif.mp3');
console.log(audio)
audio.play();
}
}
}
// Add room name to DOM
function outputRoomName(room) {
roomName.innerText = room;
}
// Add users to DOM
function outputUsers(users) {
userList.innerHTML = '';
users.forEach((user) => {
const li = document.createElement('li');
li.innerHTML = `${user.username} <br><hr>`;
li.style = "cursor:pointer;"
userList.appendChild(li);
listUsers.push(li.innerText)
});
}
//Prompt the user before leave chat room
document.getElementById('leave-btn').addEventListener('click', () => {
const leaveRoom = confirm('Are you sure you want to leave the chatroom?');
if (leaveRoom) {
window.location = '../index.html';
} else {
}
});
Error
TypeError: Cannot read property 'room' of undefined
at Socket.socket.on.msg (/home/duck/server.js:51:16)
at Socket.emit (events.js:198:13)
at /home/duck/node_modules/socket.io/lib/socket.js:528:12
at process._tickCallback (internal/process/next_tick.js:61:11)
/home/duck/server.js:51
io.to(user.room).emit('message', formatMessage(user.username, msg));
^
The repo already has this issue opened, but there's no response to it.
I'm not sure why the error occurs.
Thanks in advance.
P.S, Please ignore anything related to banning/removing users.

Remote video stream not displaying

RTCPeerConnection gets established and receives the clients reply which is 'answer' but does not show the remote video stream. The console log is shown below
console.log
From the log, the offer is sent to the peer which the peer sends back an answer that is console logged to display that it did actually send the answer back. I would greatly appreciate if you could take a look at my code pasted below and advise me how to go about rectifying it.
'use strict';
var localStream;
var remoteStream;
var isInitiator;
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
startVideo();
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
function sendMessage(message) {
socket.emit('message', message);
}
// This client receives a message
socket.on('message', function(message) {
if (message.type === 'offer') {
pc.setRemoteDescription(message);
console.log('Sending answer to peer.');
pc.createAnswer().then(
setLocalAndSendMessage,
onCreateSessionDescriptionError
);
} else if (message.type === 'answer') {
console.log('This is to check if answer was returned');
remoteStream = event.stream;
remoteVideo.srcObject = remoteStream;
pc.setRemoteDescription(message);
} else if (message.type === 'candidate') {
pc.addIceCandidate(candidate);
}
});
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(gotStream)
.catch(function(e) {
alert('getUserMedia() error: ' + e.name);
});
}
function gotStream(stream) {
localVideo.srcObject = stream;
localStream = stream;
callButton.disabled = false;
}
function callStart() {
createPeerConnection();
callButton.disabled = true;
hangupButton.disabled = false;
if (isInitiator) {
console.log('Sending offer to peer');
pc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc.onicecandidate = ({ candidate }) => sendMessage({ candidate });
pc.ontrack = event => {
if (remoteVideo.srcObject) return;
remoteVideo.srcObject = event.stream;
};
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function handleCreateOfferError(event) {
console.log('createOffer() error: ', event);
}
function setLocalAndSendMessage(sessionDescription) {
console.log('setLocalAndSendMessage sending message', sessionDescription);
pc.setLocalDescription(sessionDescription);
sendMessage(sessionDescription);
}
function onCreateSessionDescriptionError(error) {
console.log('Failed to create session description: ' + error.toString());
}
function hangupCall() {
pc.close();
pc = null;
}

How do I send value of a text box as a web push notification?

Presently I am able to send "hello" as notification. Now I want to send value of a text box as notification.below is the code I am using. What changes I need to do?
Here is my index.html:
<html>
<body>
<h1>Web Push Notification</h1>
<button id="push-subscription-button">Push notifications !
</button><br><br>
<input name="message" id="message" value=""
placeholder="Message"/><br><br>
<button id="send-Push-Button">Send Push notifications</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Here is send_push_notification.php:
<?php
require __DIR__ . '/../vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$subscription = json_decode(file_get_contents('php://input'),
true);
$auth = array(
'VAPID' => array(
'subject' => '',
'publicKey' => '',
'privateKey' => ' '
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello",
$subscription['key'],
$subscription['token'],
true
);
app.js:
document.addEventListener("DOMContentLoaded", () => {
const applicationServerKey = "`enter code here`";
let isPushEnabled = false;
const pushButton = document.querySelector('#push-subscription-
button');
if (!pushButton) {
return;
}
pushButton.addEventListener('click', function() {
if (isPushEnabled) {
push_unsubscribe();
} else {
push_subscribe();
}
});
if (!('serviceWorker' in navigator)) {
console.warn("Service workers are not supported by this browser");
changePushButtonState('incompatible');
return;
}
if (!('PushManager' in window)) {
console.warn('Push notifications are not supported by this
browser');
changePushButtonState('incompatible');
return;
}
if (!('showNotification' in ServiceWorkerRegistration.prototype))
{
console.warn('Notifications are not supported by this browser');
changePushButtonState('incompatible');
return;
}
if (Notification.permission === 'denied') {
console.warn('Notifications are denied by the user');
changePushButtonState('incompatible');
return;
}
navigator.serviceWorker.register("serviceWorker.js")
.then(() => {
console.log('[SW] Service worker has been registered');
push_updateSubscription();
}, e => {
console.error('[SW] Service worker registration failed', e);
changePushButtonState('incompatible');
});
function changePushButtonState (state) {
switch (state) {
case 'enabled':
pushButton.disabled = false;
pushButton.textContent = "Disable Push notifications";
isPushEnabled = true;
break;
case 'disabled':
pushButton.disabled = false;
pushButton.textContent = "Enable Push notifications";
isPushEnabled = false;
break;
case 'computing':
pushButton.disabled = true;
pushButton.textContent = "Loading...";
break;
case 'incompatible':
pushButton.disabled = true;
pushButton.textContent = "Push notifications are not
compatible with this browser";
break;
default:
console.error('Unhandled push button state', state);
break;
}
}
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function push_subscribe() {
changePushButtonState('computing');
navigator.serviceWorker.ready
.then(serviceWorkerRegistration =>
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:
urlBase64ToUint8Array(applicationServerKey),
}))
.then(subscription => {
// Subscription was successful
// create subscription on your server
return push_sendSubscriptionToServer(subscription, 'POST');
})
.then(subscription => subscription &&
changePushButtonState('enabled')) // update your UI
.catch(e => {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
console.warn('Notifications are denied by the user.');
changePushButtonState('incompatible');
} else {
console.error('Impossible to subscribe to push
notifications', e);
changePushButtonState('disabled');
}
});
}
function push_updateSubscription() {
navigator.serviceWorker.ready.then(serviceWorkerRegistration
=> serviceWorkerRegistration.pushManager.getSubscription())
.then(subscription => {
changePushButtonState('disabled');
if (!subscription) {
return;
}
return push_sendSubscriptionToServer(subscription, 'PUT');
})
.then(subscription => subscription &&
changePushButtonState('enabled'))
.catch(e => {
console.error('Error when updating the subscription', e);
});
}
function push_unsubscribe() {
changePushButtonState('computing');
navigator.serviceWorker.ready
.then(serviceWorkerRegistration =>
serviceWorkerRegistration.pushManager.getSubscription())
.then(subscription => {
if (!subscription) {
// No subscription object, so set the state
// to allow the user to subscribe to push
changePushButtonState('disabled');
return;
}
// We have a subscription, unsubscribe
// Remove push subscription from server
return push_sendSubscriptionToServer(subscription, 'DELETE');
})
.then(subscription => subscription.unsubscribe())
.then(() => changePushButtonState('disabled'))
.catch(e => {
console.error('Error when unsubscribing the user', e);
changePushButtonState('disabled');
});
}
function push_sendSubscriptionToServer(subscription, method) {
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
return fetch('push_subscription.php', {
method,
body: JSON.stringify({
endpoint: subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new
Uint8Array(key))) : null,
token: token ? btoa(String.fromCharCode.apply(null, new
Uint8Array(token))) : null
}),
}).then(() => subscription);
}
const sendPushButton = document.querySelector('#send-push-
button');
if (!sendPushButton) {
return;
}
sendPushButton.addEventListener('click', () =>
navigator.serviceWorker.ready
.then(serviceWorkerRegistration =>
serviceWorkerRegistration.pushManager.getSubscription())
.then(subscription => {
if (!subscription) {
alert('Please enable push notifications');
return;
}
var msg= document.getElementById("message").value;
// alert(msg);
const key = subscription.getKey('p256dh');
const token = subscription.getKey('auth');
fetch('send_push_notification.php', {
method: 'POST',
body: JSON.stringify({
endpoint:subscription.endpoint,
key: key ? btoa(String.fromCharCode.apply(null, new
Uint8Array(subscription.getKey('p256dh')))) : null,
token: token ? btoa(String.fromCharCode.apply(null,
new Uint8Array(subscription.getKey('auth')))) : null,
})
})
})
);
});
Where should I get textbox value and replace it with "hello" in send-push-notification.php?

WEBRTC remote video stops streaming after 2 seconds

I am facing a very weird behavior with this WEBRTC peer to peer app. the app would stream audio form one peer to the other, but when it comes to stream video, it actually stream video but just for the first 2 seconds, then it would stop streaming video, but the audio continues to stream. Here is some of the code that handles the remote video:
var webrtc_capable = true;
var rtc_peer_connection = null;
var rtc_session_description = null;
var get_user_media = null;
var connect_stream_to_src = null;
var stun_server = null;
if (navigator.getUserMedia) {
rtc_peer_connection = RTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.getUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.srcObject = window.URL.createObjectURL(media_stream);
media_element.play();
};
} else if (navigator.mozGetUserMedia) {
rtc_peer_connection = mozRTCPeerConnection;
rtc_session_description = mozRTCSessionDescription;
get_user_media = navigator.mozGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.srcObject = window.URL.createObjectURL(media_stream);
media_element.play();
};
stun_server = null;
} else if (navigator.webkitGetUserMedia) {
rtc_peer_connection = webkitRTCPeerConnection;
rtc_session_description = RTCSessionDescription;
get_user_media = navigator.webkitGetUserMedia.bind(navigator);
connect_stream_to_src = function(media_stream, media_element) {
media_element.src = webkitURL.createObjectURL(media_stream);
};
} else {
alert("This browser does not support WebRTC - visit WebRTC.org for more info");
webrtc_capable = false;
}
</script>
<script>
var call_token;
var signaling_server;
var peer_connection;
function start() {
// create the WebRTC peer connection object
peer_connection = new rtc_peer_connection({
"iceServers": [ // information about ice servers
{ "url": "stun:"+stun_server },
]
});
// generic handler that sends any ice candidates to the other peer
peer_connection.onicecandidate = function (ice_event) {
console.log(ice_event.candidate);
if (ice_event.candidate){
console.log("true");
}
if (ice_event.candidate) {
signaling_server.send(
JSON.stringify({
token:call_token,
type: "new_ice_candidate",
candidate: ice_event.candidate ,
})
);
}
};
peer_connection.onaddstream = function (event) {
var video = document.querySelector("#remote_video");
video.src = webkitURL.createObjectURL(event.stream);
document.getElementById("loading_state").style.display = "none";
document.getElementById("open_call_state").style.display = "block";
};
setup_video();
signaling_server = new WebSocket("ws://localhost:1234");
if (document.location.hash === "" || document.location.hash === undefined) {
var token = Date.now()+"-"+Math.round(Math.random()*10000);
call_token = "#"+token;
document.location.hash = token;
signaling_server.onopen = function() {
signaling_server.onmessage = caller_signal_handler;
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
}
document.title = "You are the Caller";
document.getElementById("loading_state").innerHTML = "Ready for a call...ask your friend to visit:<br/><br/>"+document.location;
} else { // you have a hash fragment so you must be the Callee
// get the unique token for this call from location.hash
call_token = document.location.hash;
signaling_server.onopen = function() {
// setup caller signal handler
signaling_server.onmessage = callee_signal_handler;
// tell the signaling server you have joined the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"join",
})
);
// let the caller know you have arrived so they can start the call
signaling_server.send(
JSON.stringify({
token:call_token,
type:"callee_arrived",
})
);
}
document.title = "You are the Callee";
document.getElementById("loading_state").innerHTML = "One moment please...connecting your call...";
}
// setup message bar handlers
document.getElementById("message_input").onkeydown = send_chat_message;
document.getElementById("message_input").onfocus = function() { this.value = ""; }
}
// handler to process new descriptions
function new_description_created(description) {
peer_connection.setLocalDescription(
description,
function () {
signaling_server.send(
JSON.stringify({
token:call_token,
type:"new_description",
sdp:description
})
);
},
log_error
);
}
// handle signals as a caller
function caller_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "callee_arrived") {
peer_connection.createOffer(
new_description_created,
log_error
);
} else if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(new RTCIceCandidate(signal.candidate));
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
if (peer_connection.remoteDescription.type == "answer") {
peer_connection.createOffer(new_description_created, log_error);
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
} else {
// extend with your own signal types here
}
}
// handle signals as a callee
function callee_signal_handler(event) {
var signal = JSON.parse(event.data);
if (signal.type === "new_ice_candidate") {
peer_connection.addIceCandidate(
new RTCIceCandidate(signal.candidate)
);
} else if (signal.type === "new_description") {
peer_connection.setRemoteDescription(
new rtc_session_description(signal.sdp),
function () {
if (peer_connection.remoteDescription.type == "offer") {
peer_connection.createAnswer(new_description_created, log_error);
}
},
log_error
);
} else if (signal.type === "new_chat_message") {
add_chat_message(signal);
} else {
// extend with your own signal types here
}
}
// add new chat message to messages list
function add_chat_message(signal) {
var messages = document.getElementById("messages");
var user = signal.user || "them";
messages.innerHTML = user+": "+signal.message+"<br/>\n"+messages.innerHTML;
}
// send new chat message to the other browser
function send_chat_message(e) {
if (e.keyCode == 13) {
var new_message = this.value;
this.value = "";
signaling_server.send(
JSON.stringify({
token:call_token,
type: "new_chat_message",
message: new_message
})
);
add_chat_message({ user: "you", message: new_message });
}
}
// setup stream from the local camera
function setup_video() {
get_user_media(
{
"audio": true, // request access to local microphone
"video": true // request access to local camera
},
function (local_stream) {
<video> MediaElement
connect_stream_to_src(local_stream, document.getElementById("local_video"));
peer_connection.addStream(local_stream);
},
log_error
);
}
function log_error(error) {
console.log(error);
}
</script>
Additional Info:
Windows 8 x64
opera version is 27.0.1689.76
Localvideo plays fine
This call is between two peers on the same network(no nat traversal)

Categories

Resources