feat(player): view counter

This commit is contained in:
2022-01-30 19:04:41 +08:00
parent 812b5772a4
commit 126fe54063
5 changed files with 97 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
module git.kitsu.red/restream-tools/player
go 1.17
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"flag"
"fmt"
"net/http"
"time"
)
func main() {
var addr = flag.String("addr", ":8080", "http service address")
flag.Parse()
// Map of active viewers and their last active time
var viewers = make(map[string]int64)
http.HandleFunc("/viewcount", func(w http.ResponseWriter, r *http.Request) {
// Get the current time
var now = time.Now().Unix()
// Get the remote address
var ip = r.RemoteAddr
// Update the last active time
viewers[ip] = now
// Respond with the number of viewers
fmt.Fprintf(w, "%d", len(viewers))
})
// Periodically remove inactive viewers
go func() {
for {
time.Sleep(time.Second)
// Get the current time
var now = time.Now().Unix()
// Remove any viewers that have not been active in the last 10 seconds
for ip, lastActive := range viewers {
if now-lastActive > 10 {
delete(viewers, ip)
}
}
}
}()
// Handle static files
http.Handle("/", http.FileServer(http.Dir("./static")))
// Start the server
fmt.Println("Starting server on", *addr)
err := http.ListenAndServe(*addr, nil)
if err != nil {
fmt.Println(err)
}
}
@@ -15,6 +15,10 @@
region: 'us-east',
url: 'https://us.stream.holopirates.moe',
},
{
region: 'us-east-2',
url: 'https://www.kitsu.red',
},
{
region: 'sg',
url: 'https://restream.kitsune.box.ca',
@@ -39,6 +43,7 @@
<select id="mirror-select">
<option value="">Loading mirrors...</option>
</select>
<a id="mirror-link" href="#"></a>
<div id="viewer-count">
<span id="viewer-count-value">0</span> viewers
</div>
@@ -42,6 +42,17 @@ strong {
font-weight: bold;
}
a,
a:link,
a:visited {
color: #5bd9ff;
text-decoration: none;
}
a:hover,
a:active {
text-decoration: underline;
}
#viewer-count {
flex: 1;
text-align: right;
@@ -68,6 +68,7 @@
const reloadVideo = () => {
const video = document.getElementById('video');
const mirrorSelect = document.getElementById('mirror-select');
const mirrorLink = document.getElementById('mirror-link');
const playlistURL = mirrorSelect.value + window.restream_config.playlist;
console.log('Reloading video from', playlistURL);
@@ -79,12 +80,32 @@
} else {
video.src = playlistURL;
}
mirrorLink.href = playlistURL;
mirrorLink.innerText = '[m3u8]';
};
const viewCountLoop = async () => {
const viewCount = document.getElementById('viewer-count-value');
const url = '/viewcount';
while (true) {
const response = await fetchWithTimeout(url, {
timeout: 1000,
mode: 'cors',
});
viewCount.innerText = await response.text();
await sleep(5000);
}
};
const init = async () => {
const video = document.getElementById('video');
const mirrorSelect = document.getElementById('mirror-select');
// Init viewer counter
viewCountLoop();
// Set up hls.js
if (Hls.isSupported()) {
window.restream_config.hls = new Hls();