Skip to content

Commit

Permalink
DIOS-3740 Fix sse events retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
rreynaud committed Jan 24, 2024
1 parent 23204fc commit 7a58232
Showing 1 changed file with 50 additions and 50 deletions.
100 changes: 50 additions & 50 deletions whep.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const Extensions = {
}


export class WHEPClient extends EventTarget
export class WHEPClient extends EventTarget
{
constructor()
constructor()
{
super();
//Ice properties
Expand All @@ -19,7 +19,7 @@ export class WHEPClient extends EventTarget
this.endOfcandidates = false;
}

async view(pc, url, token)
async view(pc, url, token)
{
//If already publishing
if (this.pc)
Expand All @@ -30,9 +30,9 @@ export class WHEPClient extends EventTarget
this.pc = pc;

//Listen for state change events
pc.onconnectionstatechange = (event) =>
pc.onconnectionstatechange = (event) =>
{
switch (pc.connectionState)
switch (pc.connectionState)
{
case "connected":
// The connection has become fully connected
Expand All @@ -48,18 +48,18 @@ export class WHEPClient extends EventTarget
}

//Listen for candidates
pc.onicecandidate = (event) =>
pc.onicecandidate = (event) =>
{

if (event.candidate)
if (event.candidate)
{
//Ignore candidates not from the first m line
if (event.candidate.sdpMLineIndex > 0)
//Skip
return;
//Store candidate
this.candidates.push(event.candidate);
} else
} else
{
//No more candidates
this.endOfcandidates = true;
Expand Down Expand Up @@ -105,17 +105,17 @@ export class WHEPClient extends EventTarget
const linkHeaders = fetched.headers.get("link").split(/,\s+(?=<)/)

//For each one
for (const header of linkHeaders)
for (const header of linkHeaders)
{
try
try
{
let rel, params = {};
//Split in parts
const items = header.split(";");
//Create url server
const url = items[0].trim().replace(/<(.*)>/, "$1").trim();
//For each other item
for (let i = 1; i < items.length; ++i)
for (let i = 1; i < items.length; ++i)
{
//Split into key/val
const subitems = items[i].split(/=(.*)/);
Expand Down Expand Up @@ -160,8 +160,8 @@ export class WHEPClient extends EventTarget
if (this.eventsUrl)
{
//Get supported events
const events = links[Extensions.Core.ServerSentEvents]["events"]
? links[Extensions.Core.ServerSentEvents]["events"].split(" ")
const events = links[Extensions.Core.ServerSentEvents][0].params.events
? links[Extensions.Core.ServerSentEvents][0].params.events.split(",")
: ["active","inactive","layers","viewercount"];
//Request headers
const headers = {
Expand All @@ -177,44 +177,44 @@ export class WHEPClient extends EventTarget
method: "POST",
body: JSON.stringify(events),
headers
}).then((fetched)=>{
//If the event channel could be created
if (!fetched.ok)
return;
}).then((fetched)=>{
//If the event channel could be created
if (!fetched.ok)
return;
//Get the resource url
const sseUrl = new URL(fetched.headers.get("location"), this.eventsUrl);
//Open it
this.eventSource = new EventSource(sseUrl);
this.eventSource.onopen = (event) => console.log(event);
this.eventSource.onerror = (event) => console.log(event);
//Listen for events
this.eventSource.onmessage = (event) => {
console.dir(event);
this.dispatchEvent(event);
};
});
const sseUrl = new URL(fetched.headers.get("location"), this.eventsUrl);
//Open it
this.eventSource = new EventSource(sseUrl);
this.eventSource.onopen = (event) => console.log(event);
this.eventSource.onerror = (event) => console.log(event);
//Listen for events
this.eventSource.onmessage = (event) => {
console.dir(event);
this.dispatchEvent(event);
};
});
}

//Get current config
const config = pc.getConfiguration();

//If it has ice server info and it is not overriden by the client
if ((!config.iceServer || !config.iceServer.length) && links.hasOwnProperty("ice-server"))
if ((!config.iceServer || !config.iceServer.length) && links.hasOwnProperty("ice-server"))
{
//ICe server config
config.iceServers = [];

//For each one
for (const server of links["ice-server"])
for (const server of links["ice-server"])
{
try
try
{
//Create ice server
const iceServer = {
urls : server.url
//Create ice server
const iceServer = {
urls : server.url
}
//For each other param
for (const [key,value] of Object.entries(server.params))
for (const [key,value] of Object.entries(server.params))
{
//Get key in cammel case
const cammelCase = key.replace(/([-_][a-z])/ig, $1 => $1.toUpperCase().replace('-', '').replace('_', ''))
Expand Down Expand Up @@ -260,7 +260,7 @@ export class WHEPClient extends EventTarget
await pc.setRemoteDescription({ type: "answer", sdp: answer });
}

restart()
restart()
{
//Set restart flag
this.restartIce = true;
Expand All @@ -270,7 +270,7 @@ export class WHEPClient extends EventTarget
this.iceTrickeTimeout = setTimeout(() => this.trickle(), 0);
}

async trickle()
async trickle()
{
//Clear timeout
this.iceTrickeTimeout = null;
Expand All @@ -291,7 +291,7 @@ export class WHEPClient extends EventTarget
this.restartIce = false;

//If we need to restart
if (restartIce)
if (restartIce)
{
//Restart ice
this.pc.restartIce();
Expand Down Expand Up @@ -322,7 +322,7 @@ export class WHEPClient extends EventTarget
candidates: [],
};
//For each candidate
for (const candidate of candidates)
for (const candidate of candidates)
{
//Get mid for candidate
const mid = candidate.sdpMid
Expand All @@ -342,7 +342,7 @@ export class WHEPClient extends EventTarget
media.candidates.push(candidate);
}
//For each media
for (const media of Object.values(medias))
for (const media of Object.values(medias))
{
//Add media to fragment
fragment +=
Expand Down Expand Up @@ -374,7 +374,7 @@ export class WHEPClient extends EventTarget
throw new Error("Request rejected with status " + fetched.status)

//If we have got an answer
if (fetched.status == 200)
if (fetched.status == 200)
{
//Get the SDP answer
const answer = await fetched.text();
Expand Down Expand Up @@ -425,39 +425,39 @@ export class WHEPClient extends EventTarget

//If token is set
if (this.token)
headers["Authorization"] = "Bearer " + this.token;

headers["Authorization"] = "Bearer " + this.token;

//Do the post request to the whep resource
const fetched = await fetch(this.layerUrl, {
method: "POST",
body: JSON.stringify(layer),
headers
});
});
}

async unselectLayer()
{
if (!this.layerUrl)
throw new Error("whep resource does not support layer selection");



//Request headers
const headers = {};

//If token is set
if (this.token)
headers["Authorization"] = "Bearer " + this.token;

headers["Authorization"] = "Bearer " + this.token;

//Do the post request to the whep resource
const fetched = await fetch(this.layerUrl, {
method: "DELETE",
headers
});
});
}

async stop()
async stop()
{
if (!this.pc)
if (!this.pc)
{
// Already stopped
return
Expand Down

0 comments on commit 7a58232

Please sign in to comment.