Skip to content

Commit

Permalink
Merge pull request #7 from porjo/sse
Browse files Browse the repository at this point in the history
server-sent events
  • Loading branch information
porjo authored Jan 26, 2025
2 parents bccc2ef + 09f3299 commit deb5a47
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 293 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ module github.com/porjo/ytdl-web

go 1.23

require github.com/gorilla/websocket v1.5.3
require github.com/tmaxmax/go-sse v0.10.0
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/tmaxmax/go-sse v0.10.0 h1:j9F93WB4Hxt8wUf6oGffMm4dutALvUPoDDxfuDQOSqA=
github.com/tmaxmax/go-sse v0.10.0/go.mod h1:u/2kZQR1tyngo1lKaNCj1mJmhXGZWS1Zs5yiSOD+Eg8=
22 changes: 0 additions & 22 deletions html/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -221,28 +221,6 @@ label {
overflow: hidden;
}

#ws-status-light {
/* display: block; */
width: 8px;
height: 8px;
border-radius: 4px;
margin: 10px auto;
}

#ws-status-light.off {
background-color: rgb(226,0,0);
transform: scale(1);
}

#ws-status-light.on {
background-color: rgb(0, 183, 20);
animation-name: pulse;
animation-duration: 2s;
animation-fill-mode: both;
animation-iteration-count: infinite;
animation-timing-function: ease;
}

#recent {
display: none;
margin: 20px auto;
Expand Down
119 changes: 72 additions & 47 deletions html/app.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,65 @@

var player = null;

var loc = window.location, ws_uri;
if (loc.protocol === "https:") {
ws_uri = "wss:";
} else {
ws_uri = "ws:";
}
ws_uri += "//" + loc.host;
var path = loc.pathname.replace(/\/$/, '');
ws_uri += path + "/websocket";
var sseHost = window.location.protocol + "//" + window.location.host;

var player = null;
var progLast = null;
var seekTimer = null;

var trackId = null;

var lastPing = new Date();

async function postData (data) {
try {
const response = await fetch(sseHost + "/dl", {
method: "POST",
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
} catch (error) {
console.error(error.message);
}
}

$(function(){
var ws = new WebSocket(ws_uri);

const evtSource = new EventSource(sseHost + "/sse");

// fetch /recent will trigger event to send recent URLs
fetch(sseHost + "/recent");

// it's necessary to close the event source on page unload (e.g. page refresh)
// otherwise on next page load the sse conn clashes and we get an error
window.onbeforeunload = () => {
console.log("closing sse");
evtSource.close();
};

evtSource.onerror = (err) => {
console.error("EventSource failed:", err);
};

evtSource.addEventListener("ping", (event) => {
//console.log("ping");
lastPing = new Date();
});

setInterval(() => {
let diff = new Date() - lastPing;
if(diff > 30000) {
console.log("ping timeout, reloading page...")
location.reload();
}
},5000)

/*
// this doesn't fire until server sends first message
evtSource.onopen = (e) => {
console.log("The connection has been established.");
};
*/

const url = new URL(window.location);
const searchParams = new URLSearchParams(url.search);
Expand All @@ -33,20 +75,15 @@ $(function(){
window.history.pushState('newUrl', '', url);
});

$("#go-button").click(function() {
if (ws.readyState === 1) {
$("#spinner").show();
$("#progress-bar > span").css("width", "0%")
.text("0%");
let $url = $("#url");
let val = {URL: $url.val()};
ws.send(JSON.stringify(val));
$("#status").prepend("Requesting URL " + url + "\n");
$url.val('');
//$(this).prop('disabled', true);
} else {
$("#status").prepend("socket not ready\n")
}
$("#go-button").click(function () {
$("#spinner").show();
$("#progress-bar > span").css("width", "0%")
.text("0%");
let $url = $("#url");
postData({ url: $url.val() });
$("#status").prepend("Requesting URL " + url + "\n");
$url.val('');
//$(this).prop('disabled', true);
});

$("#searchbox span").click(function() {
Expand All @@ -62,7 +99,7 @@ $(function(){

if( urls.length > 0 ) {
let param = {delete_urls: urls};
ws.send(JSON.stringify(param));
postData(param);
}
});

Expand Down Expand Up @@ -113,8 +150,14 @@ $(function(){
return $job
}

ws.onmessage = function (e) {
let msg = JSON.parse(e.data);
evtSource.onmessage = function (e) {
let messages = e.data.split(/\r?\n/);
messages.forEach(msgHandler)
}

function msgHandler(json) {
//console.log("msgHandler", json);
let msg = JSON.parse(json);
if( 'Key' in msg ) {
switch (msg.Key) {
case 'error':
Expand Down Expand Up @@ -276,24 +319,6 @@ $(function(){
$("body").css("padding-bottom", $(".shk-player").css("height"));
}

ws.onerror = function(e) {
console.log("Connection error", e)
};

ws.onclose = function() {
$("#status").prepend("Connection closed\n");
console.log("Connection closed");
$("#ws-status-light").toggleClass("on off");
$("#controls").hide();
};

ws.onopen = function(e) {
$("#status").prepend("Connection opened\n");
console.log("Connection opened");
$("#ws-status-light").toggleClass("off on");
$("#controls").show();
}

$('#output').on('click','.status', function() {
$(this).toggleClass("expand");
});
Expand Down
1 change: 0 additions & 1 deletion html/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

<div id='output'></div>
<div id='playa'></div>
<div id='ws-status-light' class='off'></div>
<div id='recent'>
<div id="recent_header">
<div class="heading">Recent Downloads</div>
Expand Down
Loading

0 comments on commit deb5a47

Please sign in to comment.