webRTC ondatachannel() and onopen() eventlisteners not firing - django

I am creating a webRTC connection to transmit data between 2 peers. Currently, I am stuck in the stage of getting the channel.readyState to get into "open" state. Can someone help me understand why the "ondatachannel()" in code block 2 and the "onopen()" in codeblock 1 eventlisteners do not fire? It works when I manually enter all the code in my dev tool consoles. I am using django backend with django channels for sdp exchange.
Instantiating RTCPeerConnection and sending localdescription to my back end.
function hostroom(){
lc = new RTCPeerConnection()
dc = lc.createDataChannel("channel")
dc.onmessage = e =>("Just got a message " + e.data);
dc.onopen = e => console.log("Connection opened!")
lc.onicecandidate = function(e){
console.log("icecandidate created");
}
lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("set successfully!")).then(
function (){
var ice = JSON.stringify(lc.localDescription);
console.log(ice);
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var p={{p.id}}
$.ajax({
type: 'POST',
url: '{% url 'createroom' %}',
data:{
"ice": ice,
"csrfmiddlewaretoken": csrftoken,
"p": p,
},
success: function (data) {
alert(data["response"])
}
});
}
)
Output on dev tool console:
Code on the remote peer's side. Runs on page load and will send the local description via the back end and then via django channels to the host.
const rc = new RTCPeerConnection();
rc.onicecandidate = function(e){
console.log("New Ice Candidate reprinting SDP " + JSON.stringify(rc.localDescription));
}
rc.ondatachannel = e => {
rc.dc = e.channel;
rc.dc.onmessage = e => console.log("new message from client! " + e.data);
rc.dc.onopen = e => console.log("Connection opened!");
};
var offer = {{icecandidate|safe}}
rc.setRemoteDescription(offer).then(a => console.log("offer set!"));
rc.createAnswer().then(a => rc.setLocalDescription(a)).then(a => console.log("local d set!")).then(
function(){
var answer = JSON.stringify(rc.localDescription)
console.log(answer)
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var user = document.getElementById("account").text.split(":")[1];
var room_name="{{room_name}}"
console.log(room_name);
$.post("{% url 'connecttoleader' %}", {
"answer": answer,
"csrfmiddlewaretoken": csrftoken,
"user": user,
"room_name": room_name,
});
}
);
Output on dev tool console:
back to the host's side. Code fires upon triggering djangochannelsocket.onmessage() on the same browser tab as code block 1(first code block above).
...
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
console.log(JSON.parse(sdp))
lc.setRemoteDescription(JSON.parse(sdp))
console.log("set")
channel = "dc"
$.ajax({
type: 'POST',
url: '{% url 'connectpeer' %}',
data:{
"channel": channel,
"csrfmiddlewaretoken": csrftoken,
"user": user,
},
success: function (data) {
alert(data["response"])
}
});
...
Output on dev tool console:(as you can see the "connection opened!" string from the onopen() eventlistener does not print and dc.readyState command in the browser dev tools console only shows "connecting")

You are not exchanging ice candidates, merely printing the updated SDP.
Without exchanging ice candidates, the connection won't get established and the datachannel won't open.

Related

I display a table with ajax in real time and I check some lines which I return in my views

I have this problem in summary:
when i fill my input automatically i display an array using ajax ,
and on the same table I shock a few lines and when I send back to my views through a button I have nothing that is displayed either at the console or the terminal.
Js & Ajax
enter code here
$(document).on("click","#final",function(){
const list_entrepot = getSelectedVals1();
const list_fournisseurs = getSelectedVals();
selection = {list_fournisseurs,list_entrepot};
$.ajax({
async: false,
type : "GET",
url : 'fournisseur_ajax',
data :{
'csrfmiddlewaretoken': csrf,
'selection':selection,
},
success : (res) =>{
console.log(res.data)
}
});
});
function getSelectedVals(){
var tmp =[];
$("input[name='fournisseur_tab']").each(function() {
if ($(this).prop('checked'))
{
checked = ($(this).val());
tmp.push(checked);
}
});
var filters = tmp.join(',');
console.log(filters)
return filters;
}

Getting a 401 (Unauthorized) on Heroku, No error on local host Mern stack being used

