How to update webrtc xirsys from v2 to v3? - webrtc

I am currently testing and working on the webrtc firebase demo by Muaz khan. In one of the files it uses Xirsys and the credentials used are the ones of Muaz Khan. The xirsys details are of version v2. Currently Xirsys uses version V3. I was wondering how to change the former code to the new code.
The former code which is working in the demo is
<script type="text/javascript" src="https://gc.kis.v2.scr.kaspersky-
labs.com/EC7AD6FB-B1E9-9D47-B085-7DB58B77DF98/main.js" charset="UTF-8">
</script><script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'https://service.xirsys.com/ice';
var xhr = createCORSRequest('POST', url);
xhr.onload = function () {
window.parent.postMessage({
iceServers: JSON.parse(xhr.responseText).d.iceServers
}, '*');
};
xhr.onerror = function () {
console.error('Woops, there was an error making xhr request.');
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.addEventListener('message', function (event) {
if (!event.data || typeof event.data !== 'string') return;
if(event.data == 'get-ice-servers') {
xhr.send('ident=muazkh&secret=59d93f26-5b89-11e5-babe-
d61aeb366a63&domain=webrtcexperiment-webrtc.netdna-
ssl.com&application=default&room=default&secure=1');
}
});
</script>
According to the new Xirsys documentation it should be like
<!-- JS Get ICE STUN and TURN list -->
<DOCTYPE>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js">
</script>
<script>
$( document ).ready( function () {
$.ajax ({
url: "https://global.xirsys.net/_turn/muazkh/",
type: "PUT",
async: false,
headers: {
"Authorization": "Basic " + btoa("muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63")
},
success: function (res){
console.log("ICE List: "+res.v.iceServers);
}
});
})
</script>
</head>
<body>
</body>
</html>
What I did was this but did not work
<head><script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'https://global.xirsys.net/_turn/muazkh/default/default';
var xhr = createCORSRequest('PUT', url);
xhr.onload = function () {
window.parent.postMessage({
iceServers: JSON.parse(xhr.responseText).v.iceServers
}, '*');
};
xhr.onerror = function () {
console.error('Woops, there was an error making xhr request.');
};
xhr.setRequestHeader("Authorization", "muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63");
window.addEventListener('message', function (event) {
if (!event.data || typeof event.data !== 'string') return;
if(event.data == 'get-ice-servers') {
xhr.send();
}
});
</script>
</head>
Will greatly appreciate any help here. Thanks

Looks like a headers issue. The authorization header should use the "Basic" authentication scheme.
Please change your XMLHttpRequest's "setRequestHeader" to:
xhr.setRequestHeader("Authorization", "Basic "+ btoa("muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63") );

Related

Square Payment SDK not taking amount from form

I have setup the Square SDK but I am having issue now, It is not taking the custom Input field value in processor file.
Here are my Codes,
<!DOCTYPE html>
<html>
<head>
<link href="css/app.css" rel="stylesheet" />
<script
type="text/javascript"
src="https://sandbox.web.squarecdn.com/v1/square.js"
></script>
<script>
const appId = 'sandbox-XXXXX-XXXXXXXXX';
const locationId = 'XXXXXXXXXXXXXX';
async function initializeCard(payments) {
const card = await payments.card();
await card.attach('#card-container');
return card;
}
async function createPayment(token) {
const body = JSON.stringify({
locationId,
sourceId: token,
});
const paymentResponse = await fetch('payment-process.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body,
});
if (paymentResponse.ok) {
return paymentResponse.json();
}
const errorBody = await paymentResponse.text();
throw new Error(errorBody);
}
async function tokenize(paymentMethod) {
const tokenResult = await paymentMethod.tokenize();
if (tokenResult.status === 'OK') {
return tokenResult.token;
} else {
let errorMessage = `Tokenization failed with status: ${tokenResult.status}`;
if (tokenResult.errors) {
errorMessage += ` and errors: ${JSON.stringify(
tokenResult.errors
)}`;
}
throw new Error(errorMessage);
}
}
// status is either SUCCESS or FAILURE;
function displayPaymentResults(status) {
const statusContainer = document.getElementById(
'payment-status-container'
);
if (status === 'SUCCESS') {
statusContainer.classList.remove('is-failure');
statusContainer.classList.add('is-success');
} else {
statusContainer.classList.remove('is-success');
statusContainer.classList.add('is-failure');
}
statusContainer.style.visibility = 'visible';
}
document.addEventListener('DOMContentLoaded', async function () {
if (!window.Square) {
throw new Error('Square.js failed to load properly');
}
let payments;
try {
payments = window.Square.payments(appId, locationId);
} catch {
const statusContainer = document.getElementById(
'payment-status-container'
);
statusContainer.className = 'missing-credentials';
statusContainer.style.visibility = 'visible';
return;
}
let card;
try {
card = await initializeCard(payments);
} catch (e) {
console.error('Initializing Card failed', e);
return;
}
// Checkpoint 2.
async function handlePaymentMethodSubmission(event, paymentMethod) {
event.preventDefault();
try {
// disable the submit button as we await tokenization and make a payment request.
cardButton.disabled = true;
const token = await tokenize(paymentMethod);
const paymentResults = await createPayment(token);
displayPaymentResults('SUCCESS');
console.debug('Payment Success', paymentResults);
} catch (e) {
cardButton.disabled = false;
displayPaymentResults('FAILURE');
console.error(e.message);
}
}
const cardButton = document.getElementById('card-button');
cardButton.addEventListener('click', async function (event) {
await handlePaymentMethodSubmission(event, card);
});
});
</script>
</head>
<body>
<form id="payment-form">
<div id="card-container"></div>
<input type="hidden" name="amount" value="500">
<button id="card-button" type="button">Pay $1.00</button>
</form>
<div id="payment-status-container"></div>
</body>
</html>
And The Next Processing file is payment-process.php
<?php
require 'vendor/autoload.php';
use Square\SquareClient;
use Square\Environment;
use Square\Exceptions\ApiException;
use Square\Models\Money;
use Square\Models\CreatePaymentRequest;
use Square\Models\createPayment;
$client = new SquareClient([
'accessToken' => 'EAAAEKE_XXXXXXXXXXXXXXXXXXXXXXXXvs3LXwg0A8TTX2dN5cR5u',
'environment' => Environment::SANDBOX,
]);
$payments_api = $client->getPaymentsApi();
$data = json_decode(file_get_contents('php://input'), true);
$amount = $_POST['amount'];
$amount = $amount * 100;
$money = new Money();
$money->setAmount($amount);
$money->setCurrency('AUD');
$Current_User = 78;
$TransactionID = 'BZ_'.$Current_User.'-'.rand(0000,9999);
$create_payment_request = new CreatePaymentRequest($data['sourceId'], $TransactionID, $money);
$create_payment_request->setNote('Description of Amount');
$response = $payments_api->createPayment($create_payment_request);
if ($response->isSuccess()) {
echo json_encode($response->getResult());
} else {
echo json_encode($response->getErrors());
}
?>
I have tried it with $data['input'] as well as $_POST['amount']
But it always give error of INVALID_AMOUNT_MONEY But If I put the same amount directly in variable $amount = 500; It works perfect.
It is not taking value from the Payment form.

Is there a way to fix Cannot read property 'post' of undefined?

I'm running a page in vue with a form, it submits and returns data to and from an API, I'm getting a 'post' of undefined error in the console and I can't seem to figure out what's going on.
<script>
methods: {
StartClient: function () { // Initiate XMLHttpRequest as aHttpRequest for GET
this.get = function(Url, Callback){
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow GET
aHttpRequest.open("GET", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(null);
}
this.post = function(Url, message, Callback) { // initiate XMLHttpRequest as aHttpRequest for POST
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow POST
aHttpRequest.open("POST", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(message);
}
},
submitData: function () { // Start a traceroute, followed by the 'Begin' button
document.getElementById('inputBox').disabled = true;
var targetInputButton = document.getElementById("inputBox").value;
var message = '{"targetInputButton":"' + targetInputButton + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/start-trace', message, function(response) {
document.getElementById('jobId').innerHTML = response;
});
},
sendBackData: function () { // Receive traceroute data, followed by the 'Generate data' button
var jobId = document.getElementById("jobId").innerHTML;
var message = '{"jobId":"' + jobId + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/check-trace', message, function(response) {
document.getElementById('report').innerHTML = response;
});
}
}
}
</script>