I have been having trouble with a MERN stack deployment, I get a 401 error on heroku, wheni try to login or use any APi call.
I am using express-sessions andi have noticed using console.log that the session on login page shows that the user have logged in but as soon as i am redirected to Dashboard, the session changes
NOte: Using AXios
Note: everything is working perfectly fine on Localhost, only facing this issue on developemnt.. and on Heroku (free v)
Code on Server.js
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
const bodyParser = require('body-parser');
var mongoUtil = require( './utils/mongoUtil' );
const cors = require('cors');
app.use(cors({credentials: true, origin: 'https://teamdashboard0.herokuapp.com'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var store = new MongoDBStore(
{
uri: "mongodb+srv://teamdashboard:ONgnWv4aqRwBKo8g#teamdashboard.3ivb8.mongodb.net/TeamDashboard",
databaseName: 'TeamDashboard',
collection: 'sessions'
});
store.on('error', function(error) {
console.log(error);
});
app.use(session({
secret: 'bakdhgsjcdbcbsdm',
resave: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
secure: true
},
store: store,
unset: 'destroy',
saveUninitialized: false
}));
mongoUtil.connectToServer( function( err, client ) {
var user = require( './controllers/user.js' );
var colleague = require( './controllers/colleague.js' );
var team = require( './controllers/team.js' );
var news = require( './controllers/news.js' );
app.post('/register', (req, res)=>{user.register(req,res)});
app.get('/verify',(req,res)=>{user.verify(req,res)});
app.get('/login',(req,res)=>{user.login(req,res)});
app.post('/changePasswordEmail',(req,res)=>{user.sendChangePassword(req,res)});
app.put('/changePassword',(req,res)=>{user.changePassword(req,res)});
app.post('/logout', (req,res)=>{user.logout(req,res)});
app.get('/colleague/checkLimit', (req,res)=>{colleague.checkLimit(req,res)});
app.post('/colleague/add', (req,res)=>{colleague.add(req,res)});
app.delete('/colleague/delete', (req,res)=>{colleague.delete(req,res)});
app.put('/colleague/update', (req,res)=>{colleague.update(req,res)});
app.get('/colleague/all', (req,res)=>{colleague.getAll(req,res)});
app.get('/colleague/one', (req,res)=>{colleague.getOne(req,res)});
app.get('/team/all', (req,res)=>{team.allTeams(req,res)});
app.post('/team/add', (req,res)=>{team.newTeam(req,res)});
app.delete('/team/delete', (req,res)=>{team.deleteTeam(req,res)});
app.put('/team/update', (req,res)=>{team.updateTeam(req,res)});
app.get('/team/colleague/all', (req,res)=>{team.getColleagues(req,res)});
app.post('/team/colleague/add', (req,res)=>{team.addColleague(req,res)});
app.delete('/team/colleague/delete', (req,res)=>{team.deleteColleague(req,res)});
app.get('/news',(req,res)=>{news.getNews(req,res)});
app.get('/', function(req, res) {
var msg = `
Welcome to the Team Dashboard\n
Visit:
https://app.swaggerhub.com/apis-docs/Hira172/TeamDashboard/1.0.0
to view all the api and details about the backend
`
res.send(msg)
});
if (err) console.log(err);
port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Server Running at port ${port}`));
} );```

Calling a Serenity service endpoint and react to success or failure on client-side

Until recently (one of the last full .net SF versions), I could call a Serenity service endpoint like below and react on success or failure. With current .net core (3.14.3) SF, somehow this seems not anymore to work.
I just get a dialog with the message content. I neither get "success" nor "error" alert box.
Question: How to do this with current SF 3.14.3.
Here my code from a project on full .net where this still works:
let bla1 = CountriesService.ImportCountriesFromRESTCountries(
{
},
response => {
alert('success');
let message = JSON.parse(bla1.responseText);
Q.notifySuccess(message, Q.text("Dialogs.Button.UpdateCountries.Import.Toast.Title"), options);
this.refresh();
},
{
blockUI: true,
onError: response => {
alert('error');
let errorcontent = JSON.parse(bla1.responseText);
let message = errorcontent["Error"]["Message"]
Q.alert(message);
this.refresh();
}
});
face same issue , i resolved this by
Q.serviceCall<Serenity.RetrieveResponse<any>>({
service: this.serviceUrl + '/Retrieve',
request: {
EntityId: this.value
} as Serenity.RetrieveRequest,
async: false,
onSuccess: (response) => {
this._selectedItem = response.Entity;
},
onError: (error) => {
console.log( error.Error);
}
});

Google Storage + JQuery-File-Upload + Django + Signed URL, how should I change submit() and relevant options?

I have the following js code and it uses the signed-url api to get signed urls for uploading content to google storage via Django api.
When I use it with the following code :
xhr.open("PUT", data.signed_url);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
It works fine and I am able to upload to Google Storage very large files. But obviously, when I do that, I cannot use any progress-bar features of jquery-file-upload.
Can you please suggest on how I should alter the data.submit(), where shall I put it, and how should I change the options or settings prior to submitting. Should I be overriding add or submit callback ?
I feel that there is a missing support for Google Storage with Jquery-file-upload as the only example covers only obsolute Google Blobstore in the following link : https://github.com/blueimp/jQuery-File-Upload/wiki/Google-App-Engine
$("#fileupload").fileupload({
dataType: 'json',
type: 'PUT',
sequentialUploads: true,
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
primary_data: data,
data: formData
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
console.log("With credentials");
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
console.log("With domainrequest");
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
console.log("With null");
xhr = null;
}
//What shall I do to make the following work for uploading GS
this.primary_data.url = data.signed_url;
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.submit();
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
} else {
alert("Failed to upload 1: " + status);
}
};
xhr.onerror = () => {
alert("Failed to upload 2");
};
//When the code below uncommented, it uploads to GS succesfully.
//xhr.setRequestHeader('Content-Type', file.type);
//xhr.send(file);
});
});
},
Also this is my cors setup for the GS Bucket.
[
{
"origin": ["*"],
"responseHeader": ["Content-Type", "Access-Control-Allow-Origin"],
"method": ["GET", "PUT", "OPTIONS"],
"maxAgeSeconds": 60
}
]

getJSON callback not called when requesting a Facebook user

I am successfully authenticating a user to Facebook through my Spotify app, but then I try to request the user information and my .getJSON callback is never called. Here's my code :
auth.authenticateWithFacebook(facebookAppId, facebookPermissions, {
onSuccess: function(accessToken, ttl) {
var request_url = 'https://graph.facebook.com/me';
var url = request_url + '?access_token=' + accessToken;
$.getJSON(url, function(data) {
alert("Working");
});
},
onFailure: function(error) {
console.log("Authentication failed with error: " + error);
},
onComplete: function() { }
});
I tried with $.ajax, adding &callback=?, &callback=myFunction but nothing ever worked... Anyone have an idea of the issue?
Thanks
Make sure you add graph.facebook.com to the RequiredPermissions key in your manifest.json file.