serverconnection.onmessage=gotMessageFromServer never called after createOffer

I'm trying to connect to a browser for video chat using WebRTC and websockets.
I'm able to createoffer, get the ice candidates but the function (where I expect a remote stream response) serverconnection.onmessage is never called.
in my index.html
function pageReady() {
localVideo = document.getElementById("localVideo");
remoteVideo = document.getElementById("remoteVideo");
serverConnection = new WebSocket('ws://localhost:3434');
serverConnection.onmessage = gotMessageFromServer;
var constraints = {
video: true,
audio: true,
};
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints, getUserMediaSuccess, getUserMediaError);
} else {
alert('Your browser does not support getUserMedia API');
}
}
function start(isCaller) {
peerConnection = new RTCPeerConnection(peerConnectionConfig, optional);
console.log('the peer connection is', peerConnection);
peerConnection.onicecandidate = gotIceCandidate;
peerConnection.onaddstream = gotRemoteStream;
peerConnection.addStream(localStream);
if (isCaller)
peerConnection.createOffer(gotDescription, createOfferError);
}
function gotMessageFromServer(message) {
console.log('message is', json);
if (!peerConnection) start(false);
var signal = JSON.parse(message.data);
if (signal.sdp) {
console.log('message is signal.sdp', signal.sdp);
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp), function () {
peerConnection.createAnswer(gotDescription, createAnswerError);
});
} else if (signal.ice) {
console.log('message is signal.ice', signal.ice);
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice));
}
}
server.js
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ noServer: true });
var http = require('http'),
fs = require('fs');
fs.readFile('../index.html', function (err, html) {
if (err) {
throw err;
}
var server = http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
})
server.listen(3434);
server.on('upgrade', function (req, socket, head) {
wss.handleUpgrade(req, socket, head, function (client) {
});
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send(message);
});
});

Loading local JSON file with Safari Extension

Trying to load JSON file with Safari Extension.
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI +'js/data.json', true);
It gives an error "Cross origin requests are only supported for HTTP."
For example it is possible with Chrome Extenison
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.extension.getURL('/js/data.json'), true);
There you need to specify it in manifest
"web_accessible_resources": ["/js/data.json"]
Is there a similar way in Safari?
EDIT
Found a solution
It is possible through Global page
global.html
function handleMessage(event) {
if (event.name === "requestParagraphs") {
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI + 'js/data.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var articlesJSON = JSON.parse(xhr.responseText);
event.target.page.dispatchMessage('paragraphs', articlesJSON);
}
};
xhr.send();
}
}
safari.application.addEventListener("message", handleMessage, false);
injected.js
function handleMessage(msgEvent) {
var messageName = msgEvent.name;
var messageData = msgEvent.message;
if (messageName === "paragraphs") {
// ...
}
}
safari.self.addEventListener("message", handleMessage, false); // Listen response
safari.self.tab.dispatchMessage('requestParagraphs'); // Call global page

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.