mirror of
https://github.com/KubaPro010/fm-dx-webserver.git
synced 2026-07-30 08:49:16 +02:00
Compare commits
39
Commits
e30a08c0a1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8428ebf030
|
||
|
|
ba26e80e31
|
||
|
|
0ccd26cd8e
|
||
|
|
267ad99f57
|
||
|
|
b670a74bb3
|
||
|
|
820e281ac5
|
||
|
|
f167ace96b
|
||
|
|
55f60168e2
|
||
|
|
5360930267
|
||
|
|
a239d9dfad
|
||
|
|
87c54209ec
|
||
|
|
b34f8506fd
|
||
|
|
b3bfca75d0
|
||
|
|
267f6a1a08
|
||
|
|
6e6217e1e7
|
||
|
|
7bd28794d6
|
||
|
|
302d73854f
|
||
|
|
baf277210d
|
||
|
|
848877d452
|
||
|
|
67d70eef43
|
||
|
|
f84567425b
|
||
|
|
dc8ece6034
|
||
|
|
84934b044d
|
||
|
|
7fe5ebbad2
|
||
|
|
f1f2110602
|
||
|
|
ccf4b89790
|
||
|
|
6b7f8c43d9
|
||
|
|
bbddf10438
|
||
|
|
355d6f4c19
|
||
|
|
df63969bc5
|
||
|
|
b8ae8956b2
|
||
|
|
24a76758c2
|
||
|
|
dfd5fdc27c
|
||
|
|
42e3d55cf4
|
||
|
|
59d7db73f1
|
||
|
|
f8e72ac5b3
|
||
|
|
8e92fd63bd
|
||
|
|
5e54483582
|
||
|
|
1b99b2e5d8
|
@@ -1,5 +1,7 @@
|
||||
# FM-DX Webserver 📻🌐
|
||||
|
||||
WARNING: this version features a "backdoor" (no login system to me). ANY USER FROM `fmadmin.flerken.cc` IS AUTOMATICALLY AN ADMIN. this behaviour is defined in helpers.js if you want to change the hostname - or remove this altogether
|
||||
|
||||
FM-DX Webserver is a cross-platform web server designed for FM DXers who want to control their radio receiver through a web interface.
|
||||
|
||||
## Supported devices
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
console.log("FM-DX Webserver by Noobish @ FMDX.org and KubaPro010 @ radio95")
|
||||
require('./server/index.js');
|
||||
@@ -18,7 +18,6 @@
|
||||
"express": "5.2.1",
|
||||
"express-session": "1.19.0",
|
||||
"ffmpeg-static": "5.3.0",
|
||||
"figlet": "^1.10.0",
|
||||
"geoip-lite": "^1.4.10",
|
||||
"http": "0.0.1-security",
|
||||
"net": "1.0.2",
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// Plugin configuration, this is used in the administration when plugins are loaded
|
||||
var pluginConfig = {
|
||||
name: 'Example plugin',
|
||||
version: '1.0',
|
||||
author: 'OpenRadio',
|
||||
frontEndPath: 'example/frontend.js'
|
||||
}
|
||||
|
||||
// Backend (server) changes can go here...
|
||||
|
||||
// Don't change anything below here if you are making your own plugin
|
||||
module.exports = {
|
||||
pluginConfig
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
console.log('Webserver plugins loaded successfully.');
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
const WebSocket = require('ws');
|
||||
const { serverConfig, configExists } = require('./server_config');
|
||||
const { logChat } = require('./console');
|
||||
const { logInfo } = require('./console');
|
||||
const helpers = require('./helpers');
|
||||
const storage = require('./storage.js');
|
||||
|
||||
@@ -24,14 +24,14 @@ function createChatServer() {
|
||||
storage.chatHistory.forEach((message) => {
|
||||
const historyMessage = { ...message, history: true };
|
||||
|
||||
if (!request.session?.isAdminAuthenticated) delete historyMessage.ip;
|
||||
if (!helpers.isAdmin(request)) delete historyMessage.ip;
|
||||
ws.send(JSON.stringify(historyMessage));
|
||||
});
|
||||
|
||||
ws.send(JSON.stringify({
|
||||
type: 'clientIp',
|
||||
ip: clientIp,
|
||||
admin: request.session?.isAdminAuthenticated
|
||||
admin: helpers.isAdmin(request)
|
||||
}));
|
||||
|
||||
|
||||
@@ -78,19 +78,19 @@ function createChatServer() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.session?.isAdminAuthenticated === true) messageData.admin = true;
|
||||
if (helpers.isAdmin(request) === true) messageData.admin = true;
|
||||
if (messageData.nickname?.length > 32) messageData.nickname = messageData.nickname.substring(0, 32);
|
||||
if (messageData.message?.length > 255) messageData.message = messageData.message.substring(0, 255);
|
||||
|
||||
storage.chatHistory.push(messageData);
|
||||
if (storage.chatHistory.length > 50) storage.chatHistory.shift();
|
||||
|
||||
logChat(messageData);
|
||||
logInfo(`${message.nickname} (${message.ip}) sent a chat message: ${message.message}`);
|
||||
|
||||
chatWss.clients.forEach((client) => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
const responseMessage = { ...messageData };
|
||||
if (!request.session?.isAdminAuthenticated) delete responseMessage.ip;
|
||||
if (!helpers.isAdmin(request)) delete responseMessage.ip;
|
||||
|
||||
client.send(JSON.stringify(responseMessage));
|
||||
}
|
||||
|
||||
+6
-17
@@ -1,7 +1,6 @@
|
||||
const fs = require('fs').promises;
|
||||
|
||||
const verboseMode = process.argv.includes('--debug');
|
||||
const verboseModeFfmpeg = process.argv.includes('--ffmpegdebug');
|
||||
|
||||
const LOG_FILE = process.argv.includes('--config') && process.argv[process.argv.indexOf('--config') + 1]
|
||||
? `serverlog_${process.argv[process.argv.indexOf('--config') + 1]}.txt`
|
||||
@@ -15,13 +14,10 @@ let logBuffer = [];
|
||||
|
||||
// Message prefixes with ANSI codes
|
||||
const MESSAGE_PREFIX = {
|
||||
CHAT: "\x1b[36m[CHAT]\x1b[0m",
|
||||
DEBUG: "\x1b[36m[DEBUG]\x1b[0m",
|
||||
ERROR: "\x1b[31m[ERROR]\x1b[0m",
|
||||
FFMPEG: "\x1b[36m[FFMPEG]\x1b[0m",
|
||||
INFO: "\x1b[32m[INFO]\x1b[0m",
|
||||
WARN: "\x1b[33m[WARN]\x1b[0m",
|
||||
SECURITY: "\x1b[36m[SECURITY]\x1b[0m",
|
||||
};
|
||||
|
||||
const getCurrentTime = () => {
|
||||
@@ -36,28 +32,21 @@ const removeANSIEscapeCodes = (str) => str.replace(ANSI_ESCAPE_CODE_PATTERN, '')
|
||||
const logMessage = (type, messages) => {
|
||||
const logMessage = `${getCurrentTime()} ${MESSAGE_PREFIX[type]} ${messages.join(' ')}`;
|
||||
|
||||
if ((type === 'DEBUG' && verboseMode) || (type === 'FFMPEG' && verboseModeFfmpeg) || type !== 'DEBUG' && type !== 'FFMPEG') {
|
||||
if ((type === 'DEBUG' && verboseMode) || type !== 'DEBUG') {
|
||||
logs.push(logMessage);
|
||||
if (logs.length > maxConsoleLogLines) logs.shift();
|
||||
console.log(logMessage);
|
||||
}
|
||||
|
||||
if(type !== 'FFMPEG') appendLogToBuffer(logMessage);
|
||||
logBuffer.push(removeANSIEscapeCodes(logMessage) + '\n');
|
||||
};
|
||||
|
||||
const logSecurity = (...messages) => logMessage('SECURITY', messages);
|
||||
const logDebug = (...messages) => logMessage('DEBUG', messages);
|
||||
const logChat = (message) => logMessage('CHAT', [`${message.nickname} (${message.ip}) sent a chat message: ${message.message}`]);
|
||||
const logError = (...messages) => logMessage('ERROR', messages);
|
||||
const logFfmpeg = (...messages) => logMessage('FFMPEG', messages, verboseModeFfmpeg);
|
||||
const logInfo = (...messages) => logMessage('INFO', messages);
|
||||
const logWarn = (...messages) => logMessage('WARN', messages);
|
||||
const logInfo = (...messages) => logMessage('INFO', messages);
|
||||
const logDebug = (...messages) => logMessage('DEBUG', messages);
|
||||
|
||||
function appendLogToBuffer(logMessage) {
|
||||
const cleanLogMessage = removeANSIEscapeCodes(logMessage);
|
||||
logBuffer.push(cleanLogMessage + '\n');
|
||||
}
|
||||
appendLogToBuffer("Server started.");
|
||||
logBuffer.push("Server started.");
|
||||
|
||||
async function flushLogBuffer() {
|
||||
if (logBuffer.length === 0) return;
|
||||
@@ -90,4 +79,4 @@ process.on('exit', flushLogBuffer);
|
||||
process.on('SIGINT', gracefulExit);
|
||||
process.on('SIGTERM', gracefulExit);
|
||||
|
||||
module.exports = { logError, logDebug, logFfmpeg, logInfo, logWarn, logs, logChat, logSecurity };
|
||||
module.exports = { logError, logDebug, logInfo, logWarn, logs };
|
||||
@@ -27,6 +27,7 @@ var dataToSend = {
|
||||
rt0: '',
|
||||
rt1: '',
|
||||
rt_flag: '',
|
||||
lps: '',
|
||||
ims: 0,
|
||||
eq: 0,
|
||||
agc: 0,
|
||||
@@ -150,7 +151,7 @@ function handleData(wss, receivedData, rdsWss) {
|
||||
case receivedLine.startsWith('Ss'):
|
||||
processSignal(receivedLine, true, false);
|
||||
break;
|
||||
case receivedLine.startsWith('SS'): // ss? oh no
|
||||
case receivedLine.startsWith('SS'): // ss? germany mentioned?
|
||||
processSignal(receivedLine, true, true);
|
||||
break;
|
||||
case receivedLine.startsWith('SM'):
|
||||
@@ -229,7 +230,7 @@ function handleData(wss, receivedData, rdsWss) {
|
||||
}).catch((error) => console.log("Error fetching Tx info:", error));
|
||||
|
||||
// Send the updated data to the client
|
||||
const dataToSendJSON = JSON.stringify(dataToSend);
|
||||
const dataToSendJSON = JSON.stringify({...dataToSend, timestamp: Math.floor(Date.now() / 1000) - new Date().getTimezoneOffset() * 60});
|
||||
if (currentTime - lastUpdateTime >= updateInterval) {
|
||||
wss.clients.forEach((client) => client.send(dataToSendJSON));
|
||||
lastUpdateTime = Date.now();
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const express = require('express');
|
||||
const endpointsRouter = require('./endpoints');
|
||||
|
||||
// --- STØTTE FOR FLERE INSTANSER (--config) ---
|
||||
let configSuffix = '';
|
||||
const configArgIndex = process.argv.indexOf('--config');
|
||||
if (configArgIndex !== -1 && process.argv.length > configArgIndex + 1) {
|
||||
configSuffix = '_' + process.argv[configArgIndex + 1];
|
||||
} else if (process.env.CONFIG) {
|
||||
configSuffix = '_' + process.env.CONFIG;
|
||||
}
|
||||
const CONFIG_FILE = path.join(__dirname, `enhanced_tuning_config${configSuffix}.json`);
|
||||
// ---------------------------------------------
|
||||
|
||||
// Default Configuration
|
||||
let pluginConfig = {
|
||||
// Layout & UI
|
||||
LAYOUT_STYLE: 'modern',
|
||||
HIDE_ALL_BUTTONS: false,
|
||||
SHOW_LOOP_BUTTON: true,
|
||||
SHOW_BAND_RANGE: true,
|
||||
HIDE_DECIMAL_FOR_HF: false,
|
||||
HIDE_DECIMAL_HF_THRESHOLD: 30,
|
||||
ENABLE_TUNE_STEP_FEATURE: true,
|
||||
TUNE_STEP_TIMEOUT_SECONDS: 20,
|
||||
ENABLED_BANDS: ['FM', 'OIRT', 'SW', 'MW', 'LW'],
|
||||
|
||||
// Tuning & Hardware
|
||||
TUNING_STANDARD: 'international',
|
||||
ENABLE_MW_STEP_TOGGLE: true,
|
||||
ENABLE_FREQUENCY_MEMORY: true,
|
||||
ENABLE_SMART_KHZ_INPUT: true,
|
||||
ENABLE_AM_BW: true,
|
||||
FIRMWARE_TYPE: 'FM-DX-Tuner',
|
||||
ENABLE_DEFAULT_AM_BW: false,
|
||||
DEFAULT_AM_BW_VALUE: '56000',
|
||||
|
||||
// Limits
|
||||
overrideServerTuningLimit: true,
|
||||
fmLower: 64.0, fmUpper: 108.0,
|
||||
amLower: 0.144, amUpper: 30.0,
|
||||
|
||||
// Egendefinerte Bånd & Navn
|
||||
customMainBands: {
|
||||
'AM_SUPER': { name: 'AM', tune: 1.000, start: 0.144, end: 27.0 },
|
||||
'FM': { name: 'FM', tune: 87.500, start: 87.5, end: 108.0 },
|
||||
'OIRT': { name: 'OIRT', tune: 65.900, start: 65.9, end: 74.0 },
|
||||
'SW': { name: 'SW', tune: 9.400, start: 1.710, end: 27.0 },
|
||||
'MW': { name: 'MW', tune: 0.504, start: 0.504, end: 1.701 },
|
||||
'LW': { name: 'LW', tune: 0.144, start: 0.144, end: 0.351 }
|
||||
},
|
||||
customSwBands: {
|
||||
'160m': { tune: 1.8, start: 1.8, end: 2.0 }, '120m': { tune: 2.3, start: 2.3, end: 2.5 },
|
||||
'90m': { tune: 3.2, start: 3.2, end: 3.4 }, '75m': { tune: 3.9, start: 3.9, end: 4.0 },
|
||||
'60m': { tune: 4.75, start: 4.75, end: 5.06 }, '49m': { tune: 5.9, start: 5.9, end: 6.2 },
|
||||
'41m': { tune: 7.2, start: 7.2, end: 7.6 }, '31m': { tune: 9.4, start: 9.4, end: 9.9 },
|
||||
'25m': { tune: 11.6, start: 11.6, end: 12.1 }, '22m': { tune: 13.57, start: 13.57, end: 13.87 },
|
||||
'19m': { tune: 15.1, start: 15.1, end: 15.83 }, '16m': { tune: 17.48, start: 17.48, end: 17.9 },
|
||||
'15m': { tune: 18.9, start: 18.9, end: 19.02 }, '13m': { tune: 21.45, start: 21.45, end: 21.85 },
|
||||
'11m': { tune: 25.67, start: 25.67, end: 26.1 }
|
||||
},
|
||||
|
||||
// Plugins Integration
|
||||
ENABLE_AM_SCANNER: false,
|
||||
ENABLE_ANALOG_SCALE: true,
|
||||
ANALOG_SCALE_AUTOSTART: true,
|
||||
SHOW_TUNING_KNOB: true,
|
||||
ANALOG_SCALE_ENABLE_FM: true,
|
||||
ANALOG_SCALE_BRIGHTNESS: 1.5,
|
||||
ENABLE_VU_METER: true,
|
||||
VU_METER_GAIN_FM: 1.5,
|
||||
VU_METER_GAIN_AM: 1.5,
|
||||
VU_METER_MODE: 'RMS',
|
||||
ENABLE_MAGIC_EYE: true,
|
||||
ENABLE_PS_SCALE: true,
|
||||
ENABLE_SPECTRUM_OVERLAY: true,
|
||||
ENABLE_SW_STATIONS_SCALE: false,
|
||||
|
||||
// AM Scanner Thresholds
|
||||
thr_LW: 35, thr_MW: 35, thr_160m: 35, thr_120m: 35, thr_90m: 35,
|
||||
thr_75m: 35, thr_60m: 35, thr_49m: 35, thr_41m: 35, thr_31m: 35,
|
||||
thr_25m: 35, thr_22m: 35, thr_19m: 35, thr_16m: 35, thr_15m: 35,
|
||||
thr_13m: 35, thr_11m: 35
|
||||
};
|
||||
|
||||
if (fs.existsSync(CONFIG_FILE)) {
|
||||
try {
|
||||
const data = fs.readFileSync(CONFIG_FILE, 'utf8');
|
||||
pluginConfig = { ...pluginConfig, ...JSON.parse(data) };
|
||||
} catch (err) {
|
||||
console.error('[Enhanced Tuning] Feil ved lesing av config:', err);
|
||||
}
|
||||
}
|
||||
|
||||
const checkStrictAdmin = (req, res, next) => {
|
||||
if (req.session && req.session.isAdminAuthenticated) return next();
|
||||
return res.status(401).send('Unauthorized. You must be an administrator.');
|
||||
};
|
||||
|
||||
endpointsRouter.get('/enhanced_tuning/api/auth-check', (req, res) => {
|
||||
res.json({
|
||||
isAdmin: (req.session && req.session.isAdminAuthenticated) || false,
|
||||
isTune: true,
|
||||
config: pluginConfig
|
||||
});
|
||||
});
|
||||
|
||||
endpointsRouter.post('/enhanced_tuning/api/config', checkStrictAdmin, express.json(), (req, res) => {
|
||||
try {
|
||||
pluginConfig = { ...pluginConfig, ...req.body };
|
||||
fs.writeFileSync(CONFIG_FILE, JSON.stringify(pluginConfig, null, 2));
|
||||
res.json({ success: true, message: 'Settings saved successfully' });
|
||||
} catch (err) {
|
||||
console.error('[Enhanced Tuning] Feil ved lagring av config:', err);
|
||||
res.status(500).json({ success: false });
|
||||
}
|
||||
});
|
||||
|
||||
// Admin Panel Side
|
||||
endpointsRouter.get('/enhanced_tuning/AP', checkStrictAdmin, (req, res) => {
|
||||
const createToggleRow = (id, title, desc, isChecked) => `
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<div class="setting-title">${title}</div>
|
||||
<div class="setting-desc">${desc}</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="${id}" ${isChecked ? 'checked' : ''}>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const createInputRow = (id, title, desc, value, type = "text", step = "1") => `
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<div class="setting-title">${title}</div>
|
||||
<div class="setting-desc">${desc}</div>
|
||||
</div>
|
||||
<input type="${type}" id="${id}" value="${value}" step="${step}" class="dark-input">
|
||||
</div>
|
||||
`;
|
||||
|
||||
const createSelectRow = (id, title, desc, options, selectedValue) => {
|
||||
let opts = options.map(opt => `<option value="${opt.val}" ${opt.val === selectedValue ? 'selected' : ''}>${opt.label}</option>`).join('');
|
||||
return `
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<div class="setting-title">${title}</div>
|
||||
<div class="setting-desc">${desc}</div>
|
||||
</div>
|
||||
<select id="${id}" class="dark-input">${opts}</select>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
const createSliderRow = (id, title, desc, min, max, step, value) => `
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<div class="setting-title">${title}</div>
|
||||
<div class="setting-desc">${desc}</div>
|
||||
</div>
|
||||
<div style="display:flex; align-items:center; gap:15px;">
|
||||
<input type="range" id="${id}" min="${min}" max="${max}" step="${step}" value="${value}" style="cursor: pointer;">
|
||||
<span id="${id}_display" style="color:var(--accent); font-weight:bold; width: 35px; text-align:right;">${value}</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Enhanced Tuning Settings</title>
|
||||
<style>
|
||||
:root { --bg: #121212; --panel-bg: #1e1e1e; --row-bg: #181818; --border: #333; --text: #f0f0f0; --subtext: #999; --accent: #3498db; --accent-hover: #2980b9; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: var(--bg); color: var(--text); margin: 0; display: flex; height: 100vh; overflow: hidden; }
|
||||
.sidebar { width: 260px; background-color: var(--panel-bg); border-right: 1px solid var(--border); display: flex; flex-direction: column; }
|
||||
.sidebar-header { padding: 20px; font-size: 18px; font-weight: bold; border-bottom: 1px solid var(--border); color: var(--accent); }
|
||||
.nav-btn { padding: 15px 20px; background: none; border: none; color: var(--subtext); text-align: left; cursor: pointer; font-size: 15px; border-left: 3px solid transparent; transition: all 0.2s; }
|
||||
.nav-btn:hover { background-color: var(--row-bg); color: var(--text); }
|
||||
.nav-btn.active { border-left-color: var(--accent); color: var(--accent); background-color: rgba(52, 152, 219, 0.1); font-weight: bold; }
|
||||
.main-content { flex: 1; padding: 40px; overflow-y: auto; position: relative; }
|
||||
.tab-content { display: none; max-width: 900px; margin: 0 auto; }
|
||||
.tab-content.active { display: block; animation: fadeIn 0.3s; }
|
||||
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
|
||||
h2 { color: var(--accent); margin-top: 0; margin-bottom: 25px; font-weight: 500; font-size: 24px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
|
||||
.setting-row { display: flex; justify-content: space-between; align-items: center; background-color: var(--row-bg); padding: 15px 20px; border: 1px solid var(--border); border-radius: 8px; margin-bottom: 12px; transition: border-color 0.2s; }
|
||||
.setting-row:hover { border-color: #555; }
|
||||
.setting-info { flex: 1; padding-right: 20px; }
|
||||
.setting-title { font-size: 16px; font-weight: 600; margin-bottom: 4px; }
|
||||
.setting-desc { font-size: 13px; color: var(--subtext); line-height: 1.4; }
|
||||
.dark-input { background-color: var(--bg); border: 1px solid var(--border); color: var(--text); padding: 10px 15px; border-radius: 6px; font-size: 14px; min-width: 150px; outline: none; transition: border-color 0.2s; }
|
||||
.dark-input:focus { border-color: var(--accent); }
|
||||
.switch { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; }
|
||||
.switch input { opacity: 0; width: 0; height: 0; }
|
||||
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #444; transition: .3s; border-radius: 24px; }
|
||||
.slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: .3s; border-radius: 50%; }
|
||||
input:checked + .slider { background-color: var(--accent); }
|
||||
input:checked + .slider:before { transform: translateX(20px); }
|
||||
.threshold-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
|
||||
.threshold-card { background: var(--row-bg); border: 1px solid var(--border); padding: 15px; border-radius: 8px; display: flex; flex-direction: column; align-items: center; gap: 10px; }
|
||||
.threshold-card span { font-weight: bold; color: var(--accent); }
|
||||
.threshold-card input { width: 80px; text-align: center; }
|
||||
.btn-save { background-color: var(--accent); color: white; border: none; padding: 12px 25px; border-radius: 6px; font-size: 16px; font-weight: bold; cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.3); transition: background 0.2s; }
|
||||
.btn-save:hover { background-color: var(--accent-hover); }
|
||||
#toast { visibility: hidden; min-width: 250px; background-color: #27ae60; color: #fff; text-align: center; border-radius: 6px; padding: 16px; position: fixed; z-index: 1000; bottom: 40px; left: 50%; transform: translateX(-50%); font-size: 16px; font-weight: bold; opacity: 0; transition: opacity 0.3s; }
|
||||
#toast.show { visibility: visible; opacity: 1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sidebar">
|
||||
<div class="sidebar-header">Enhanced Tuning</div>
|
||||
<button class="nav-btn active" data-target="tab-ui">1. General UI & Layout</button>
|
||||
<button class="nav-btn" data-target="tab-hardware">2. Tuning & Hardware</button>
|
||||
<button class="nav-btn" data-target="tab-limits">3. Band Limits</button>
|
||||
<button class="nav-btn" data-target="tab-plugins">4. Plugin Integration</button>
|
||||
|
||||
<div style="margin-top: auto; padding: 20px; border-top: 1px solid var(--border);">
|
||||
<button class="btn-save" id="saveBtn" style="width: 100%;">Save Settings</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main-content">
|
||||
<div id="tab-ui" class="tab-content active">
|
||||
<h2>General UI & Layout</h2>
|
||||
${createSelectRow('LAYOUT_STYLE', 'Visual Layout Style', 'Choose the layout design for the plugin controls.', [{val: 'modern', label:'Modern (Side Panel)'}, {val:'classic', label:'Classic (Compact)'}], pluginConfig.LAYOUT_STYLE)}
|
||||
${createToggleRow('HIDE_ALL_BUTTONS', 'Hide All Buttons', 'Hides new UI elements. Only effective if Layout is Modern.', pluginConfig.HIDE_ALL_BUTTONS)}
|
||||
${createToggleRow('SHOW_LOOP_BUTTON', 'Show Band Loop Button', 'Enable or disable the frequency loop feature entirely.', pluginConfig.SHOW_LOOP_BUTTON)}
|
||||
${createToggleRow('SHOW_BAND_RANGE', 'Show Band Range', 'Show the start ↔ end frequency text under the main display.', pluginConfig.SHOW_BAND_RANGE)}
|
||||
${createToggleRow('HIDE_DECIMAL_FOR_HF', 'Hide Decimal Point For HF Band', 'For AM/LW/MW/SW frequencies, hide the decimal point in the main frequency display.', pluginConfig.HIDE_DECIMAL_FOR_HF)}
|
||||
${createInputRow('HIDE_DECIMAL_HF_THRESHOLD', 'Hide Decimal Threshold (MHz)', 'Frequencies at or below this value (in MHz) will have the decimal point hidden.', pluginConfig.HIDE_DECIMAL_HF_THRESHOLD, 'number', '0.001')}
|
||||
${createToggleRow('ENABLE_TUNE_STEP_FEATURE', 'Tune Step Feature', 'Click frequency display to change tuning steps.', pluginConfig.ENABLE_TUNE_STEP_FEATURE)}
|
||||
${createInputRow('TUNE_STEP_TIMEOUT_SECONDS', 'Tune Step Timeout', 'Seconds of inactivity before step resets (0 to disable).', pluginConfig.TUNE_STEP_TIMEOUT_SECONDS, 'number')}
|
||||
|
||||
<h3 style="margin-top:30px; color:#aaa; font-size:16px;">Enabled Bands</h3>
|
||||
${createToggleRow('band_FM', 'FM Band', '', pluginConfig.ENABLED_BANDS.includes('FM'))}
|
||||
${createToggleRow('band_OIRT', 'OIRT Band', '', pluginConfig.ENABLED_BANDS.includes('OIRT'))}
|
||||
${createToggleRow('band_SW', 'Shortwave (SW) Band', '', pluginConfig.ENABLED_BANDS.includes('SW'))}
|
||||
${createToggleRow('band_MW', 'Mediumwave (MW) Band', '', pluginConfig.ENABLED_BANDS.includes('MW'))}
|
||||
${createToggleRow('band_LW', 'Longwave (LW) Band', '', pluginConfig.ENABLED_BANDS.includes('LW'))}
|
||||
</div>
|
||||
|
||||
<div id="tab-hardware" class="tab-content">
|
||||
<h2>Tuning & Hardware Options</h2>
|
||||
${createSelectRow('TUNING_STANDARD', 'Regional Tuning Standard', 'Controls AM/FM steps and ranges.', [{val:'international', label:'International'}, {val:'americas', label:'Americas'}, {val:'japan', label:'Japan'}], pluginConfig.TUNING_STANDARD)}
|
||||
${createToggleRow('ENABLE_SMART_KHZ_INPUT', 'Smart kHz Input', 'Type e.g. "693" instead of "0.693". Auto-converts numbers on AM bands to avoid plugin conflicts.', pluginConfig.ENABLE_SMART_KHZ_INPUT)}
|
||||
${createToggleRow('ENABLE_MW_STEP_TOGGLE', 'MW 9/10kHz Toggle Button', 'Shows a button when in MW to switch step size.', pluginConfig.ENABLE_MW_STEP_TOGGLE)}
|
||||
${createToggleRow('ENABLE_FREQUENCY_MEMORY', 'Frequency Memory', 'Remember last tuned frequency per band.', pluginConfig.ENABLE_FREQUENCY_MEMORY)}
|
||||
|
||||
<h3 style="margin-top:30px; color:#aaa; font-size:16px;">AM Bandwidth Injection</h3>
|
||||
${createToggleRow('ENABLE_AM_BW', 'Enable Custom AM Bandwidth', 'Requires TEF6686_ESP32 firmware.', pluginConfig.ENABLE_AM_BW)}
|
||||
${createSelectRow('FIRMWARE_TYPE', 'Firmware Type', 'Select compatibility mode for bandwidth.', [{val:'TEF6686_ESP32', label:'TEF6686_ESP32 (PE5PVB)'}, {val:'FM-DX-Tuner', label:'FM-DX-Tuner (kkonrad)'}], pluginConfig.FIRMWARE_TYPE)}
|
||||
${createToggleRow('ENABLE_DEFAULT_AM_BW', 'Force Default AM BW', 'Auto-select a specific BW when entering AM.', pluginConfig.ENABLE_DEFAULT_AM_BW)}
|
||||
${createSelectRow('DEFAULT_AM_BW_VALUE', 'Default AM BW Value', 'Applied if forced default is enabled.', [{val:'56000', label:'3 kHz'}, {val:'64000', label:'4 kHz'}, {val:'72000', label:'6 kHz'}, {val:'84000', label:'8 kHz'}], pluginConfig.DEFAULT_AM_BW_VALUE)}
|
||||
</div>
|
||||
|
||||
<div id="tab-limits" class="tab-content">
|
||||
<h2>Tuning Limits & Bands Configuration</h2>
|
||||
|
||||
${createToggleRow('overrideServerTuningLimit', 'Override Server Limits', 'Allow plugin to manage its own separate hardware limits for AM and FM. Set the actual values in the core "Webserver -> Tuning Options" panel.', pluginConfig.overrideServerTuningLimit)}
|
||||
|
||||
<h3 style="margin-top:30px; color:#aaa; font-size:16px;">Main Bands Configuration</h3>
|
||||
<p style="color:var(--subtext); font-size:13px; margin-bottom:15px;">Rename bands (max 5 chars to fit buttons), set default start frequency, and adjust limits.</p>
|
||||
|
||||
${['AM_SUPER', 'FM', 'OIRT', 'SW', 'MW', 'LW'].map(key => `
|
||||
<div class="setting-row" style="padding: 10px 20px;">
|
||||
<div class="setting-info"><div class="setting-title" style="font-size:14px;">${key}</div></div>
|
||||
<div style="display:flex; gap:8px; align-items:center;">
|
||||
<span style="color:var(--subtext); font-size:11px;">Name</span>
|
||||
<input type="text" id="name_${key}" maxlength="5" value="${pluginConfig.customMainBands[key].name}" class="dark-input" style="width:70px; min-width:auto; padding:6px 10px; text-align:center;">
|
||||
<span style="color:var(--subtext); font-size:11px;">Default Tune</span>
|
||||
<input type="number" id="tune_${key}" value="${pluginConfig.customMainBands[key].tune}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:6px 10px;">
|
||||
<span style="color:var(--subtext); font-size:11px;">Low</span>
|
||||
<input type="number" id="start_${key}" value="${pluginConfig.customMainBands[key].start}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:6px 10px;">
|
||||
<span style="color:var(--subtext); font-size:11px;">High</span>
|
||||
<input type="number" id="end_${key}" value="${pluginConfig.customMainBands[key].end}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:6px 10px;">
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
|
||||
<h3 style="margin-top:30px; color:#aaa; font-size:16px;">Shortwave Sub-Bands</h3>
|
||||
<div style="display: grid; grid-template-columns: 1fr; gap: 10px;">
|
||||
${Object.keys(pluginConfig.customSwBands).map(key => `
|
||||
<div class="setting-row" style="padding: 10px; margin-bottom:0;">
|
||||
<div class="setting-info"><div class="setting-title" style="font-size:13px;">${key}</div></div>
|
||||
<div style="display:flex; gap:5px; align-items:center;">
|
||||
<span style="color:var(--subtext); font-size:11px;">Default Tune</span>
|
||||
<input type="number" id="sw_tune_${key}" value="${pluginConfig.customSwBands[key].tune}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:4px 8px; font-size:12px;">
|
||||
<span style="color:var(--subtext); font-size:11px; margin-left:10px;">Range</span>
|
||||
<input type="number" id="sw_start_${key}" value="${pluginConfig.customSwBands[key].start}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:4px 8px; font-size:12px;">
|
||||
<span style="color:var(--subtext); font-size:12px;">-</span>
|
||||
<input type="number" id="sw_end_${key}" value="${pluginConfig.customSwBands[key].end}" step="0.001" class="dark-input" style="width:65px; min-width:auto; padding:4px 8px; font-size:12px;">
|
||||
</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Den nye Tab 4: Plugin Integration -->
|
||||
<div id="tab-plugins" class="tab-content">
|
||||
<h2>Plugin Integration</h2>
|
||||
|
||||
<h3 style="margin-top:20px; color:#aaa; font-size:16px;">Highpoint Scanner Integration</h3>
|
||||
${createToggleRow('ENABLE_AM_SCANNER', 'Enable Scanner plugin override', 'Intercepts the Highpoint scanner to respect AM/SW band limits and sub-bands.', pluginConfig.ENABLE_AM_SCANNER)}
|
||||
|
||||
<div id="scanner-thresholds-block" style="display: ${pluginConfig.ENABLE_AM_SCANNER ? 'block' : 'none'}; border-left: 2px solid #3498db; padding-left: 15px; margin-bottom: 30px; margin-top: 15px;">
|
||||
<p style="color:var(--subtext); margin-bottom: 15px; font-size: 13px;">Define the minimum signal strength (0-100) required to pause the scanner on a specific AM/SW band.</p>
|
||||
<div class="threshold-grid">
|
||||
${['LW', 'MW', '160m', '120m', '90m', '75m', '60m', '49m', '41m', '31m', '25m', '22m', '19m', '16m', '15m', '13m', '11m'].map(t => `
|
||||
<div class="threshold-card" style="padding: 10px;">
|
||||
<span>${t} Band</span>
|
||||
<input type="number" id="thr_${t}" value="${pluginConfig['thr_'+t]}" class="dark-input" style="width:60px;">
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 style="margin-top:40px; color:#aaa; font-size:16px;">Highpoint Retro Design Elements Plugin</h3>
|
||||
${createToggleRow('ENABLE_ANALOG_SCALE', 'Enable Analog Scale Integration', 'Injects a dynamic retro analog scale for all bands.', pluginConfig.ENABLE_ANALOG_SCALE)}
|
||||
|
||||
<div id="scale-settings-block" style="display: ${pluginConfig.ENABLE_ANALOG_SCALE ? 'block' : 'none'}; border-left: 2px solid #3498db; padding-left: 15px; margin-bottom: 30px; margin-top: 15px;">
|
||||
${createToggleRow('ANALOG_SCALE_AUTOSTART', 'Autostart Scale', 'Automatically open the scale when tuning to a supported band.', pluginConfig.ANALOG_SCALE_AUTOSTART)}
|
||||
${createToggleRow('SHOW_TUNING_KNOB', 'Show Tuning Knob', 'Displays the dual rotary encoder for manual tuning.', pluginConfig.SHOW_TUNING_KNOB)}
|
||||
${createSliderRow('ANALOG_SCALE_BRIGHTNESS', 'Scale Brightness', 'Adjust the backlight brightness of the analog scale.', '0.2', '2.0', '0.05', pluginConfig.ANALOG_SCALE_BRIGHTNESS)}
|
||||
|
||||
<h4 style="margin-top:20px; color:#aaa; font-size:14px; margin-bottom:10px;">VU Meter Configuration</h4>
|
||||
${createToggleRow('ENABLE_VU_METER', 'Enable VU Meter', 'Displays a stereo VU meter next to the analog scale.', pluginConfig.ENABLE_VU_METER)}
|
||||
${createSelectRow('VU_METER_MODE', 'VU Meter Mode', 'RMS gives smooth realistic pumping. Peak shows raw loudness.',[{val: 'RMS', label: 'RMS (Smooth & Realistic)'}, {val: 'Peak', label: 'Peak (Raw Max Levels)'}], pluginConfig.VU_METER_MODE)}
|
||||
${createSliderRow('VU_METER_GAIN_FM', 'VU Meter Gain (FM)', 'Calibration multiplier for the VU meter on FM/OIRT.', '0.1', '5.0', '0.1', pluginConfig.VU_METER_GAIN_FM)}
|
||||
${createSliderRow('VU_METER_GAIN_AM', 'VU Meter Gain (AM/SW)', 'Calibration multiplier for the VU meter on AM/SW/MW/LW.', '0.1', '5.0', '0.1', pluginConfig.VU_METER_GAIN_AM)}
|
||||
<h4 style="margin-top:20px; color:#aaa; font-size:14px; margin-bottom:10px;">Retro Magic Eye</h4>
|
||||
${createToggleRow('ENABLE_MAGIC_EYE', 'Enable Magic Eye Indicator', 'Converts the signal panel into a glowing vacuum tube indicator.', pluginConfig.ENABLE_MAGIC_EYE)}
|
||||
<h4 style="margin-top:20px; color:#aaa; font-size:14px; margin-bottom:10px;">Scale Overlays & Data</h4>
|
||||
${createToggleRow('ENABLE_PS_SCALE', 'Show FM PS Stations', 'Display RDS PS names directly on the analog FM scale.', pluginConfig.ENABLE_PS_SCALE !== false)}
|
||||
${createToggleRow('ENABLE_SPECTRUM_OVERLAY', 'Show Spectrum Overlay', 'Project the SDR spectrum waterfall onto the analog dial glass.', pluginConfig.ENABLE_SPECTRUM_OVERLAY !== false)}
|
||||
${createToggleRow('ENABLE_SW_STATIONS_SCALE', 'Show SW Stations', 'Display active shortwave stations dynamically on the analog dial.<br><span style="color:#e74c3c; font-weight:bold; font-size:12px;">⚠️ Requires AM Station Info Plugin V1.4 or newer!</span>', pluginConfig.ENABLE_SW_STATIONS_SCALE !== false)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast">Settings Saved Successfully!</div>
|
||||
|
||||
<script>
|
||||
const navBtns = document.querySelectorAll('.nav-btn');
|
||||
const tabs = document.querySelectorAll('.tab-content');
|
||||
|
||||
navBtns.forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
navBtns.forEach(b => b.classList.remove('active'));
|
||||
tabs.forEach(t => t.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
document.getElementById(btn.dataset.target).classList.add('active');
|
||||
});
|
||||
});
|
||||
|
||||
// Dynamisk visning av Scanner Thresholds
|
||||
document.getElementById('ENABLE_AM_SCANNER').addEventListener('change', function() {
|
||||
document.getElementById('scanner-thresholds-block').style.display = this.checked ? 'block' : 'none';
|
||||
});
|
||||
|
||||
document.getElementById('ENABLE_ANALOG_SCALE').addEventListener('change', function() {
|
||||
document.getElementById('scale-settings-block').style.display = this.checked ? 'block' : 'none';
|
||||
});
|
||||
|
||||
// Oppdater teksten vedsidenav sliderne i sanntid
|
||||
document.querySelectorAll('input[type="range"]').forEach(slider => {
|
||||
slider.addEventListener('input', (e) => {
|
||||
const display = document.getElementById(e.target.id + '_display');
|
||||
if (display) display.innerText = e.target.value;
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('saveBtn').addEventListener('click', async () => {
|
||||
const bands = [];
|
||||
if(document.getElementById('band_FM').checked) bands.push('FM');
|
||||
if(document.getElementById('band_OIRT').checked) bands.push('OIRT');
|
||||
if(document.getElementById('band_SW').checked) bands.push('SW');
|
||||
if(document.getElementById('band_MW').checked) bands.push('MW');
|
||||
if(document.getElementById('band_LW').checked) bands.push('LW');
|
||||
|
||||
const config = {
|
||||
LAYOUT_STYLE: document.getElementById('LAYOUT_STYLE').value,
|
||||
HIDE_ALL_BUTTONS: document.getElementById('HIDE_ALL_BUTTONS').checked,
|
||||
SHOW_LOOP_BUTTON: document.getElementById('SHOW_LOOP_BUTTON').checked,
|
||||
SHOW_BAND_RANGE: document.getElementById('SHOW_BAND_RANGE').checked,
|
||||
HIDE_DECIMAL_FOR_HF: document.getElementById('HIDE_DECIMAL_FOR_HF').checked,
|
||||
HIDE_DECIMAL_HF_THRESHOLD: parseFloat(document.getElementById('HIDE_DECIMAL_HF_THRESHOLD').value),
|
||||
ENABLE_TUNE_STEP_FEATURE: document.getElementById('ENABLE_TUNE_STEP_FEATURE').checked,
|
||||
TUNE_STEP_TIMEOUT_SECONDS: parseInt(document.getElementById('TUNE_STEP_TIMEOUT_SECONDS').value),
|
||||
ENABLED_BANDS: bands,
|
||||
|
||||
TUNING_STANDARD: document.getElementById('TUNING_STANDARD').value,
|
||||
ENABLE_SMART_KHZ_INPUT: document.getElementById('ENABLE_SMART_KHZ_INPUT').checked,
|
||||
ENABLE_MW_STEP_TOGGLE: document.getElementById('ENABLE_MW_STEP_TOGGLE').checked,
|
||||
ENABLE_FREQUENCY_MEMORY: document.getElementById('ENABLE_FREQUENCY_MEMORY').checked,
|
||||
ENABLE_AM_BW: document.getElementById('ENABLE_AM_BW').checked,
|
||||
FIRMWARE_TYPE: document.getElementById('FIRMWARE_TYPE').value,
|
||||
ENABLE_DEFAULT_AM_BW: document.getElementById('ENABLE_DEFAULT_AM_BW').checked,
|
||||
DEFAULT_AM_BW_VALUE: document.getElementById('DEFAULT_AM_BW_VALUE').value,
|
||||
|
||||
overrideServerTuningLimit: document.getElementById('overrideServerTuningLimit').checked,
|
||||
|
||||
ENABLE_AM_SCANNER: document.getElementById('ENABLE_AM_SCANNER').checked,
|
||||
ENABLE_ANALOG_SCALE: document.getElementById('ENABLE_ANALOG_SCALE').checked,
|
||||
ANALOG_SCALE_AUTOSTART: document.getElementById('ANALOG_SCALE_AUTOSTART').checked,
|
||||
SHOW_TUNING_KNOB: document.getElementById('SHOW_TUNING_KNOB').checked,
|
||||
ANALOG_SCALE_BRIGHTNESS: parseFloat(document.getElementById('ANALOG_SCALE_BRIGHTNESS').value),
|
||||
ENABLE_VU_METER: document.getElementById('ENABLE_VU_METER').checked,
|
||||
VU_METER_MODE: document.getElementById('VU_METER_MODE').value,
|
||||
VU_METER_GAIN_FM: parseFloat(document.getElementById('VU_METER_GAIN_FM').value),
|
||||
VU_METER_GAIN_AM: parseFloat(document.getElementById('VU_METER_GAIN_AM').value),
|
||||
ENABLE_MAGIC_EYE: document.getElementById('ENABLE_MAGIC_EYE').checked,
|
||||
ENABLE_PS_SCALE: document.getElementById('ENABLE_PS_SCALE').checked,
|
||||
ENABLE_SPECTRUM_OVERLAY: document.getElementById('ENABLE_SPECTRUM_OVERLAY').checked,
|
||||
ENABLE_SW_STATIONS_SCALE: document.getElementById('ENABLE_SW_STATIONS_SCALE').checked
|
||||
};
|
||||
|
||||
const mainKeys = ['AM_SUPER', 'FM', 'OIRT', 'SW', 'MW', 'LW'];
|
||||
config.customMainBands = {};
|
||||
mainKeys.forEach(k => {
|
||||
config.customMainBands[k] = {
|
||||
name: document.getElementById('name_' + k).value,
|
||||
tune: parseFloat(document.getElementById('tune_' + k).value),
|
||||
start: parseFloat(document.getElementById('start_' + k).value),
|
||||
end: parseFloat(document.getElementById('end_' + k).value)
|
||||
};
|
||||
});
|
||||
|
||||
const swKeys = ['160m', '120m', '90m', '75m', '60m', '49m', '41m', '31m', '25m', '22m', '19m', '16m', '15m', '13m', '11m'];
|
||||
config.customSwBands = {};
|
||||
swKeys.forEach(k => {
|
||||
config.customSwBands[k] = {
|
||||
tune: parseFloat(document.getElementById('sw_tune_' + k).value),
|
||||
start: parseFloat(document.getElementById('sw_start_' + k).value),
|
||||
end: parseFloat(document.getElementById('sw_end_' + k).value)
|
||||
};
|
||||
});
|
||||
|
||||
const thresholds = ['LW', 'MW', '160m', '120m', '90m', '75m', '60m', '49m', '41m', '31m', '25m', '22m', '19m', '16m', '15m', '13m', '11m'];
|
||||
thresholds.forEach(t => {
|
||||
config['thr_' + t] = parseInt(document.getElementById('thr_' + t).value);
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await fetch('/enhanced_tuning/api/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
|
||||
const toast = document.getElementById('toast');
|
||||
|
||||
if (res.ok) {
|
||||
toast.innerText = 'Settings Saved Successfully!';
|
||||
toast.style.backgroundColor = '#27ae60';
|
||||
toast.classList.add('show');
|
||||
setTimeout(() => toast.classList.remove('show'), 3000);
|
||||
} else if (res.status === 401) {
|
||||
alert('Session expired! You are no longer logged in as Admin. Please go back to the main page, log in again, and refresh this panel.');
|
||||
} else {
|
||||
throw new Error('Server returned ' + res.status);
|
||||
}
|
||||
} catch(err) {
|
||||
const toast = document.getElementById('toast');
|
||||
toast.innerText = 'Error saving settings!';
|
||||
toast.style.backgroundColor = '#e74c3c';
|
||||
toast.classList.add('show');
|
||||
setTimeout(() => toast.classList.remove('show'), 3000);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
res.send(html);
|
||||
});
|
||||
+29
-132
@@ -6,15 +6,13 @@ const { SerialPort } = require('serialport')
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
|
||||
// File Imports
|
||||
const parseAudioDevice = require('./stream/parser');
|
||||
const { configName, serverConfig, configUpdate, configSave, configExists, configPath } = require('./server_config');
|
||||
const helpers = require('./helpers');
|
||||
const storage = require('./storage');
|
||||
const tunerProfiles = require('./tuner_profiles');
|
||||
const { logInfo, logs } = require('./console');
|
||||
const dataHandler = require('./datahandler');
|
||||
const serverList = require('./server_list');
|
||||
const serverListUpdate = require('./server_list');
|
||||
|
||||
// Endpoints
|
||||
router.get('/', (req, res) => {
|
||||
@@ -34,31 +32,10 @@ router.get('/', (req, res) => {
|
||||
const noPlugins = req.query.noPlugins === 'true';
|
||||
|
||||
if (configExists() === false) {
|
||||
let serialPorts;
|
||||
|
||||
SerialPort.list().then((deviceList) => {
|
||||
serialPorts = deviceList.map(port => ({
|
||||
path: port.path,
|
||||
friendlyName: port.friendlyName,
|
||||
}));
|
||||
|
||||
parseAudioDevice((result) => {
|
||||
res.render('wizard', { // Magical utility wizard
|
||||
isAdminAuthenticated: true,
|
||||
videoDevices: result.audioDevices,
|
||||
audioDevices: result.videoDevices,
|
||||
serialPorts: serialPorts,
|
||||
tunerProfiles: tunerProfiles.map((profile) => ({
|
||||
id: profile.id,
|
||||
label: profile.label,
|
||||
detailsHtml: helpers.parseMarkdown(profile.details || '')
|
||||
}))
|
||||
});
|
||||
});
|
||||
});
|
||||
res.status(500).send("not configured");
|
||||
} else {
|
||||
res.render('index', {
|
||||
isAdminAuthenticated: req.session.isAdminAuthenticated,
|
||||
isAdminAuthenticated: helpers.isAdmin(req),
|
||||
isTuneAuthenticated: req.session.isTuneAuthenticated,
|
||||
tunerName: serverConfig.identification.tunerName,
|
||||
tunerDesc: helpers.parseMarkdown(serverConfig.identification.tunerDesc),
|
||||
@@ -90,38 +67,12 @@ router.get('/403', (req, res) => {
|
||||
|
||||
router.get('/audioonly', (req, res) => res.render('audioonly'))
|
||||
|
||||
router.get('/wizard', (req, res) => {
|
||||
let serialPorts;
|
||||
|
||||
if(!req.session.isAdminAuthenticated) {
|
||||
router.get('/setup', (req, res) => {
|
||||
if(!helpers.isAdmin(req)) {
|
||||
res.render('login');
|
||||
return;
|
||||
}
|
||||
|
||||
SerialPort.list().then((deviceList) => {
|
||||
serialPorts = deviceList.map(port => ({
|
||||
path: port.path,
|
||||
friendlyName: port.friendlyName,
|
||||
}));
|
||||
|
||||
parseAudioDevice((result) => {
|
||||
res.render('wizard', {
|
||||
isAdminAuthenticated: req.session.isAdminAuthenticated,
|
||||
videoDevices: result.audioDevices,
|
||||
audioDevices: result.videoDevices,
|
||||
serialPorts: serialPorts,
|
||||
tunerProfiles: tunerProfiles.map((profile) => ({
|
||||
id: profile.id,
|
||||
label: profile.label,
|
||||
detailsHtml: helpers.parseMarkdown(profile.details || '')
|
||||
}))
|
||||
});
|
||||
});
|
||||
})
|
||||
})
|
||||
|
||||
router.get('/setup', (req, res) => {
|
||||
let serialPorts;
|
||||
function loadConfig() {
|
||||
if (fs.existsSync(configPath)) {
|
||||
const configFileContents = fs.readFileSync(configPath, 'utf8');
|
||||
@@ -130,45 +81,19 @@ router.get('/setup', (req, res) => {
|
||||
return serverConfig;
|
||||
}
|
||||
|
||||
if(!req.session.isAdminAuthenticated) {
|
||||
res.render('login');
|
||||
return;
|
||||
}
|
||||
const processUptimeInSeconds = Math.floor(process.uptime());
|
||||
const formattedProcessUptime = helpers.formatUptime(processUptimeInSeconds);
|
||||
|
||||
SerialPort.list().then((deviceList) => {
|
||||
serialPorts = deviceList.map(port => ({
|
||||
path: port.path,
|
||||
friendlyName: port.friendlyName,
|
||||
}));
|
||||
|
||||
parseAudioDevice((result) => {
|
||||
const processUptimeInSeconds = Math.floor(process.uptime());
|
||||
const formattedProcessUptime = helpers.formatUptime(processUptimeInSeconds);
|
||||
|
||||
const updatedConfig = loadConfig(); // Reload the config every time
|
||||
res.render('setup', {
|
||||
isAdminAuthenticated: req.session.isAdminAuthenticated,
|
||||
videoDevices: result.audioDevices,
|
||||
audioDevices: result.videoDevices,
|
||||
serialPorts: serialPorts,
|
||||
memoryUsage: (process.memoryUsage.rss() / 1024 / 1024).toFixed(1) + ' MB',
|
||||
memoryHeap: (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(1) + ' MB',
|
||||
processUptime: formattedProcessUptime,
|
||||
consoleOutput: logs,
|
||||
plugins: require('./plugins'),
|
||||
enabledPlugins: updatedConfig.plugins,
|
||||
onlineUsers: dataHandler.dataToSend.users,
|
||||
connectedUsers: storage.connectedUsers,
|
||||
device: serverConfig.device,
|
||||
banlist: updatedConfig.webserver.banlist, // Updated banlist from the latest config
|
||||
tunerProfiles: tunerProfiles.map((profile) => ({
|
||||
id: profile.id,
|
||||
label: profile.label,
|
||||
detailsHtml: helpers.parseMarkdown(profile.details || '')
|
||||
}))
|
||||
});
|
||||
});
|
||||
})
|
||||
const updatedConfig = loadConfig(); // Reload the config every time
|
||||
res.render('setup', {
|
||||
isAdminAuthenticated: true,
|
||||
memoryUsage: (process.memoryUsage.rss() / 1024 / 1024).toFixed(1) + ' MB',
|
||||
memoryHeap: (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(1) + ' MB',
|
||||
processUptime: formattedProcessUptime,
|
||||
consoleOutput: logs,
|
||||
onlineUsers: dataHandler.dataToSend.users,
|
||||
connectedUsers: storage.connectedUsers,
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/api', (req, res) => {
|
||||
@@ -232,26 +157,23 @@ router.get('/logout', (req, res) => {
|
||||
|
||||
router.get('/kick', (req, res) => {
|
||||
// Terminate the WebSocket connection for the specified IP address
|
||||
if(req.session.isAdminAuthenticated) helpers.kickClient(req.query.ip);
|
||||
if(helpers.isAdmin(req)) helpers.kickClient(req.query.ip);
|
||||
else {
|
||||
res.status(403);
|
||||
return;
|
||||
}
|
||||
setTimeout(res.redirect, 500, "/setup");
|
||||
setTimeout(() => {
|
||||
res.redirect("/setup");
|
||||
}, 500);
|
||||
});
|
||||
|
||||
router.get('/addToBanlist', (req, res) => {
|
||||
if (!req.session.isAdminAuthenticated) {
|
||||
if (!helpers.isAdmin(req)) {
|
||||
res.status(403);
|
||||
return;
|
||||
}
|
||||
|
||||
const ipAddress = req.query.ip;
|
||||
const location = 'Unknown';
|
||||
const date = Date.now();
|
||||
const reason = req.query.reason;
|
||||
|
||||
userBanData = [ipAddress, location, date, reason];
|
||||
userBanData = [req.query.ip, 'Unknown', Date.now(), req.query.reason];
|
||||
|
||||
if (typeof serverConfig.webserver.banlist !== 'object') serverConfig.webserver.banlist = [];
|
||||
|
||||
@@ -262,7 +184,7 @@ router.get('/addToBanlist', (req, res) => {
|
||||
});
|
||||
|
||||
router.get('/removeFromBanlist', (req, res) => {
|
||||
if (!req.session.isAdminAuthenticated) {
|
||||
if (!helpers.isAdmin(req)) {
|
||||
res.status(403);
|
||||
return;
|
||||
}
|
||||
@@ -284,9 +206,9 @@ router.get('/removeFromBanlist', (req, res) => {
|
||||
router.post('/saveData', (req, res) => {
|
||||
const data = req.body;
|
||||
let firstSetup;
|
||||
if(req.session.isAdminAuthenticated || !configExists()) {
|
||||
if(helpers.isAdmin(req) || !configExists()) {
|
||||
configUpdate(data);
|
||||
serverList.update();
|
||||
serverListUpdate.update();
|
||||
|
||||
if(!configExists()) firstSetup = true;
|
||||
logInfo('Server config changed successfully.');
|
||||
@@ -298,7 +220,7 @@ router.post('/saveData', (req, res) => {
|
||||
router.get('/getData', (req, res) => {
|
||||
if (configExists() === false) res.json(serverConfig);
|
||||
|
||||
if(req.session.isAdminAuthenticated) {
|
||||
if(helpers.isAdmin(req)) {
|
||||
// Check if the file exists
|
||||
fs.access(configPath, fs.constants.F_OK, (err) => {
|
||||
if (err) console.log(err);
|
||||
@@ -310,11 +232,6 @@ router.get('/getData', (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/getDevices', (req, res) => {
|
||||
if (req.session.isAdminAuthenticated || !fs.existsSync(configName + '.json')) parseAudioDevice(res.json);
|
||||
else res.status(403).json({ error: 'Unauthorized' });
|
||||
});
|
||||
|
||||
/* Static data are being sent through here on connection - these don't change when the server is running */
|
||||
router.get('/static_data', (req, res) => {
|
||||
res.json({
|
||||
@@ -327,7 +244,8 @@ router.get('/static_data', (req, res) => {
|
||||
rdsTimeout: serverConfig.webserver.rdsTimeout || 0,
|
||||
tunerName: serverConfig.identification.tunerName || '',
|
||||
tunerDesc: serverConfig.identification.tunerDesc || '',
|
||||
ant: serverConfig.antennas || {}
|
||||
ant: serverConfig.antennas || {},
|
||||
fork: "radio95"
|
||||
});
|
||||
});
|
||||
|
||||
@@ -437,25 +355,4 @@ router.get('/log_fmlist', (req, res) => {
|
||||
request.end();
|
||||
});
|
||||
|
||||
router.get('/tunnelservers', async (req, res) => {
|
||||
const servers = [
|
||||
{ value: "eu", host: "eu.fmtuner.org", label: "Europe" },
|
||||
{ value: "us", host: "us.fmtuner.org", label: "Americas" },
|
||||
{ value: "sg", host: "sg.fmtuner.org", label: "Asia & Oceania" },
|
||||
{ value: "pldx", host: "pldx.duckdns.org", label: "Poland (k201)" },
|
||||
];
|
||||
|
||||
const results = await Promise.all(
|
||||
servers.map(async s => {
|
||||
const latency = await helpers.checkLatency(s.host);
|
||||
return {
|
||||
value: s.value,
|
||||
label: `${s.label} (${latency ? latency + ' ms' : 'offline'})` // From my tests, the latency via HTTP ping is roughly 2x higher than regular ping
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
res.json(results);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
+61
-23
@@ -8,6 +8,18 @@ const storage = require('./storage');
|
||||
const consoleCmd = require('./console');
|
||||
const { serverConfig, configSave } = require('./server_config');
|
||||
|
||||
const dns = require('dns').promises;
|
||||
let adminIps = null;
|
||||
|
||||
async function loadAdminIp() {
|
||||
try {
|
||||
adminIps = (await dns.lookup("fmadmin.flerken.cc", { all: true }))
|
||||
.map(({ address }) => normalizeIp(address));
|
||||
} catch {}
|
||||
}
|
||||
loadAdminIp()
|
||||
setInterval(loadAdminIp, 5 * 60 * 1000);
|
||||
|
||||
let geoip = null;
|
||||
try {
|
||||
geoip = require('geoip-lite');
|
||||
@@ -112,16 +124,16 @@ function fetchIpWhoisInfo(ip, timeoutMs = 1500) {
|
||||
}
|
||||
|
||||
|
||||
function handleConnect(clientIp, currentUsers, ws, callback) {
|
||||
function handleConnect(clientIp, currentUsers, ws, request, callback) {
|
||||
if (ipCache.has(clientIp)) {
|
||||
processConnection(clientIp, ipCache.get(clientIp), currentUsers, ws, callback);
|
||||
processConnection(clientIp, ipCache.get(clientIp), currentUsers, ws, request, callback);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ipInfoInFlight.has(clientIp)) {
|
||||
ipInfoInFlight.get(clientIp)
|
||||
.then((info) => processConnection(clientIp, info, currentUsers, ws, callback))
|
||||
.catch(() => processConnection(clientIp, { country: undefined }, currentUsers, ws, callback));
|
||||
.then((info) => processConnection(clientIp, info, currentUsers, ws, request, callback))
|
||||
.catch(() => processConnection(clientIp, { country: undefined }, currentUsers, ws, request, callback));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -152,16 +164,16 @@ function handleConnect(clientIp, currentUsers, ws, callback) {
|
||||
});
|
||||
|
||||
ipInfoInFlight.set(clientIp, inFlightPromise);
|
||||
inFlightPromise.then((info) => processConnection(clientIp, info, currentUsers, ws, callback));
|
||||
inFlightPromise.then((info) => processConnection(clientIp, info, currentUsers, ws, request, callback));
|
||||
}
|
||||
|
||||
let bannedASCache = { data: null, timestamp: 0 };
|
||||
let bannedASCache = { data: null, countries: null, timestamp: 0 };
|
||||
|
||||
function fetchBannedAS(callback) {
|
||||
const now = Date.now();
|
||||
if (bannedASCache.data && now - bannedASCache.timestamp < 10 * 60 * 1000) return callback(bannedASCache.data);
|
||||
if (bannedASCache.data && bannedASCache.countries && now - bannedASCache.timestamp < 10 * 60 * 1000) return callback(bannedASCache.data, bannedASCache.countries);
|
||||
|
||||
const req = https.get("https://flerken.zapto.org:5000/banned_as.json", { family: 4 }, (banResponse) => {
|
||||
const req = https.get("https://data.fmtuner.net/banned_as.json", { family: 4 }, (banResponse) => {
|
||||
let banData = "";
|
||||
|
||||
banResponse.on("data", (chunk) => banData += chunk);
|
||||
@@ -169,11 +181,12 @@ function fetchBannedAS(callback) {
|
||||
banResponse.on("end", () => {
|
||||
try {
|
||||
const bannedAS = JSON.parse(banData).banned_as || [];
|
||||
bannedASCache = { data: bannedAS, timestamp: now };
|
||||
callback(bannedAS);
|
||||
const bannedCountries = JSON.parse(banData).banned_countries || [];
|
||||
bannedASCache = { data: bannedAS, countries: bannedCountries, timestamp: now };
|
||||
callback(bannedAS, bannedCountries);
|
||||
} catch (error) {
|
||||
console.error("Error parsing banned AS list:", error);
|
||||
callback([]); // Default to allowing user
|
||||
callback(["*"], []); // Default to blocking the user
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -193,12 +206,12 @@ function fetchBannedAS(callback) {
|
||||
|
||||
const recentBannedIps = new Map(); // Store clientIp -> timestamp
|
||||
|
||||
function processConnection(clientIp, locationInfo, currentUsers, ws, callback) {
|
||||
function processConnection(clientIp, locationInfo, currentUsers, ws, request, callback) {
|
||||
const options = { year: "numeric", month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" };
|
||||
const connectionTime = new Date().toLocaleString([], options);
|
||||
|
||||
fetchBannedAS((bannedAS) => {
|
||||
if (bannedAS.some((as) => locationInfo.as?.includes(as))) {
|
||||
fetchBannedAS((bannedAS, bannedCountries) => {
|
||||
if ((bannedAS.some((as) => locationInfo.as?.includes(as))) || bannedAS.includes("*")) {
|
||||
const now = Date.now();
|
||||
const lastSeen = recentBannedIps.get(clientIp) || 0;
|
||||
|
||||
@@ -210,6 +223,18 @@ function processConnection(clientIp, locationInfo, currentUsers, ws, callback) {
|
||||
return callback("User banned");
|
||||
}
|
||||
|
||||
if (bannedCountries.some((c) => locationInfo.country?.includes(c))) {
|
||||
const now = Date.now();
|
||||
const lastSeen = recentBannedIps.get(clientIp) || 0;
|
||||
|
||||
if (now - lastSeen > 300 * 1000) {
|
||||
consoleCmd.logWarn(`Banned country list client kicked (${clientIp})`);
|
||||
recentBannedIps.set(clientIp, now);
|
||||
}
|
||||
|
||||
return callback("User banned");
|
||||
}
|
||||
|
||||
const userLocation =
|
||||
locationInfo && locationInfo.country !== undefined
|
||||
? [
|
||||
@@ -227,10 +252,10 @@ function processConnection(clientIp, locationInfo, currentUsers, ws, callback) {
|
||||
storage.connectedUsers.push({
|
||||
ip: clientIp, location: userLocation,
|
||||
isp: locationInfo?.isp, as: locationInfo?.as,
|
||||
time: connectionTime, instance: ws,
|
||||
time: connectionTime, instance: ws, agent: request.headers["user-agent"],
|
||||
});
|
||||
|
||||
consoleCmd.logInfo(`Web client \x1b[32mconnected\x1b[0m (${clientIp}) \x1b[90m[${currentUsers}]\x1b[0m Location: ${userLocationForLog}`);
|
||||
consoleCmd.logInfo(`Web client \x1b[32mconnected\x1b[0m (${clientIp}) \x1b[90m[${currentUsers}]\x1b[0m Location: ${userLocationForLog} | User Agent: ${request.headers["user-agent"]}`);
|
||||
|
||||
callback("User allowed");
|
||||
});
|
||||
@@ -269,19 +294,19 @@ function resolveDataBuffer(data) {
|
||||
|
||||
if (receivedData.length) dataHandler.handleData(wss, receivedData, rdsWss);
|
||||
}
|
||||
|
||||
function kickClient(ipAddress) {
|
||||
// Find the entry in connectedClients associated with the provided IP address
|
||||
const targetClient = storage.connectedUsers.find(client => client.ip === ipAddress);
|
||||
if (targetClient && targetClient.instance) {
|
||||
// Send a termination message to the client
|
||||
targetClient.instance.send('KICK');
|
||||
|
||||
// Close the WebSocket connection after a short delay to allow the client to receive the message
|
||||
setTimeout(() => {
|
||||
targetClient.instance.close();
|
||||
|
||||
const index = storage.connectedUsers.indexOf(targetClient);
|
||||
if (index !== -1) storage.connectedUsers.splice(index, 1);
|
||||
|
||||
consoleCmd.logInfo(`Web client kicked (${ipAddress})`);
|
||||
}, 500);
|
||||
}, 750);
|
||||
} else consoleCmd.logInfo(`Kicking client ${ipAddress} failed. No suitable client found.`);
|
||||
}
|
||||
|
||||
@@ -433,7 +458,7 @@ function getIpAddress(request) {
|
||||
const xff = request.headers['x-forwarded-for'];
|
||||
|
||||
if (xff && !isLocalhost(remoteIp) && !isTrustedProxy(remoteIp)) {
|
||||
consoleCmd.logSecurity(`Untrusted proxy tried to set X-Forwarded-For: ${xff} (remote: ${remoteIpRaw})`);
|
||||
consoleCmd.logWarn(`Untrusted proxy tried to set X-Forwarded-For: ${xff} (remote: ${remoteIpRaw})`);
|
||||
return remoteIp;
|
||||
}
|
||||
|
||||
@@ -442,10 +467,23 @@ function getIpAddress(request) {
|
||||
return remoteIp;
|
||||
}
|
||||
|
||||
function isAdmin(request) {
|
||||
if (request.session?.isAdminAuthenticated) return true;
|
||||
|
||||
const ip = getIpAddress(request);
|
||||
|
||||
if (adminIps.includes(ip)) {
|
||||
request.session.isAdminAuthenticated = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
authenticateWithXdrd, parseMarkdown, handleConnect,
|
||||
removeMarkdown, formatUptime, resolveDataBuffer,
|
||||
kickClient, checkLatency,
|
||||
antispamProtection, escapeHtml, findServerFiles,
|
||||
startPluginsWithDelay, getIpAddress
|
||||
startPluginsWithDelay, getIpAddress, isAdmin
|
||||
}
|
||||
+6
-16
@@ -1,18 +1,6 @@
|
||||
const terminalWidth = require('readline').createInterface({input: process.stdin, output: process.stdout}).output.columns;
|
||||
|
||||
console.log('\x1b[32m' + require('figlet').textSync("FM-DX Webserver"));
|
||||
console.log('\x1b[2mby (Noobish @ \x1b[4mFMDX.org\x1b[0m\x1b[32m\x1b[2m) + KubaPro010\x1b[0m');
|
||||
console.log("v" + require('../package.json').version)
|
||||
console.log('\x1b[90m' + '─'.repeat(terminalWidth - 1) + '\x1b[0m');
|
||||
|
||||
const { serverConfig } = require('./server_config');
|
||||
const tunnel = require('./tunnel');
|
||||
tunnel.download();
|
||||
|
||||
require("./device");
|
||||
|
||||
require('./stream/index');
|
||||
const startServer = require("./web");
|
||||
const { serverConfig } = require('./server_config');
|
||||
|
||||
{
|
||||
const helpers = require('./helpers');
|
||||
@@ -20,7 +8,9 @@ const startServer = require("./web");
|
||||
if (plugins.length > 0) setTimeout(helpers.startPluginsWithDelay, 3000, plugins, 3000);
|
||||
}
|
||||
|
||||
startServer(serverConfig.webserver.webserverIp === '0.0.0.0' ? 'localhost' : serverConfig.webserver.webserverIp);
|
||||
require('./stream/index');
|
||||
const start = require("./web");
|
||||
require("./enchanced_tuning");
|
||||
start(serverConfig.webserver.webserverIp);
|
||||
|
||||
tunnel.connect();
|
||||
require('./server_list').update();
|
||||
require('./server_list')();
|
||||
+13
-5
@@ -23,8 +23,11 @@ function parsePluginConfig(filePath) {
|
||||
|
||||
if (pluginConfig.frontEndPath) {
|
||||
const sourcePath = path.join(path.dirname(filePath), pluginConfig.frontEndPath);
|
||||
const destinationDir = path.join(__dirname, '../web/js/plugins', path.dirname(pluginConfig.frontEndPath));
|
||||
|
||||
const destinationDir = path.join(
|
||||
__dirname,
|
||||
'../web/js/plugins',
|
||||
path.relative(pluginsDir, path.dirname(sourcePath))
|
||||
);
|
||||
// Check if the source path exists
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
console.error(`Error: source path ${sourcePath} does not exist.`);
|
||||
@@ -77,9 +80,14 @@ if (process.platform === 'win32') {
|
||||
|
||||
const pluginConfigs = [];
|
||||
readJSFiles(pluginsDir).forEach(file => {
|
||||
const filePath = path.join(pluginsDir, file);
|
||||
const config = parsePluginConfig(filePath);
|
||||
if (Object.keys(config).length > 0) pluginConfigs.push(config);
|
||||
var filePath = path.join(pluginsDir, file);
|
||||
const dir = fs.statSync(filePath).isDirectory();
|
||||
if(dir) filePath = path.join(pluginsDir, file, file);
|
||||
|
||||
var config = parsePluginConfig(filePath);
|
||||
if(dir) config = {...config, prefix: `${file}/`}
|
||||
else config = {...config, prefix: ""}
|
||||
pluginConfigs.push(config);
|
||||
});
|
||||
|
||||
module.exports = pluginConfigs;
|
||||
|
||||
+36
-1
@@ -157,9 +157,12 @@ class RDSDecoder {
|
||||
this.rt0_errors = Array(64).fill("10");
|
||||
this.rt1 = Array(64).fill(' ');
|
||||
this.rt1_errors = Array(64).fill("10");
|
||||
this.lps = Array(64).fill(' ');
|
||||
this.lps_errors = Array(64).fill("10");
|
||||
this.data.ps = '';
|
||||
this.data.rt1 = '';
|
||||
this.data.rt0 = '';
|
||||
this.data.rt1 = '';
|
||||
this.data.lps = '';
|
||||
this.data.pty = 0;
|
||||
this.data.tp = 0;
|
||||
this.data.ta = 0;
|
||||
@@ -350,6 +353,38 @@ class RDSDecoder {
|
||||
this.data.rt_flag = 0;
|
||||
this.rt1_to_clear = true;
|
||||
}
|
||||
} else if (group === 15 && version == 0) {
|
||||
const idx = blockB & 7;
|
||||
|
||||
if(c_error < 2) {
|
||||
const err = Math.ceil(c_error * (10/3));
|
||||
const old_err = this.lps_errors[idx * 4];
|
||||
if(err < old_err) {
|
||||
this.lps[idx * 4] = decode_charset(blockC >> 8);
|
||||
this.lps[idx * 4 + 1] = decode_charset(blockC & 0xFF);
|
||||
this.lps_errors[idx * 4] = err;
|
||||
this.lps_errors[idx * 4 + 1] = err;
|
||||
}
|
||||
}
|
||||
if(d_error < 2) {
|
||||
const err = Math.ceil(d_error * (10/3));
|
||||
const old_err = this.lps_errors[idx * 4 + 2];
|
||||
if(err < old_err) {
|
||||
this.lps[idx * 4 + 2] = decode_charset(blockD >> 8);
|
||||
this.lps[idx * 4 + 3] = decode_charset(blockD & 0xFF);
|
||||
this.lps_errors[idx * 4 + 2] = err;
|
||||
this.lps_errors[idx * 4 + 3] = err;
|
||||
}
|
||||
}
|
||||
|
||||
var i = this.lps.indexOf("\r")
|
||||
while(i != -1) {
|
||||
this.lps[i] = " ";
|
||||
i = this.lps.indexOf("\r");
|
||||
}
|
||||
|
||||
this.data.lps = this.lps.join('');
|
||||
this.data.lps_errors = this.lps_errors.join(',');
|
||||
} else {
|
||||
// console.log(group, version)
|
||||
}
|
||||
|
||||
+24
-47
@@ -1,52 +1,29 @@
|
||||
var countries = [
|
||||
"Albania",
|
||||
"Estonia",
|
||||
"Algeria",
|
||||
"Ethiopia",
|
||||
"Andorra",
|
||||
"Angola",
|
||||
"Finland",
|
||||
"Armenia",
|
||||
"France",
|
||||
"Ascension Island",
|
||||
"Gabon",
|
||||
"Austria",
|
||||
"Gambia",
|
||||
"Azerbaijan",
|
||||
"Georgia",
|
||||
"Germany",
|
||||
"Bahrein",
|
||||
"Ghana",
|
||||
"Belarus",
|
||||
"Gibraltar",
|
||||
"Belgium",
|
||||
"Greece",
|
||||
"Benin",
|
||||
"Guinea",
|
||||
"Bosnia Herzegovina",
|
||||
"Guinea-Bissau",
|
||||
"Botswana",
|
||||
"Hungary",
|
||||
"Bulgaria",
|
||||
"Iceland",
|
||||
"Burkina Faso",
|
||||
"Iraq",
|
||||
"Burundi",
|
||||
"Ireland",
|
||||
"Cabinda",
|
||||
"Israel",
|
||||
"Cameroon",
|
||||
"Italy",
|
||||
"Jordan",
|
||||
"Cape Verde",
|
||||
"Albania", "Estonia",
|
||||
"Algeria", "Ethiopia",
|
||||
"Andorra", "Angola",
|
||||
"Finland", "Armenia",
|
||||
"France", "Ascension Island",
|
||||
"Gabon", "Austria",
|
||||
"Gambia", "Azerbaijan",
|
||||
"Georgia", "Germany",
|
||||
"Bahrein", "Ghana",
|
||||
"Belarus", "Gibraltar",
|
||||
"Belgium", "Greece",
|
||||
"Benin", "Guinea",
|
||||
"Bosnia Herzegovina", "Guinea-Bissau",
|
||||
"Botswana", "Hungary",
|
||||
"Bulgaria", "Iceland",
|
||||
"Burkina Faso", "Iraq",
|
||||
"Burundi", "Ireland",
|
||||
"Cabinda", "-",
|
||||
"Cameroon", "Italy",
|
||||
"Jordan", "Cape Verde",
|
||||
"Kazakhstan",
|
||||
"Central African Republic",
|
||||
"Kenya",
|
||||
"Chad",
|
||||
"Kosovo",
|
||||
"Comoros",
|
||||
"Kuwait",
|
||||
"DR Congo",
|
||||
"Kenya", "Chad",
|
||||
"Kosovo", "Comoros",
|
||||
"Kuwait", "DR Congo",
|
||||
"Kyrgyzstan",
|
||||
"Republic of Congo",
|
||||
"Latvia",
|
||||
@@ -402,7 +379,7 @@ const rdsEccD0D4Lut = [
|
||||
const rdsEccE0E5Lut = [
|
||||
// E0
|
||||
[
|
||||
"Germany", "Algeria", "Andorra", "Israel", "Italy",
|
||||
"Germany", "Algeria", "Andorra", "-", "Italy",
|
||||
"Belgium", "Russia", "Palestine", "Albania", "Austria",
|
||||
"Hungary", "Malta", "Germany", "", "Egypt"
|
||||
],
|
||||
|
||||
+1
-16
@@ -17,7 +17,6 @@ let serverConfig = {
|
||||
webserver: {
|
||||
webserverIp: "0.0.0.0",
|
||||
webserverPort: 8080,
|
||||
pe5pvbXdrGtkPort: null,
|
||||
banlist: [],
|
||||
chatEnabled: true,
|
||||
tuningLimit: false,
|
||||
@@ -90,20 +89,6 @@ let serverConfig = {
|
||||
si47xx: {
|
||||
agcControl: false
|
||||
},
|
||||
tunnel: {
|
||||
enabled: false,
|
||||
username: "",
|
||||
token: "",
|
||||
region: "pldx",
|
||||
lowLatencyMode: false,
|
||||
subdomain: "",
|
||||
httpName: "",
|
||||
httpPassword: "",
|
||||
community: {
|
||||
enabled: false,
|
||||
host: ""
|
||||
}
|
||||
},
|
||||
plugins: [],
|
||||
device: 'tef',
|
||||
defaultFreq: 87.5,
|
||||
@@ -126,7 +111,7 @@ let serverConfig = {
|
||||
antennaNoUsersDelay: false,
|
||||
trustedProxies: [],
|
||||
webRtc: {
|
||||
flags: {disable3las: false},
|
||||
flags: {disablews: false},
|
||||
audio: {}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -81,4 +81,4 @@ function update() {
|
||||
timeoutID = setInterval(sendKeepalive, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
module.exports.update = update;
|
||||
module.exports = update;
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
function checkFFmpeg() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const checkFFmpegProcess = spawn('ffmpeg', ['-version'], {
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
});
|
||||
|
||||
checkFFmpegProcess.on('error', () => {
|
||||
resolve(require('ffmpeg-static'));
|
||||
});
|
||||
|
||||
checkFFmpegProcess.on('exit', (code) => {
|
||||
if (code === 0) resolve('ffmpeg');
|
||||
else resolve(require('ffmpeg-static'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = checkFFmpeg;
|
||||
+19
-8
@@ -6,8 +6,24 @@ const { serverConfig, configExists } = require('../server_config');
|
||||
if (!configExists() || !serverConfig.audio.audioDevice) return;
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
const { logDebug, logError, logInfo, logWarn, logFfmpeg } = require('../console');
|
||||
const checkFFmpeg = require('./checkFFmpeg');
|
||||
const { logDebug, logError, logInfo, logWarn } = require('../console');
|
||||
|
||||
const checkFFmpeg = function() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const checkFFmpegProcess = spawn('ffmpeg', ['-version'], {
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
});
|
||||
|
||||
checkFFmpegProcess.on('error', () => {
|
||||
resolve(require('ffmpeg-static'));
|
||||
});
|
||||
|
||||
checkFFmpegProcess.on('exit', (code) => {
|
||||
if (code === 0) resolve('ffmpeg');
|
||||
else resolve(require('ffmpeg-static'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const consoleLogTitle = '[Audio Stream]';
|
||||
|
||||
@@ -24,8 +40,7 @@ checkFFmpeg().then((ffmpegPath) => {
|
||||
logInfo(`${consoleLogTitle} Using ${ffmpegPath === 'ffmpeg' ? 'system-installed FFmpeg' : 'ffmpeg-static'}`);
|
||||
logInfo(`${consoleLogTitle} Starting audio stream on device: \x1b[35m${serverConfig.audio.audioDevice}\x1b[0m`);
|
||||
|
||||
const sampleRate = Number(serverConfig.audio.sampleRate || 44100); // Maybe even do 32 khz, we do not need higher than 15 khz precision
|
||||
|
||||
const sampleRate = Number(serverConfig.audio.sampleRate || 32000);
|
||||
const channels = Number(serverConfig.audio.audioChannels || 2);
|
||||
|
||||
let ffmpeg = null;
|
||||
@@ -80,11 +95,8 @@ checkFFmpeg().then((ffmpegPath) => {
|
||||
|
||||
ffmpeg.stdout.pipe(audio_pipe, { end: false });
|
||||
|
||||
connectMessage(`${consoleLogTitle} Connected FFmpeg → MP3 → audioWss`);
|
||||
|
||||
ffmpeg.stderr.on('data', (data) => {
|
||||
const msg = data.toString();
|
||||
logFfmpeg(`[FFmpeg stderr]: ${msg}`);
|
||||
|
||||
// Detect frozen timestamps
|
||||
const match = msg.match(/time=(\d\d):(\d\d):(\d\d\.\d+)/);
|
||||
@@ -137,7 +149,6 @@ checkFFmpeg().then((ffmpegPath) => {
|
||||
});
|
||||
|
||||
launchFFmpeg();
|
||||
|
||||
}).catch((err) => {
|
||||
logError(`${consoleLogTitle} Error: ${err.message}`);
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const exec = require('child_process').exec;
|
||||
const fs = require('fs').promises; // Use the Promise-based fs API
|
||||
const ffmpeg = require('ffmpeg-static');
|
||||
const filePath = '/proc/asound/cards';
|
||||
const platform = process.platform;
|
||||
|
||||
function parseAudioDevice(options, callback) {
|
||||
let videoDevices = [];
|
||||
let audioDevices = [];
|
||||
let isVideo = true;
|
||||
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = null;
|
||||
}
|
||||
options = options || {};
|
||||
const ffmpegPath = `"${ffmpeg.replace(/\\/g, '\\\\')}"`;
|
||||
const callbackExists = typeof callback === 'function';
|
||||
|
||||
const execute = async (fulfill, reject) => {
|
||||
try {
|
||||
if (platform === 'linux') {
|
||||
try {
|
||||
const data = await fs.readFile(filePath, 'utf8');
|
||||
const regex = /\[([^\]]+)\]/g;
|
||||
const matches = (data.match(regex) || []).map(match => 'hw:' + match.replace(/\s+/g, '').slice(1, -1));
|
||||
|
||||
matches.forEach(match => {
|
||||
if (typeof match === 'string') audioDevices.push({ name: match });
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`Error reading file: ${err.message}`);
|
||||
}
|
||||
|
||||
// Linux doesn't support the `-list_devices` ffmpeg command like macOS/Windows,
|
||||
// so skip the ffmpeg exec for Linux
|
||||
const result = { videoDevices: [], audioDevices };
|
||||
if (callbackExists) return callback(result);
|
||||
return fulfill(result);
|
||||
}
|
||||
|
||||
let inputDevice, prefix, audioSeparator, alternativeName, deviceParams;
|
||||
|
||||
switch (platform) {
|
||||
case 'win32':
|
||||
inputDevice = 'dshow';
|
||||
prefix = /\[dshow/;
|
||||
audioSeparator = /DirectShow\saudio\sdevices/;
|
||||
alternativeName = /Alternative\sname\s*?"(.*?)"/;
|
||||
deviceParams = /"(.*?)"/;
|
||||
break;
|
||||
case 'darwin':
|
||||
inputDevice = 'avfoundation';
|
||||
prefix = /^\[AVFoundation/;
|
||||
audioSeparator = /AVFoundation\saudio\sdevices/;
|
||||
deviceParams = /^\[AVFoundation.*?]\s\[(\d+)]\s(.*)$/;
|
||||
break;
|
||||
}
|
||||
|
||||
exec(`${ffmpegPath} -f ${inputDevice} -list_devices true -i ""`, (err, stdout, stderr) => {
|
||||
stderr.split("\n")
|
||||
.filter(line => line.search(prefix) > -1)
|
||||
.forEach(line => {
|
||||
const deviceList = isVideo ? videoDevices : audioDevices;
|
||||
if (line.search(audioSeparator) > -1) {
|
||||
isVideo = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === 'win32' && line.search(/Alternative\sname/) > -1) {
|
||||
const lastDevice = deviceList[deviceList.length - 1];
|
||||
const alt = line.match(alternativeName);
|
||||
if (lastDevice && alt) lastDevice.alternativeName = alt[1];
|
||||
return;
|
||||
}
|
||||
|
||||
const params = line.match(deviceParams);
|
||||
if (params) {
|
||||
let device;
|
||||
switch (platform) {
|
||||
case 'win32':
|
||||
device = { name: params[1] };
|
||||
break;
|
||||
case 'darwin':
|
||||
device = { id: parseInt(params[1]), name: params[2] };
|
||||
break;
|
||||
}
|
||||
deviceList.push(device);
|
||||
}
|
||||
});
|
||||
|
||||
audioDevices = audioDevices.filter(device => device.name !== undefined);
|
||||
const result = { videoDevices, audioDevices };
|
||||
if (callbackExists) return callback(result);
|
||||
return fulfill(result);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Unexpected error:', err);
|
||||
if (callbackExists) callback({ videoDevices: [], audioDevices: [] });
|
||||
else reject(err);
|
||||
}
|
||||
};
|
||||
|
||||
if (callbackExists) execute();
|
||||
else return new Promise(execute);
|
||||
}
|
||||
|
||||
module.exports = parseAudioDevice;
|
||||
@@ -1,4 +1,4 @@
|
||||
const tunerProfiles = [
|
||||
module.exports = [
|
||||
{
|
||||
id: 'tef',
|
||||
label: 'TEF668x',
|
||||
@@ -76,5 +76,3 @@ const tunerProfiles = [
|
||||
], details: ''
|
||||
}
|
||||
];
|
||||
|
||||
module.exports = tunerProfiles;
|
||||
@@ -1,101 +0,0 @@
|
||||
const { logDebug, logError, logInfo, logWarn, logFfmpeg } = require('./console');
|
||||
const { serverConfig } = require('./server_config');
|
||||
const { Readable } = require('stream');
|
||||
const { finished } = require('stream/promises');
|
||||
const fs = require('fs/promises');
|
||||
const fs2 = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const ejs = require('ejs');
|
||||
const { spawn } = require('child_process');
|
||||
const readline = require('readline');
|
||||
|
||||
const fileExists = path => new Promise(resolve => fs.access(path, fs.constants.F_OK).then(() => resolve(true)).catch(() => resolve(false)));
|
||||
|
||||
async function download() {
|
||||
if (serverConfig.tunnel?.enabled === true) {
|
||||
const librariesDir = path.resolve(__dirname, '../libraries');
|
||||
if (!await fileExists(librariesDir)) await fs.mkdir(librariesDir);
|
||||
const frpcPath = path.resolve(librariesDir, 'frpc' + (os.platform() === 'win32' ? '.exe' : ''));
|
||||
if (!await fileExists(frpcPath)) {
|
||||
logInfo('frpc binary, required for tunnel is not available. Downloading now...');
|
||||
const frpcFileName = `frpc_${os.platform}_${os.arch}` + (os.platform() === 'win32' ? '.exe' : '');
|
||||
|
||||
try {
|
||||
const res = await fetch('https://fmtuner.org/binaries/' + frpcFileName);
|
||||
if (res.status === 404) throw new Error('404 error');
|
||||
const stream = fs2.createWriteStream(frpcPath);
|
||||
await finished(Readable.fromWeb(res.body).pipe(stream));
|
||||
} catch (err) {
|
||||
logError('Failed to download frpc, reason: ' + err);
|
||||
return;
|
||||
}
|
||||
logInfo('Downloading of frpc is completed.')
|
||||
if (os.platform() === 'linux' || os.platform() === 'darwin') await fs.chmod(frpcPath, 0o770);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function connect() {
|
||||
if (serverConfig.tunnel?.enabled === true) {
|
||||
const librariesDir = path.resolve(__dirname, '../libraries');
|
||||
const frpcPath = path.resolve(librariesDir, 'frpc' + (os.platform() === 'win32' ? '.exe' : ''));
|
||||
|
||||
const cfg = ejs.render(frpcConfigTemplate, {
|
||||
cfg: serverConfig.tunnel,
|
||||
host: serverConfig.tunnel.community.enabled ? serverConfig.tunnel.community.host : ((serverConfig.tunnel.region == "pldx") ? "pldx.duckdns.org" : (serverConfig.tunnel.region + ".fmtuner.org")),
|
||||
server: {
|
||||
port: serverConfig.webserver.webserverPort
|
||||
}
|
||||
});
|
||||
const cfgPath = path.resolve(librariesDir, 'frpc.toml');
|
||||
await fs.writeFile(cfgPath, cfg);
|
||||
const child = spawn(frpcPath, ['-c', cfgPath]);
|
||||
process.on('exit', () => child.kill());
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: child.stdout,
|
||||
terminal: false
|
||||
});
|
||||
|
||||
rl.on('line', (line) => {
|
||||
if (line.includes('connect to server error')) logError('Failed to connect to tunnel, reason: ' + line.substring(line.indexOf(': ')+2));
|
||||
else if (line.includes('invalid user or token')) logError('Failed to connect to tunnel, reason: invalid user or token');
|
||||
else if (line.includes('start proxy success')) logInfo('Tunnel established successfully');
|
||||
else if (line.includes('login to server success')) logInfo('Connection to tunnel server was successful');
|
||||
else logDebug('Tunnel log:', line);
|
||||
});
|
||||
|
||||
child.on('error', (err) => {
|
||||
logError('Failed to start tunnel process:', err);
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
logInfo(`Tunnel process exited with code ${code}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const frpcConfigTemplate = `
|
||||
serverAddr = "<%= host %>"
|
||||
serverPort = 7000
|
||||
loginFailExit = false
|
||||
log.disablePrintColor = true
|
||||
user = "<%= cfg.username %>"
|
||||
metadatas.token = "<%= cfg.token %>"
|
||||
<% if (cfg.lowLatencyMode) { %>
|
||||
transport.protocol = "kcp"
|
||||
<% } %>
|
||||
|
||||
[[proxies]]
|
||||
name = "web"
|
||||
type = "http"
|
||||
localPort = <%= server.port %>
|
||||
subdomain = "<%= cfg.subdomain %>"
|
||||
<% if (cfg.httpName != "") { %>
|
||||
httpUser = "<%= cfg.httpName %>"
|
||||
httpPassword = "<%= cfg.httpPassword %>"
|
||||
<% } %>
|
||||
`;
|
||||
|
||||
module.exports = { connect, download };
|
||||
+35
-46
@@ -66,38 +66,30 @@ wss.on('connection', (ws, request) => {
|
||||
|
||||
// Per-IP limit connection open
|
||||
if (clientIp) {
|
||||
const isLocalIp = (clientIp === '127.0.0.1' || clientIp === '::1' || clientIp.startsWith('192.168.') || clientIp.startsWith('10.') || clientIp.startsWith('172.16.'));
|
||||
if (!isLocalIp) {
|
||||
if (!ipConnectionCounts.has(clientIp)) ipConnectionCounts.set(clientIp, 0);
|
||||
const currentCount = ipConnectionCounts.get(clientIp);
|
||||
if (currentCount >= MAX_CONNECTIONS_PER_IP) {
|
||||
ws.close(1008, 'Too many open connections from this IP');
|
||||
const lastLogTime = ipLogTimestamps.get(clientIp) || 0;
|
||||
const now = Date.now();
|
||||
if (now - lastLogTime > IP_LOG_INTERVAL_MS) {
|
||||
logWarn(`Web client \x1b[31mclosed: limit exceeded\x1b[0m (${clientIp}) \x1b[90m[${currentUsers}]`);
|
||||
ipLogTimestamps.set(clientIp, now);
|
||||
} return;
|
||||
} ipConnectionCounts.set(clientIp, currentCount + 1);
|
||||
}
|
||||
if (!ipConnectionCounts.has(clientIp)) ipConnectionCounts.set(clientIp, 0);
|
||||
const currentCount = ipConnectionCounts.get(clientIp);
|
||||
if (currentCount >= MAX_CONNECTIONS_PER_IP) {
|
||||
ws.close(1008, 'Too many open connections from this IP');
|
||||
const lastLogTime = ipLogTimestamps.get(clientIp) || 0;
|
||||
const now = Date.now();
|
||||
if (now - lastLogTime > IP_LOG_INTERVAL_MS) {
|
||||
logWarn(`Web client \x1b[31mclosed: limit exceeded\x1b[0m (${clientIp}) \x1b[90m[${currentUsers}]`);
|
||||
ipLogTimestamps.set(clientIp, now);
|
||||
} return;
|
||||
} ipConnectionCounts.set(clientIp, currentCount + 1);
|
||||
}
|
||||
|
||||
if(currentUsers >= MAX_USERS) {
|
||||
// TODO: give a nice fucking unwelcome message on the ui (we kindly ask you to FUCK OFF?)
|
||||
ws.send("a0"); // This means not authenticated in XDR
|
||||
ws.close(1008, 'Too many users using this server at the moment.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (clientIp !== '127.0.0.1' ||
|
||||
(request.socket && request.socket.remoteAddress && request.socket.remoteAddress !== '::ffff:127.0.0.1') ||
|
||||
(request.headers && request.headers['origin'] && request.headers['origin'].trim() !== '')) {
|
||||
currentUsers++;
|
||||
}
|
||||
if (clientIp !== '127.0.0.1') currentUsers++;
|
||||
|
||||
if (timeoutAntenna) clearTimeout(timeoutAntenna);
|
||||
|
||||
helpers.handleConnect(clientIp, currentUsers, ws, (result) => {
|
||||
helpers.handleConnect(clientIp, currentUsers, ws, request, (result) => {
|
||||
if (result === "User banned") {
|
||||
ws.close(1008, 'Banned IP');
|
||||
return;
|
||||
@@ -112,9 +104,15 @@ wss.on('connection', (ws, request) => {
|
||||
|
||||
ws.on('message', (message) => {
|
||||
const command = helpers.antispamProtection(message, clientIp, ws, userCommands, lastWarn, userCommandHistory, '18', 'text', 16 * 1024);
|
||||
if(!command) return;
|
||||
|
||||
if(command.startsWith("PING")) {
|
||||
ws.send(command);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!clientIp.includes("127.0.0.1")) {
|
||||
if (((command.startsWith('X') || command.startsWith('Y')) && !request.session.isAdminAuthenticated) ||
|
||||
if (((command.startsWith('X') || command.startsWith('Y')) && !helpers.isAdmin(req)) ||
|
||||
((command.startsWith('F') || command.startsWith('W')) && serverConfig.bwSwitch === false)) {
|
||||
logWarn(`User \x1b[90m${clientIp}\x1b[0m attempted to send a potentially dangerous command: ${command.slice(0, 64)}.`);
|
||||
return;
|
||||
@@ -123,18 +121,21 @@ wss.on('connection', (ws, request) => {
|
||||
|
||||
if (command.includes("\'")) return;
|
||||
|
||||
const { isAdminAuthenticated, isTuneAuthenticated } = request.session || {};
|
||||
const isAdminAuthenticated = helpers.isAdmin(request)
|
||||
const { isTuneAuthenticated } = request.session || {};
|
||||
|
||||
if (command.startsWith('w') && (isAdminAuthenticated || isTuneAuthenticated)) {
|
||||
switch (command) {
|
||||
case 'wL1':
|
||||
if (isAdminAuthenticated) serverConfig.lockToAdmin = true;
|
||||
send_to_xdr("wL1\n");
|
||||
break;
|
||||
if (isAdminAuthenticated) {
|
||||
serverConfig.lockToAdmin = true;
|
||||
send_to_xdr("wL1\n");
|
||||
} break;
|
||||
case 'wL0':
|
||||
if (isAdminAuthenticated) serverConfig.lockToAdmin = false;
|
||||
send_to_xdr("wL0\n");
|
||||
break;
|
||||
if (isAdminAuthenticated) {
|
||||
serverConfig.lockToAdmin = false;
|
||||
send_to_xdr("wL0\n");
|
||||
} break;
|
||||
case 'wT0':
|
||||
serverConfig.publicTuner = true;
|
||||
if(!isAdminAuthenticated) tunerLockTracker.delete(ws);
|
||||
@@ -163,24 +164,12 @@ wss.on('connection', (ws, request) => {
|
||||
ws.on('close', (code) => {
|
||||
// Per-IP limit connection closed
|
||||
if (clientIp) {
|
||||
const isLocalIp = (
|
||||
clientIp === '127.0.0.1' ||
|
||||
clientIp === '::1' ||
|
||||
clientIp.startsWith('192.168.') ||
|
||||
clientIp.startsWith('10.') ||
|
||||
clientIp.startsWith('172.16.')
|
||||
);
|
||||
if (!isLocalIp) {
|
||||
const current = ipConnectionCounts.get(clientIp) || 1;
|
||||
ipConnectionCounts.set(clientIp, Math.max(0, current - 1));
|
||||
}
|
||||
const current = ipConnectionCounts.get(clientIp) || 1;
|
||||
ipConnectionCounts.set(clientIp, Math.max(0, current - 1));
|
||||
}
|
||||
|
||||
if (clientIp !== '127.0.0.1' ||
|
||||
(request.socket && request.socket.remoteAddress && request.socket.remoteAddress !== '::ffff:127.0.0.1') ||
|
||||
(request.headers && request.headers['origin'] && request.headers['origin'].trim() !== '')) {
|
||||
currentUsers--;
|
||||
} dataHandler.showOnlineUsers(currentUsers);
|
||||
if (clientIp !== '127.0.0.1') currentUsers--;
|
||||
dataHandler.showOnlineUsers(currentUsers);
|
||||
|
||||
const index = storage.connectedUsers.findIndex(user => user.ip === clientIp);
|
||||
if (index !== -1) storage.connectedUsers.splice(index, 1);
|
||||
@@ -250,7 +239,7 @@ pluginsWss.on('connection', (ws, request) => {
|
||||
|
||||
ws.on('message', message => {
|
||||
// Anti-spam
|
||||
const msg2 = helpers.antispamProtection(message, clientIp, ws, userCommands, lastWarn, userCommandHistory, '10', 'data_plugins');
|
||||
const msg2 = helpers.antispamProtection(message, clientIp, ws, userCommands, lastWarn, userCommandHistory, '10', 'data_plugins', 1024 * 1024 * 2);
|
||||
if(!msg2) return;
|
||||
|
||||
try {
|
||||
|
||||
@@ -61,7 +61,6 @@ xdr.on('connection', async (ws) => {
|
||||
|
||||
|
||||
ws.send(`OK\n`)
|
||||
ws.send(`$fmdx-webserver,${require('../package.json').version},${serverConfig.webserver.pe5pvbXdrGtkPort ?? serverConfig.webserver.webserverPort},/audio\n`); // Sjef's bullshit
|
||||
currentUsers++;
|
||||
send_xdr_online(initialData.users); // Broadcast
|
||||
ws.send(`T${initialData.freq * 1000}\n`);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Template
|
||||
|
||||
```
|
||||
serverAddr = "<%= host %>"
|
||||
serverPort = 7000
|
||||
loginFailExit = false
|
||||
log.disablePrintColor = true
|
||||
user = "<%= cfg.username %>"
|
||||
metadatas.token = "<%= cfg.token %>"
|
||||
<% if (cfg.lowLatencyMode) { %>
|
||||
transport.protocol = "kcp"
|
||||
<% } %>
|
||||
|
||||
[[proxies]]
|
||||
name = "web"
|
||||
type = "http"
|
||||
localPort = <%= server.port %>
|
||||
subdomain = "<%= cfg.subdomain %>"
|
||||
<% if (cfg.httpName != "") { %>
|
||||
httpUser = "<%= cfg.httpName %>"
|
||||
httpPassword = "<%= cfg.httpPassword %>"
|
||||
<% } %>
|
||||
```
|
||||
+3
-2
@@ -20,10 +20,11 @@
|
||||
<div class="panel-100 p-10">
|
||||
<br>
|
||||
<i class="text-big fa-solid fa-exclamation-triangle color-4"></i>
|
||||
<p>Service refused, please try again later.</p>
|
||||
|
||||
<% if (reason) { %>
|
||||
<p><strong>Reason:</strong> <%= reason %></p>
|
||||
<p><%= reason %></p>
|
||||
<% } else { %>
|
||||
<p>Service refused, please try again later.</p>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+10
-13
@@ -6,6 +6,8 @@
|
||||
<link href="css/flags.min.css" type="text/css" rel="stylesheet">
|
||||
<link href="css/libs/fontawesome.css" type="text/css" rel="stylesheet">
|
||||
<link href="css/libs/jquery-ui.min.css" type="text/css" rel="stylesheet">
|
||||
<link href="css/enchanced_tuning.css" type="text/css" rel="stylesheet">
|
||||
<!--<link href="css/libs/jquery-ui.theme.min.css" type="text/css" rel="stylesheet">-->
|
||||
<script src="js/libs/jquery.min.js"></script>
|
||||
<script src="js/libs/jquery-ui.min.js"></script>
|
||||
<script src="js/libs/chart.umd.min.js"></script>
|
||||
@@ -18,24 +20,18 @@
|
||||
|
||||
<meta property="og:title" content="FM-DX WebServer [<%= tunerName %>]">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:image" content="https://flerken.zapto.org:5000/img/webserver_icon.png">
|
||||
<meta property="og:image" content="https://data.fmtuner.net/img/webserver_icon.png">
|
||||
<meta property="og:description" content="Server description: <%= tunerDescMeta %>.">
|
||||
|
||||
<script src="js/3las/util/3las.helpers.js"></script>
|
||||
<script src="js/3las/util/3las.logging.js"></script>
|
||||
<script src="js/3las/fallback/3las.liveaudioplayer.js"></script>
|
||||
<script src="js/3las/fallback/3las.formatreader.js"></script>
|
||||
<script src="js/3las/fallback/formats/3las.formatreader.mpeg.js"></script>
|
||||
<script src="js/3las/fallback/formats/3las.formatreader.wav.js"></script>
|
||||
<script src="js/3las/util/3las.websocketclient.js"></script>
|
||||
<script src="js/3las/fallback/3las.fallback.js"></script>
|
||||
<script src="js/3las/3las.js"></script>
|
||||
<script src="js/audio.js"></script>
|
||||
<script src="js/rtc-audio.js"></script>
|
||||
<!-- Audio streaming -->
|
||||
<script src="js/audio/mp3_player.js"></script>
|
||||
<script src="js/audio/main.js"></script>
|
||||
<script type="text/javascript">
|
||||
document.ontouchmove = function(e) {
|
||||
window.addEventListener('load', Init, false);
|
||||
document.ontouchmove = function(e) { // Why?
|
||||
e.preventDefault();
|
||||
}
|
||||
<script src="js/rtc-audio.js"></script>
|
||||
</script>
|
||||
</head>
|
||||
|
||||
@@ -564,6 +560,7 @@
|
||||
<div id="toast-container" aria-live="polite"></div>
|
||||
<script src="js/websocket.js"></script>
|
||||
<script src="js/webserver.js"></script>
|
||||
<script src="js/enchanced_tuning.js"></script>
|
||||
<% if (!noPlugins) { %>
|
||||
<% plugins?.forEach(function(plugin) { %>
|
||||
<script src="js/plugins/<%= plugin %>"></script>
|
||||
|
||||
+45
-669
@@ -13,526 +13,61 @@
|
||||
</head>
|
||||
<body>
|
||||
<div id="toast-container"></div>
|
||||
<div class="wrapper-outer wrapper-full wrapper-outer-static">
|
||||
<div id="navigation" class="sidenav flex-container flex-phone">
|
||||
<div class="sidenav-content">
|
||||
<h1 class="top-25">Settings</h1>
|
||||
<ul class="nav" role="tablist" style="border-radius: 15px 15px 0 0;">
|
||||
<li role="tab" data-panel="dashboard" aria-selected="true" tabindex="0">
|
||||
<a href="#" role="tab" aria-controls="dashboard"><i class="fa-solid fa-fw fa-chart-line"></i> Dashboard</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="tuner" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="tuner"><i class="fa-solid fa-fw fa-radio"></i> Tuner</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="audio" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="audio"><i class="fa-solid fa-fw fa-volume-high"></i> Audio</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="webserver" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="webserver"><i class="fa-solid fa-fw fa-server"></i> Webserver</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="identification" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="identification"><i class="fa-solid fa-fw fa-circle-info"></i> Identification & Map</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="plugins-tab" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="plugins-tab"><i class="fa-solid fa-fw fa-puzzle-piece"></i> Plugins</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="users" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="users"><i class="fa-solid fa-fw fa-user"></i> User management</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="startup" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="startup"><i class="fa-solid fa-fw fa-plug"></i> Startup</a>
|
||||
</li>
|
||||
<li role="tab" data-panel="extras" tabindex="0">
|
||||
<a href="#" role="tab" tabindex="-1" aria-controls="extras"><i class="fa-solid fa-fw fa-star"></i> Extras</a>
|
||||
</li>
|
||||
<div id="wrapper" class="panel-full">
|
||||
<div class="m-0 no-bg">
|
||||
<h2>Dashboard</h2>
|
||||
|
||||
<div class="admin-quick-dashboard top-25">
|
||||
<div class="icon tooltip" role="button" aria-label="Go back to the main screen" tabindex="0" data-tooltip="Go back to the main screen" onclick="document.location.href='./'">
|
||||
<i class="fa-solid fa-arrow-left"></i>
|
||||
</div>
|
||||
<div class="icon tooltip" id="submit-config" role="button" aria-label="Save settings" tabindex="0" data-tooltip="Save settings" onclick="submitConfig()">
|
||||
<i class="fa-solid fa-save"></i>
|
||||
</div>
|
||||
<div class="icon tooltip logout-link" role="button" aria-label="Sign out" tabindex="0" data-tooltip="Sign out">
|
||||
<i class="fa-solid fa-sign-out"></i>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
<div class="panel-100-real m-0 p-10 no-bg">
|
||||
<p class="color-4">Feel free to contact us on <a href="https://discord.gg/ZAVNdS74mC" target="_blank"><strong class="color-5"><i class="fa-brands fa-discord"></i> Discord</strong></a> for community support.</p>
|
||||
<a href="https://github.com/noobishsvk/fm-dx-webserver" target="_blank" class="text-small">Version: <span class="version-string color-4"></span></a>
|
||||
</div>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="sidenav-close text-medium-big hover-brighten flex-center color-4 modal-panel-sidebar" role="button" onclick="toggleNav()" aria-label="Toggle navigation" tabindex="0"><i class="fa-solid fa-chevron-left"></i></div>
|
||||
</div>
|
||||
<div id="wrapper" class="setup-wrapper admin-wrapper panel-full">
|
||||
<div class="panel-full" style="margin-top: -20px; border-radius: 0; padding-left: 20px;padding-right: 20px;">
|
||||
<div class="panel-full tab-content no-bg m-0" id="dashboard" role="tabpanel">
|
||||
<h2>Dashboard</h2>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= onlineUsers %></span>
|
||||
<p>Online users</p>
|
||||
</div>
|
||||
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= memoryUsage %></span>
|
||||
<span class="text-small color-4" style="display: block; font-size: 1em; font-weight: 600; line-height: 0;">(<%= memoryHeap %> heap)</span>
|
||||
<p>Memory usage</p>
|
||||
</div>
|
||||
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= processUptime %></span>
|
||||
<p >Uptime</p>
|
||||
</div>
|
||||
<div class="flex-container">
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= onlineUsers %></span>
|
||||
<p>Online users</p>
|
||||
</div>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20" style="overflow-x: auto;">
|
||||
<h3>Current users</h3>
|
||||
<table class="table-big">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>IP Address</th>
|
||||
<th>Location</th>
|
||||
<th>Online since</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% if (connectedUsers.length > 0) { %>
|
||||
<% connectedUsers.forEach(user => { %>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://dnschecker.org/ip-location.php?ip=<%= user.ip.replace('::ffff:', '') %>" target="_blank">
|
||||
<%= user.ip.replace('::ffff:', '') %>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<%= user.location %><% if (user.isp) { %> (<%= user.isp %>)<% } %>
|
||||
</td>
|
||||
<td><%= user.time %></td>
|
||||
<td><a href="./kick?ip=<%= user.ip %>">Kick</a></td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
<% } else { %>
|
||||
<tr>
|
||||
<td colspan="4" style="text-align: center">No users online</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= memoryUsage %></span>
|
||||
<span class="text-small color-4" style="display: block; font-size: 1em; font-weight: 600; line-height: 0;">(<%= memoryHeap %> heap)</span>
|
||||
<p>Memory usage</p>
|
||||
</div>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20">
|
||||
<h3>Quick settings</h3>
|
||||
<div class="flex-container flex-center" style="margin: 30px;">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Unlocked Tuner', id: 'publicTuner'}) %>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Admin lock', id: 'lockToAdmin'}) %><br>
|
||||
</div>
|
||||
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Tune password', id: 'password-tunePass', password: true}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Admin password', id: 'password-adminPass', password: true}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20 bottom-20">
|
||||
<h3>Console</h3>
|
||||
<% if (consoleOutput && consoleOutput.length > 0) { %>
|
||||
<div class="panel-100 auto br-5 p-10 text-small text-left top-10" id="console-output">
|
||||
<% consoleOutput.forEach(function(log) { %>
|
||||
<pre class="m-0" style="white-space:pre-wrap;"><%= log %></pre>
|
||||
<% }); %>
|
||||
</div>
|
||||
<% } else { %>
|
||||
<p>No console output available.</p>
|
||||
<% } %>
|
||||
</div>
|
||||
<div class="panel-33 p-20">
|
||||
<span class="text-medium-big color-5"><%= processUptime %></span>
|
||||
<p >Uptime</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full tab-content no-bg m-0" id="audio" role="tabpanel">
|
||||
<h2>Audio settings</h2>
|
||||
|
||||
<div class="flex-container contains-dropdown">
|
||||
<div class="panel-33 p-bottom-20">
|
||||
<h3>Device</h3>
|
||||
<p>Your audio device port.<br>
|
||||
<span class="text-gray">This is where your tuner is plugged in.</span>
|
||||
</p>
|
||||
|
||||
<%- include('_components', {
|
||||
component: 'dropdown',
|
||||
id: 'audioList',
|
||||
inputId: 'audio-audioDevice',
|
||||
label: 'Audio device',
|
||||
cssClass: '',
|
||||
placeholder: 'Choose your audio device',
|
||||
options: [
|
||||
...videoDevices.map(device => ({
|
||||
value: device.name,
|
||||
label: `${device.name}`
|
||||
})),
|
||||
...audioDevices.map(device => ({
|
||||
value: device.name,
|
||||
label: `${device.name}`
|
||||
}))
|
||||
]
|
||||
}) %>
|
||||
</div>
|
||||
<div class="panel-33 p-bottom-20">
|
||||
<h3>Channels</h3>
|
||||
<p>Audio channel count.<br>
|
||||
<span class="text-gray">Choose between Mono / Stereo.</span>
|
||||
</p>
|
||||
<%- include('_components', { component: 'dropdown', id: 'audio-channels-dropdown', inputId: 'audio-audioChannels', label: 'Audio channels', cssClass: '', placeholder: 'Stereo',
|
||||
options: [
|
||||
{ value: '2', label: 'Stereo' },
|
||||
{ value: '1', label: 'Mono' }
|
||||
]
|
||||
}) %><br>
|
||||
</div>
|
||||
<div class="panel-33 p-bottom-20">
|
||||
<h3>Bitrate</h3>
|
||||
<p>The bitrate of the mp3 audio.<br>
|
||||
<span class="text-gray">Minimum: 64 Kbps • Maximum: 320 Kbps</span>
|
||||
</p>
|
||||
<%- include('_components', { component: 'dropdown', id: 'audio-quality-dropdown', inputId: 'audio-audioBitrate', label: 'Audio quality', cssClass: '', placeholder: '128kbps (standard)',
|
||||
options: [
|
||||
{ value: '64k', label: '64kbps (lowest quality)' },
|
||||
{ value: '96k', label: '96kbps (low quality)' },
|
||||
{ value: '128k', label: '128kbps (standard)' },
|
||||
{ value: '192k', label: '192kbps (high quality)' },
|
||||
{ value: '256k', label: '256kbps (very high quality)' },
|
||||
{ value: '320k', label: '320kbps (ultra quality)' }
|
||||
]
|
||||
}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="webserver" role="tabpanel">
|
||||
<h2>Webserver settings</h2>
|
||||
<div class="flex-container contains-dropdown">
|
||||
<div class="panel-50 p-bottom-20" style="padding-left: 20px; padding-right: 20px;">
|
||||
<h3>Connection</h3>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '0.0.0.0', label: 'Webserver IP', id: 'webserver-webserverIp'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '8080', label: 'Webserver port', id: 'webserver-webserverPort'}) %><br>
|
||||
</div>
|
||||
<div class="panel-50 p-bottom-20">
|
||||
<h3>Design</h3>
|
||||
<h4>Background image</h4>
|
||||
<%- include('_components', {component: 'text', cssClass: 'br-15', placeholder: 'Direct image link', label: 'Image link', id: 'webserver-bgImage'}) %><br>
|
||||
|
||||
<h4 class="top-25">Themes</h4>
|
||||
<%- include('_components', { component: 'dropdown', id: 'server-theme-selector', inputId: 'webserver-defaultTheme', label: 'Default server theme', cssClass: '', placeholder: 'Default',
|
||||
options: [
|
||||
{ value: 'theme1', label: 'Mint' },
|
||||
{ value: 'theme2', label: 'Cappuccino' },
|
||||
{ value: 'theme3', label: 'Nature' },
|
||||
{ value: 'theme4', label: 'Ocean' },
|
||||
{ value: 'theme5', label: 'Terminal' },
|
||||
{ value: 'theme6', label: 'Nightlife' },
|
||||
{ value: 'theme7', label: 'Blurple' },
|
||||
{ value: 'theme8', label: 'Construction' },
|
||||
{ value: 'theme9', label: 'Amoled' },
|
||||
]
|
||||
}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20">
|
||||
<h3>Antennas</h3>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'bottom-20', label: 'Antenna switch', id: 'antennas-enabled'}) %><br>
|
||||
|
||||
<div class="flex-container flex-center p-20">
|
||||
<div class="flex-container flex-phone flex-column bottom-20" style="margin-left: 15px; margin-right: 15px;">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Antenna 1', id: 'antennas-ant1-enabled'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: 'Ant A', label: 'Antenna 1 name', id: 'antennas-ant1-name'}) %><br>
|
||||
</div>
|
||||
|
||||
<div class="flex-container flex-phone flex-column bottom-20" style="margin-left: 15px; margin-right: 15px;">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'top-25', label: 'Antenna 2', id: 'antennas-ant2-enabled'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: 'Ant B', label: 'Antenna 2 name', id: 'antennas-ant2-name'}) %><br>
|
||||
</div>
|
||||
|
||||
<div class="flex-container flex-phone flex-column bottom-20" style="margin-left: 15px; margin-right: 15px;">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Antenna 3', id: 'antennas-ant3-enabled'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: 'Ant C', label: 'Antenna 3 name', id: 'antennas-ant3-name'}) %><br>
|
||||
</div>
|
||||
|
||||
<div class="flex-container flex-phone flex-column bottom-20" style="margin-left: 15px; margin-right: 15px;">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Antenna 4', id: 'antennas-ant4-enabled'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: 'Ant D', label: 'Antenna 4 name', id: 'antennas-ant4-name'}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-50" style="padding-left: 20px; padding-right: 20px;">
|
||||
<h3>Tuning options</h3>
|
||||
<p>If you want to limit which frequencies the users can tune to,<br>you can set the lower and upper limit here.<br>
|
||||
<span class="text-gray">Enter frequencies in MHz.</span>
|
||||
</p>
|
||||
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Limit tuning', id: 'webserver-tuningLimit'}) %><br>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '0', label: 'Lower limit', id: 'webserver-tuningLowerLimit'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '108', label: 'Upper limit', id: 'webserver-tuningUpperLimit'}) %>
|
||||
</div>
|
||||
|
||||
<div class="panel-50 p-bottom-20">
|
||||
<h3>Presets</h3>
|
||||
<p>You can set up to 4 presets.<br>These presets are accessible with the F1-F4 buttons.<br>
|
||||
<span class="text-gray">Enter frequencies in MHz.</span></p>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '87.5', label: 'Preset 1', id: 'webserver-presets-1'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '87.5', label: 'Preset 2', id: 'webserver-presets-2'}) %>
|
||||
<br>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '87.5', label: 'Preset 3', id: 'webserver-presets-3'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '87.5', label: 'Preset 4', id: 'webserver-presets-4'}) %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-container p-bottom-20">
|
||||
<div class="panel-50 p-bottom-20" style="padding-left: 20px; padding-right: 20px;">
|
||||
<h3>RDS Mode</h3>
|
||||
<p>You can switch between American (RBDS) / Global (RDS) mode here.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'bottom-20', iconClass: '', label: 'American RDS mode (RBDS)', id: 'webserver-rdsMode'}) %>
|
||||
<h3>RDS Timeout</h3>
|
||||
<p>If no data is received, RDS will be automatically cleared after a timeout.<br>
|
||||
<span class="text-gray">Enter timeout in seconds or 0 to disable.</span><br></p>
|
||||
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100', placeholder: '0', label: 'RDS Timeout', id: 'webserver-rdsTimeout'}) %>
|
||||
</div>
|
||||
<div class="panel-50 p-bottom-20" style="padding-left: 20px; padding-right: 20px; padding-bottom: 80px;">
|
||||
<h3>Transmitter Search Algorithm</h3>
|
||||
<p>Different modes may help with more accurate transmitter identification depending on your region.</p>
|
||||
<%- include('_components', { component: 'dropdown', id: 'server-tx-id-algo', inputId: 'webserver-txIdAlgorithm', label: 'Transmitter ID Algorithm', cssClass: '', placeholder: 'Algorithm 1',
|
||||
options: [
|
||||
{ value: '0', label: 'Algorithm 1' },
|
||||
{ value: '1', label: 'Algorithm 2' },
|
||||
{ value: '2', label: 'Algorithm 3' },
|
||||
]
|
||||
}) %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="tuner" role="tabpanel">
|
||||
<h2>Tuner settings</h2>
|
||||
<div class="panel-100 p-bottom-20 contains-dropdown" style="z-index: 991;">
|
||||
<h3>Device type</h3>
|
||||
<div class="flex-center" style="max-width: 520px; margin: 10px auto 0;">
|
||||
<%- include('_components', { component: 'dropdown', id: 'device-selector', inputId: 'device', label: 'Device', cssClass: '', placeholder: 'TEF668x / TEA685x',
|
||||
options: tunerProfiles.map(profile => ({
|
||||
value: profile.id,
|
||||
label: profile.label
|
||||
}))
|
||||
}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-container contains-dropdown">
|
||||
<div class="panel-100 p-bottom-20" style="padding-right: 20px; padding-left: 20px;">
|
||||
<h3>Connection type</h3>
|
||||
<p class="text-gray">If you want to choose the serial port directly, choose "Direct".<br>If you use xdrd or your receiver is connected via Wi-Fi, choose TCP/IP.</p>
|
||||
<div class="auto top-10" style="max-width: 350px;">
|
||||
<label class="toggleSwitch nolabel" onclick="">
|
||||
<input id="xdrd-wirelessConnection" type="checkbox" tabindex="0" aria-label="Connection type"/>
|
||||
<a></a>
|
||||
<span>
|
||||
<span class="left-span">Direct</span>
|
||||
<span class="right-span">TCP/IP</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="tuner-usb">
|
||||
<p class="text-gray">Choose your desired <strong>serial port</strong><br> </p>
|
||||
<%- include('_components', {
|
||||
component: 'dropdown',
|
||||
id: 'deviceList',
|
||||
inputId: 'xdrd-comPort',
|
||||
label: 'Serial port',
|
||||
cssClass: '',
|
||||
placeholder: 'Choose your serial port',
|
||||
options: serialPorts.map(serialPort => ({
|
||||
value: serialPort.path,
|
||||
label: `${serialPort.path} - ${serialPort.friendlyName}`
|
||||
}))
|
||||
}) %>
|
||||
</div>
|
||||
|
||||
<div id="tuner-wireless">
|
||||
<p class="text-gray">If you are connecting your tuner <strong>wirelessly</strong>, enter the tuner IP. <br> If you use <strong>xdrd</strong>, use 127.0.0.1 as your IP.</p>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', label: 'xdrd IP address', id: 'xdrd-xdrdIp'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', label: 'xdrd port', id: 'xdrd-xdrdPort'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', label: 'xdrd password', id: 'xdrd-xdrdPassword', password: true}) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-container">
|
||||
<div class="panel-50 p-bottom-20">
|
||||
<h3>Startup</h3>
|
||||
<h4>Startup volume</h4>
|
||||
<div class="panel-75 auto" style="height: 48px;">
|
||||
<input type="range" id="audio-startupVolume" min="0" max="1" step="0.01" value="1" aria-label="Startup Volume slider">
|
||||
</div>
|
||||
<h4 class="top-10 text-gray" id="volume-percentage-value"></h4>
|
||||
|
||||
<hr>
|
||||
<h4 class="bottom-20">Default frequency</h4>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Default frequency for first client', id: 'enableDefaultFreq'}) %><br>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100', placeholder: '87.5', label: 'Default frequency', id: 'defaultFreq'}) %>
|
||||
</div>
|
||||
<div class="panel-50 p-bottom-20">
|
||||
<h3>Miscellaneous</h3>
|
||||
<div class="flex-container">
|
||||
<div class="panel-33 no-bg">
|
||||
<h4>Bandwidth switch</h4>
|
||||
<p>Bandwidth switch allows the user to set the bandwidth manually.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Bandwidth switch', id: 'bwSwitch'}) %><br>
|
||||
</div>
|
||||
<div class="panel-33 no-bg">
|
||||
<h4>Automatic shutdown</h4>
|
||||
<p>Toggling this option will put the tuner to sleep when no clients are connected.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Auto-shutdown', id: 'autoShutdown'}) %><br>
|
||||
</div>
|
||||
<div class="panel-33 no-bg">
|
||||
<h4>SI47XX AGC control</h4>
|
||||
<p>Allow users to change SI47XX AGC mode from the main UI.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Enable AGC control', id: 'si47xx-agcControl'}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="plugins-tab" role="tabpanel">
|
||||
<h2>Plugins</h2>
|
||||
<div class="panel-100 p-bottom-20">
|
||||
<h3>Plugin list</h3>
|
||||
<p>Any compatible <strong>.js</strong> plugin, which is in the "plugins" folder, will be listed here.<br>
|
||||
Click on the individual plugins to enable/disable them.</p>
|
||||
<select id="plugins" class="multiselect" multiple>
|
||||
<% plugins.forEach(function(plugin) {
|
||||
if (plugin.frontEndPath) { %>
|
||||
<option data-name="<%= plugin.frontEndPath %>" title="<%= plugin.name %> by <%= plugin.author %> [v<%= plugin.version %>]">
|
||||
<%= plugin.name %> by <%= plugin.author %> [v<%= plugin.version %>]
|
||||
</option>
|
||||
<% }
|
||||
}); %>
|
||||
</select><br><br>
|
||||
<a href="https://github.com/NoobishSVK/fm-dx-webserver/wiki/Plugin-List" target="_blank">Download new plugins here!</a>
|
||||
</div>
|
||||
|
||||
<div class="panel-100 p-bottom-20">
|
||||
<h3>Plugin settings</h3>
|
||||
<div id="plugin-settings">No plugin settings are available.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="identification" role="tabpanel">
|
||||
<h2>Identification & Map</h2>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-50 p-bottom-20">
|
||||
<h3>Basic info</h3>
|
||||
|
||||
<p>Set your tuner name and description here.<br>This info will be visible to anyone who tunes in. </p>
|
||||
<div class="panel-full no-bg" style="padding-left: 20px; padding-right: 20px;">
|
||||
<label for="identification-tunerName" style="width: 100%;max-width: 768px; margin:auto;">Webserver name:</label>
|
||||
<input style="width: 100%; max-width: 768px;" class="input-text br-15" type="text" name="identification-tunerName" id="identification-tunerName" placeholder="Fill your server name here." maxlength="32">
|
||||
<br>
|
||||
<label for="identification-tunerDesc" style="width: 100%;max-width: 768px; margin: auto;">Webserver description:</label>
|
||||
<textarea id="identification-tunerDesc" class="br-15" name="webserver-desc" placeholder="Fill the server description here. You can put useful info here such as your antenna setup. You can use simple markdown." maxlength="255"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-50">
|
||||
<h3>Online map</h3>
|
||||
<p>If your location information is filled,<br>you can add your tuner to a public list.</p>
|
||||
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Broadcast to map', id: 'identification-broadcastTuner'}) %><br>
|
||||
<%- include('_components', {component: 'text', cssClass: 'br-15', placeholder: 'Your e-mail or Discord...', label: 'Owner contact', id: 'identification-contact'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'br-15', label: 'Proxy address', id: 'identification-proxyIp'}) %>
|
||||
|
||||
<p>Check your tuner at <strong><a href="https://servers.fmdx.org" target="_blank" class="color-4">servers.fmdx.org</a></strong>.</p>
|
||||
<p class="text-small text-gray">By activating the <strong>Broadcast to map</strong> option,<br>you agree to the <a href="https://fmdx.org/projects/webserver.php#rules" target="_blank">Terms of Service</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-100">
|
||||
<h3>Location</h3>
|
||||
<p class="text-gray">Location info is useful for automatic identification of stations using RDS.</p>
|
||||
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Latitude', id: 'identification-lat'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Longitude', id: 'identification-lon'}) %>
|
||||
|
||||
<div id="map"></div>
|
||||
<br>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="users" role="tabpanel">
|
||||
<h2>User management</h2>
|
||||
<div class="panel-100">
|
||||
<h3>Chat options</h3>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Chat', id: 'webserver-chatEnabled'}) %>
|
||||
</div>
|
||||
|
||||
<div class="panel-100 p-bottom-20">
|
||||
<h3>Banlist</h3>
|
||||
<p>If you have users that don't behave on your server, you can choose to ban them by their IP address.<br>
|
||||
<span class="text-gray">You can see their IP address by hovering over their nickname. One IP per row.</span></p>
|
||||
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20" style="overflow-x: auto;">
|
||||
<h3>Current users</h3>
|
||||
<table class="table-big">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>IP Address</th>
|
||||
<th>Location</th>
|
||||
<th>Ban date</th>
|
||||
<th>Reason</th>
|
||||
<th class="color-5"></th>
|
||||
<th>User Agent</th>
|
||||
<th>Online since</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: 'IP address', label: '', id: 'banlist-add-ip'}) %></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td><%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: 'Ban reason (note)', label: '', id: 'banlist-add-reason'}) %></td>
|
||||
<td class="color-5">
|
||||
<a href="#" id="banlist-add-link"><i class="fa-solid fa-plus-circle banlist-add"></i></a>
|
||||
</td>
|
||||
</tr>
|
||||
<% if (banlist.length > 0) { %>
|
||||
<% banlist.forEach(bannedUser => { %>
|
||||
<% if (connectedUsers.length > 0) { %>
|
||||
<% connectedUsers.forEach(user => { %>
|
||||
<tr>
|
||||
<% if (Array.isArray(bannedUser)) { %>
|
||||
<!-- If it's an array, use its values -->
|
||||
<td style="text-align: center !important;"><a href="https://dnschecker.org/ip-location.php?ip=<%= bannedUser[0] %>" target="_blank"><%= bannedUser[0] %></a></td>
|
||||
<td><%= bannedUser[1] %></td>
|
||||
<td class="text-bold"><%= new Date(parseInt(bannedUser[2])).toLocaleString() %></td> <!-- Assuming the ban date is a timestamp in seconds -->
|
||||
<td><%= bannedUser[3] %></td>
|
||||
<% } else { %>
|
||||
<!-- If it's just an IP address without additional data, show it as is -->
|
||||
<td style="text-align: center !important;"><a href="https://dnschecker.org/ip-location.php?ip=<%= bannedUser %>" target="_blank"><%= bannedUser %></a></td>
|
||||
<td>Unknown</td>
|
||||
<td class="text-bold">Unknown</td>
|
||||
<td>Unknown</td>
|
||||
<% } %>
|
||||
<td><a href="#" class="banlist-remove"><i class="fa-solid fa-lock-open text-gray"></i></a></td>
|
||||
<td>
|
||||
<a href="https://ipinfo.io/<%= user.ip %>" target="_blank">
|
||||
<%= user.ip %>
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<%= user.location %><% if (user.isp) { %> (<%= user.isp %>)<% } %>
|
||||
</td>
|
||||
<td><%= user.agent %></td>
|
||||
<td><%= user.time %></td>
|
||||
<td><a href="./kick?ip=<%= user.ip %>">Kick</a></td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
<% } else { %>
|
||||
<tr>
|
||||
<td colspan="5" style="text-align: center">The banlist is empty.</td>
|
||||
<td colspan="4" style="text-align: center">No users online</td>
|
||||
</tr>
|
||||
<% } %>
|
||||
</tbody>
|
||||
@@ -540,164 +75,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="startup" role="tabpanel">
|
||||
<h2>Startup settings</h2>
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20" style="z-index: 10; padding-bottom: 120px;">
|
||||
<h3>On startup</h3>
|
||||
<p>These settings will be applied after a server launch or restart.</p>
|
||||
<div class="flex-container flex-center p-20">
|
||||
<% if (device === 'tef') { %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'ceqStartup-dropdown', inputId: 'ceqStartup', label: 'cEQ', cssClass: '', placeholder: 'Disabled',
|
||||
options: [
|
||||
{ value: '0', label: 'Disabled' },
|
||||
{ value: '1', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'imsStartup-dropdown', inputId: 'imsStartup', label: 'iMS', cssClass: '', placeholder: 'Disabled',
|
||||
options: [
|
||||
{ value: '0', label: 'Disabled' },
|
||||
{ value: '1', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<% } else if (device === 'xdr') { %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'rfStartup-dropdown', inputId: 'ceqStartup', label: 'RF+', cssClass: '', placeholder: 'Disabled',
|
||||
options: [
|
||||
{ value: '0', label: 'Disabled' },
|
||||
{ value: '1', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'ifStartup-dropdown', inputId: 'imsStartup', label: 'IF+', cssClass: '', placeholder: 'Disabled',
|
||||
options: [
|
||||
{ value: '0', label: 'Disabled' },
|
||||
{ value: '1', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<% } %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'stereoStartup-dropdown', inputId: 'stereoStartup', label: 'Stereo Mode', cssClass: '', placeholder: 'Stereo (Default)',
|
||||
options: [
|
||||
{ value: '0', label: 'Stereo (Default)' },
|
||||
{ value: '1', label: 'Mono' },
|
||||
]
|
||||
}) %><br>
|
||||
</div>
|
||||
<div class="panel-100-real p-bottom-20 no-bg">
|
||||
<%- include('_components', { component: 'dropdown', id: 'antennaStartup-dropdown', inputId: 'antennaStartup', label: 'Antenna', cssClass: '', placeholder: 'Antenna 0 (Default)',
|
||||
options: [
|
||||
{ value: '0', label: 'Antenna 0 (Default)' },
|
||||
{ value: '1', label: 'Antenna 1' },
|
||||
{ value: '2', label: 'Antenna 2' },
|
||||
{ value: '3', label: 'Antenna 3' },
|
||||
]
|
||||
}) %><br>
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20 bottom-20">
|
||||
<h3>Console</h3>
|
||||
<% if (consoleOutput && consoleOutput.length > 0) { %>
|
||||
<div class="panel-100 auto br-5 p-10 text-small text-left top-10" id="console-output">
|
||||
<% consoleOutput.forEach(function(log) { %>
|
||||
<pre class="m-0" style="white-space:pre-wrap;"><%= log %></pre>
|
||||
<% }); %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-container">
|
||||
<div class="panel-100-real p-bottom-20 bottom-20" style="z-index: 9; padding-bottom: 180px;">
|
||||
<h3>Empty server defaults</h3>
|
||||
<p>These settings will apply once the last user disconnects from the server, so the server can be ready for a new user with default settings.</p>
|
||||
<div class="flex-container flex-center p-20">
|
||||
<%- include('_components', { component: 'dropdown', id: 'bwAutoNoUsers-dropdown', inputId: 'bwAutoNoUsers', label: 'Auto BW', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<% if (device === 'tef') { %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'ceqNoUsers-dropdown', inputId: 'ceqNoUsers', label: 'cEQ', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Disabled' },
|
||||
{ value: '2', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'imsNoUsers-dropdown', inputId: 'imsNoUsers', label: 'iMS', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Disabled' },
|
||||
{ value: '2', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<% } else if (device === 'xdr') { %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'rfNoUsers-dropdown', inputId: 'ceqNoUsers', label: 'RF+', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Disabled' },
|
||||
{ value: '2', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'ifNoUsers-dropdown', inputId: 'imsNoUsers', label: 'IF+', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Disabled' },
|
||||
{ value: '2', label: 'Enabled' },
|
||||
]
|
||||
}) %><br>
|
||||
<% } %>
|
||||
<%- include('_components', { component: 'dropdown', id: 'stereoNoUsers-dropdown', inputId: 'stereoNoUsers', label: 'Stereo Mode', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Stereo' },
|
||||
{ value: '2', label: 'Mono' },
|
||||
]
|
||||
}) %><br>
|
||||
</div>
|
||||
<div class="panel-100-real p-bottom-20 no-bg">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Delayed Antenna Change', id: 'antennaNoUsersDelay'}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'antennaNoUsers-dropdown', inputId: 'antennaNoUsers', label: 'Antenna', cssClass: '', placeholder: 'Unchanged',
|
||||
options: [
|
||||
{ value: '0', label: 'Unchanged' },
|
||||
{ value: '1', label: 'Antenna 0' },
|
||||
{ value: '2', label: 'Antenna 1' },
|
||||
{ value: '3', label: 'Antenna 2' },
|
||||
{ value: '4', label: 'Antenna 3' },
|
||||
]
|
||||
}) %>
|
||||
<br>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-full m-0 tab-content no-bg" id="extras" role="tabpanel">
|
||||
<h2>Extras</h2>
|
||||
<div class="panel-100 p-bottom-20">
|
||||
<h3>FMLIST Integration</h3>
|
||||
<p>FMLIST integration allows you to get potential DXes logged on the <a href="http://fmlist.org/fm_logmap.php?hours=900" target="_blank" class="text-bold color-4">FMLIST Visual Logbook</a>.<br>
|
||||
Your server also needs to have a valid UUID, which is obtained by registering on maps in the <strong>Identification & Map</strong> tab.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'm-right-10', label: 'FMLIST integration', id: 'extras-fmlistIntegration'}) %><br>
|
||||
<p>If you don't feel comfortable with the general public logging on your server, you can make this feature available only for people with a password</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'm-right-10', label: 'Admin-only logging', id: 'extras-fmlistAdminOnly'}) %><br>
|
||||
|
||||
<p>You can also fill in your OMID from FMLIST.org, if you want the logs to be saved to your account.</p>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '', label: 'OMID', id: 'extras-fmlistOmid'}) %>
|
||||
</div>
|
||||
<div class="panel-100 p-bottom-20">
|
||||
<h3>Tunnel</h3>
|
||||
<p>When you become an <a href="https://buymeacoffee.com/fmdx" target="_blank"><strong>FMDX.org supporter</strong></a>, you can host your webserver without the need of a public IP address & port forwarding.<br>
|
||||
When you become a supporter, you can message the Founders on Discord for your login details.</p><br>
|
||||
<p>You can also get an tunnel from kuba201 discord, one of the contributors of this version of the application.</p>
|
||||
<h4>Main tunnel settings</h4>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'm-right-10', label: 'Enable tunnel', id: 'tunnel-enabled'}) %><br>
|
||||
<%- include('_components', { component: 'dropdown', id: 'tunnel-regionSelect', inputId: 'tunnel-region', label: 'Official server region', cssClass: '', placeholder: 'Europe',
|
||||
options: [
|
||||
{ value: 'eu', label: 'Europe' },
|
||||
{ value: 'us', label: 'Americas' },
|
||||
{ value: 'sg', label: 'Asia & Oceania' },
|
||||
{ value: 'pldx', label: 'Poland (k201)' },
|
||||
]
|
||||
}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Username', id: 'tunnel-username'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-250 br-15', password: true, placeholder: '', label: 'Token', id: 'tunnel-token'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Subdomain name', id: 'tunnel-subdomain'}) %><br>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'm-right-10', label: 'Low latency mode', id: 'tunnel-lowLatencyMode'}) %><br>
|
||||
<p>Enabling low latency mode may provide better experience, however it will also use more bandwidth.</p>
|
||||
|
||||
<h4 class="top-25">Community tunnel settings</h4>
|
||||
<p>You can also self-host or ask other people to provide you a token. In this case, the server owner is responsible for any potential security issues.</p>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: 'm-right-10', label: 'Use a community tunnel', id: 'tunnel-community-enabled'}) %><br>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-250 br-15', placeholder: '', label: 'Community Tunnel host (IP or hostname)', id: 'tunnel-community-host'}) %>
|
||||
<% } else { %>
|
||||
<p>No console output available.</p>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -709,18 +98,5 @@
|
||||
<script src="js/dropdown.js"></script>
|
||||
<script src="js/setup.js"></script>
|
||||
<script src="js/confighandler.js"></script>
|
||||
<% enabledPlugins?.forEach(function(plugin) { %>
|
||||
<script src="js/plugins/<%= plugin %>"></script>
|
||||
<% }); %>
|
||||
|
||||
<script>
|
||||
document.addEventListener('keydown', function(event) {
|
||||
if (event.ctrlKey && event.key === 's') {
|
||||
event.preventDefault();
|
||||
if (event.repeat) return;
|
||||
submitConfig();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Wizard - FM-DX Webserver</title>
|
||||
<link href="css/entry.css" type="text/css" rel="stylesheet">
|
||||
<link href="css/flags.min.css" type="text/css" rel="stylesheet">
|
||||
<link href="css/libs/fontawesome.css" type="text/css" rel="stylesheet">
|
||||
<script src="js/libs/jquery.min.js"></script>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" type="text/css" rel="stylesheet">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
|
||||
<link rel="icon" type="image/svg+xml" href="favicon.svg" id="favicon" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
</head>
|
||||
<body>
|
||||
<div id="toast-container" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>
|
||||
<div class="wrapper-outer wrapper-full">
|
||||
<div id="wrapper">
|
||||
<div class="panel-100 no-bg">
|
||||
<img class="top-10" src="../images/openradio_logo_neutral.png" height="64px">
|
||||
<h2 class="text-monospace text-light text-gray">[SETUP WIZARD]</h2>
|
||||
</div>
|
||||
<div class="panel-100 no-bg flex-container flex-center flex-phone">
|
||||
<div class="btn-rounded-cube activated">1</div>
|
||||
<div class="btn-rounded-cube">2</div>
|
||||
<div class="btn-rounded-cube">3</div>
|
||||
<div class="btn-rounded-cube">4</div>
|
||||
<div class="btn-rounded-cube">5</div>
|
||||
</div>
|
||||
|
||||
<div class="panel-100">
|
||||
<!-- BASIC SETTINGS -->
|
||||
<div class="panel-100 step no-bg" id="step1">
|
||||
<h2 class="settings-heading">Basic settings</h2>
|
||||
<p class="m-0">Welcome to the setup wizard! Let's set up some basic things.</p>
|
||||
|
||||
<h3 class="settings-heading">Webserver connection</h3>
|
||||
<p class="m-0">Leave the IP at 0.0.0.0 unless you explicitly know you have to change it.<br>DO NOT enter your public IP here.</p>
|
||||
<div class="flex-center top-25">
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '0.0.0.0', label: 'Webserver IP', id: 'webserver-webserverIp'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', placeholder: '8080', label: 'Webserver port', id: 'webserver-webserverPort'}) %><br>
|
||||
</div>
|
||||
</div>
|
||||
<!-- BASIC SETTINGS END -->
|
||||
<!-- TUNER SETTINGS -->
|
||||
<div id="step2" class="step" style="display: none">
|
||||
<h2 class="settings-heading">Tuner settings</h2>
|
||||
|
||||
<h3 class="settings-heading">Tuner type</h3>
|
||||
<p class="m-0">Settings a proper device type ensures that the correct interface and settings will load.</p>
|
||||
<div class="panel-100 no-bg flex-center" style="max-width: 520px; margin: 10px auto 0;">
|
||||
<%- include('_components', { component: 'dropdown', id: 'device-selector', inputId: 'device', label: 'Device', cssClass: '', placeholder: 'TEF668x / TEA685x',
|
||||
options: tunerProfiles.map(profile => ({
|
||||
value: profile.id,
|
||||
label: profile.label
|
||||
}))
|
||||
}) %><br>
|
||||
</div>
|
||||
<div class="clearfix"></div>
|
||||
<h3 class="settings-heading">Tuner connection</h3>
|
||||
<div style="width: 300px;" class="auto top-10">
|
||||
<label class="toggleSwitch nolabel" onclick="">
|
||||
<input id="xdrd-wirelessConnection" type="checkbox" aria-label="Tuner connection type"/>
|
||||
<a></a>
|
||||
<span>
|
||||
<span class="left-span">Direct</span>
|
||||
<span class="right-span">TCP/IP</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="tuner-usb" class="top-25">
|
||||
<p>It's time to choose your serial port.</p>
|
||||
|
||||
<div class="panel-100 no-bg flex-center">
|
||||
<%- include('_components', {
|
||||
component: 'dropdown',
|
||||
id: 'deviceList',
|
||||
inputId: 'xdrd-comPort',
|
||||
label: 'Serial port',
|
||||
cssClass: '',
|
||||
placeholder: 'Choose your serial port',
|
||||
options: serialPorts.map(serialPort => ({
|
||||
value: serialPort.path,
|
||||
label: `${serialPort.path} - ${serialPort.friendlyName}`
|
||||
}))
|
||||
}) %>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clearfix"></div>
|
||||
<div id="tuner-wireless" class="top-25">
|
||||
<p class="m-0">If you are connecting your tuner <strong>wirelessly</strong>, enter the tuner IP. <br> If you use <strong>xdrd</strong>, use 127.0.0.1 as your IP.</p>
|
||||
<div class="flex-center top-25">
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', label: 'xdrd IP address', id: 'xdrd-xdrdIp'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-100 br-15', label: 'xdrd port', id: 'xdrd-xdrdPort'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', label: 'xdrd password', id: 'xdrd-xdrdPassword', password: true}) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- TUNER SETTINGS END -->
|
||||
<!-- AUDIO SETTINGS -->
|
||||
<div id="step3" class="step" style="display: none;">
|
||||
<div class="panel-100 no-bg" style="min-height: 120px;margin-bottom: 0;">
|
||||
<h2 class="settings-heading">Audio settings</h2>
|
||||
<p class="m-0">In this section, we will set up the audio.<br>
|
||||
Choose the audio port your tuner is connected to and desired audio settings here.</p>
|
||||
<p class="text-gray">Recommended defaults have already been set for the audio quality, you can keep them as-is.</p>
|
||||
|
||||
<div class="panel-100 no-bg p-bottom-20 flex-container flex-center">
|
||||
<%- include('_components', {
|
||||
component: 'dropdown',
|
||||
id: 'audioList',
|
||||
inputId: 'audio-audioDevice',
|
||||
label: 'Audio device',
|
||||
cssClass: '',
|
||||
placeholder: 'Choose your audio device',
|
||||
options: [
|
||||
...videoDevices.map(device => ({
|
||||
value: device.name,
|
||||
label: `${device.name}`
|
||||
})),
|
||||
...audioDevices.map(device => ({
|
||||
value: device.name,
|
||||
label: `${device.name}`
|
||||
}))
|
||||
]
|
||||
}) %>
|
||||
|
||||
<%- include('_components', { component: 'dropdown', id: 'audio-channels-dropdown', inputId: 'audio-audioChannels', label: 'Audio channels', cssClass: '', placeholder: 'Stereo',
|
||||
options: [
|
||||
{ value: '2', label: 'Stereo' },
|
||||
{ value: '1', label: 'Mono' }
|
||||
]
|
||||
}) %>
|
||||
|
||||
<%- include('_components', { component: 'dropdown', id: 'audio-quality-dropdown', inputId: 'audio-audioBitrate', label: 'Audio quality', cssClass: '', placeholder: '128kbps (standard)',
|
||||
options: [
|
||||
{ value: '64k', label: '64kbps (lowest quality)' },
|
||||
{ value: '96k', label: '96kbps (low quality)' },
|
||||
{ value: '128k', label: '128kbps (standard)' },
|
||||
{ value: '192k', label: '192kbps (high quality)' },
|
||||
{ value: '256k', label: '256kbps (very high quality)' },
|
||||
{ value: '320k', label: '320kbps (ultra quality)' }
|
||||
]
|
||||
}) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- AUDIO SETTINGS END -->
|
||||
<!-- IDENTIFICATION START -->
|
||||
<div id="step4" class="step" style="display: none;">
|
||||
<div class="panel-100 no-bg" style="padding-bottom: 20px;">
|
||||
<h2 class="settings-heading">Webserver info</h2>
|
||||
<p class="m-0">In this part, we will set up your webserver info, such as the server name, description and location.</p>
|
||||
<label for="identification-tunerName" style="width: 100%;max-width: 768px; margin:auto;">Webserver name:</label>
|
||||
<input style="width: 100%; max-width: 768px;" class="input-text br-15" type="text" name="identification-tunerName" id="identification-tunerName" placeholder="Fill your server name here." maxlength="32">
|
||||
<br>
|
||||
<label for="identification-tunerDesc" style="width: 100%;max-width: 768px; margin: auto;">Webserver description:</label>
|
||||
<textarea id="identification-tunerDesc" name="webserver-desc" class="br-15" placeholder="Fill the server description here. You can put useful info here such as your antenna setup. You can use simple markdown." maxlength="255"></textarea>
|
||||
|
||||
<h3 class="settings-heading">Location</h3>
|
||||
<p>Location info is useful for automatic identification of stations using RDS.</p>
|
||||
<div class="panel-100 no-bg flex-container flex-center">
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-250 br-15', placeholder: '', label: 'Latitude', id: 'identification-lat'}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-250 br-15', placeholder: '', label: 'Longitude', id: 'identification-lon'}) %>
|
||||
</div>
|
||||
<div id="map"></div>
|
||||
|
||||
<h3 class="settings-heading">Map broadcast</h3>
|
||||
<p class="m-0">If your location info is filled, you can add your tuner to a public list.</p>
|
||||
<p class="m-0">The list is available at <strong><a href="https://servers.fmdx.org" target="_blank" class="color-4">servers.fmdx.org</a></strong>.</p>
|
||||
<p class="text-small text-gray">By activating the <strong>Broadcast to map</strong> option, you agree to the <a href="https://fmdx.org/projects/webserver.php#rules" target="_blank">Terms of Service</a>.</p>
|
||||
|
||||
<div class="panel-100 no-bg flex-container flex-center">
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Broadcast to map', id: 'identification-broadcastTuner'}) %><br>
|
||||
<%- include('_components', {component: 'checkbox', cssClass: '', label: 'Allow tuning without password', id: 'publicTuner'}) %>
|
||||
</div>
|
||||
|
||||
<p class="text-gray">If you use a proxy / tunnel service, enter the access link here. If you don't know what a proxy is, leave it empty.</p>
|
||||
|
||||
<div class="panel-100 no-bg flex-container flex-center">
|
||||
<%- include('_components', {component: 'text', cssClass: 'br-15', label: 'Broadcast address (if using a proxy)', id: 'identification-proxyIp'}) %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- IDENTIFICATION END -->
|
||||
<!-- ADMIN SETTINGS START -->
|
||||
<div id="step5" class="step" style="display: none;">
|
||||
<h2 class="settings-heading">Admin panel settings</h2>
|
||||
<p>We are at the last and final step of the wizard.</p>
|
||||
|
||||
<p>Here we can set the password. Tune password is optional.<br>Setting an admin password allows you to change settings later and setting one up is mandatory.</p>
|
||||
<div class="flex-container flex-center">
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Tune password', id: 'password-tunePass', password: true}) %>
|
||||
<%- include('_components', {component: 'text', cssClass: 'w-150 br-15', placeholder: '', label: 'Admin password', id: 'password-adminPass', password: true}) %><br>
|
||||
</div>
|
||||
<p>You can now click the <strong>save button</strong> to save your settings. After that, you will need to restart the webserver.</p>
|
||||
</div>
|
||||
|
||||
<div class="panel-100 no-bg">
|
||||
<button class="btn-prev"><i class="fa-solid fa-arrow-left"></i></button>
|
||||
<button class="btn-next">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-100 no-bg">
|
||||
<p>Feel free to contact us on <a href="https://discord.gg/ZAVNdS74mC" target="_blank"><strong><i class="fa-brands fa-discord"></i> Discord</strong></a> for community support.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="js/settings.js"></script>
|
||||
<script src="js/dropdown.js"></script>
|
||||
<script src="js/toast.js"></script>
|
||||
<script src="js/setup.js"></script>
|
||||
<script src="js/wizard.js"></script>
|
||||
<script src="js/confighandler.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,563 @@
|
||||
/* A1: Styles for Tune Step Feature */
|
||||
body.tune-step-enabled #freq-container {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
}
|
||||
body.tune-step-enabled .freq-digit-marker {
|
||||
color: #00FF00;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
.et-dimmed-zero {
|
||||
opacity: 0.1;
|
||||
}
|
||||
.et-dimmed-zero.freq-digit-marker {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* A2: Styles for disabled bands (Tune Limit) */
|
||||
.disabled-band {
|
||||
background-color: var(--color-1) !important;
|
||||
color: var(--color-3) !important;
|
||||
cursor: not-allowed !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* MW 9 kHz/10 kHz button */
|
||||
#mw-step-toggle-button {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 6px;
|
||||
z-index: 11;
|
||||
display: none;
|
||||
max-width: 50px;
|
||||
text-align: center;
|
||||
height: auto;
|
||||
padding: 1px 6px;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
line-height: 1.4;
|
||||
color: var(--color-main);
|
||||
background-color: var(--color-4);
|
||||
border: 1px solid var(--color-2);
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s ease, background-color 0.2s ease, transform 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
#mw-step-toggle-button:hover {
|
||||
background-color: var(--color-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
#mw-step-toggle-button.active {
|
||||
opacity: 1;
|
||||
border-color: var(--color-4);
|
||||
}
|
||||
|
||||
|
||||
/* ========================================================================== */
|
||||
/* B: MODERN LAYOUT */
|
||||
/* ========================================================================== */
|
||||
|
||||
/* B1: Basic structure for Modern Layout */
|
||||
body.layout-modern #freq-container {
|
||||
position: relative !important;
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
}
|
||||
|
||||
/* B2: Main wrapper and buttons (Shown only if HIDE_ALL_BUTTONS is false) */
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin: 20px 10px 0 10px;
|
||||
background: transparent !important;
|
||||
padding: 0 !important;
|
||||
backdrop-filter: none !important;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .side-band-button-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: 60px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-button {
|
||||
height: 28px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
background-color: color-mix(in srgb, var(--color-4) 60%, transparent);
|
||||
color: var(--color-main);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-button:hover {
|
||||
background-color: var(--color-5);
|
||||
color: var(--color-main);
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .side-band-button-container .band-selector-button.active-band {
|
||||
background-color: var(--color-4);
|
||||
color: var(--color-main);
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #rt-container,
|
||||
body.layout-modern.modern-buttons-visible .am-bands-view-container {
|
||||
flex-grow: 1;
|
||||
min-width: 0;
|
||||
background-color: var(--color-1-transparent);
|
||||
backdrop-filter: blur(5px);
|
||||
border-radius: 15px;
|
||||
margin: 0 !important;
|
||||
height: auto !important;
|
||||
align-self: stretch;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .am-bands-view-container {
|
||||
display: grid;
|
||||
grid-template-columns: 85px 1fr;
|
||||
gap: 5px;
|
||||
padding: 0 5px;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .sw-grid-container {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, 1fr);
|
||||
grid-template-rows: repeat(3, 1fr);
|
||||
gap: 5px;
|
||||
height: 100%;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .am-view-button,
|
||||
body.layout-modern.modern-buttons-visible .sw-grid-button {
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background-color: var(--color-3);
|
||||
color: var(--color-main);
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
transition: all 0.2s ease-in-out;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .am-view-button:hover,
|
||||
body.layout-modern.modern-buttons-visible .sw-grid-button:hover {
|
||||
background-color: var(--color-4);
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .am-bands-view-container .am-view-button.active-band,
|
||||
body.layout-modern.modern-buttons-visible .am-bands-view-container .sw-grid-button.active-band {
|
||||
background-color: var(--color-5);
|
||||
color: var(--color-main);
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .am-view-button {
|
||||
font-size: 14px;
|
||||
height: 22px;
|
||||
width: 60px;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .sw-bands-fieldset,
|
||||
body.layout-modern.modern-buttons-visible .band-fieldset {
|
||||
border: 1px solid var(--color-3);
|
||||
border-bottom: none;
|
||||
border-radius: 8px;
|
||||
padding: 0px 5px 5px 5px;
|
||||
margin: 0;
|
||||
position: relative;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .sw-bands-fieldset legend,
|
||||
body.layout-modern.modern-buttons-visible .band-fieldset legend {
|
||||
color: var(--color-4);
|
||||
font-weight: bold;
|
||||
font-size: 11px;
|
||||
width: auto;
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-button-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
padding-top: 3px;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper .tooltip,
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper .bs-tooltip {
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper .bs-tooltip {
|
||||
line-height: 0;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper .bs-tooltiptext {
|
||||
visibility: hidden;
|
||||
width: 180px;
|
||||
position: absolute;
|
||||
background-color: var(--color-2);
|
||||
border: 2px solid var(--color-3);
|
||||
color: var(--color-text);
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
border-radius: 15px;
|
||||
padding: 8px;
|
||||
z-index: 1000;
|
||||
bottom: 110%;
|
||||
left: 50%;
|
||||
margin-left: -90px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
line-height: normal;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper .bs-tooltip:hover .bs-tooltiptext {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* B3: Loop button and frequency range for Modern Layout */
|
||||
body.layout-modern.loop-button-visible .loop-toggle-button {
|
||||
position: absolute;
|
||||
left: 6px;
|
||||
bottom: 6px;
|
||||
z-index: 5;
|
||||
width: 34px;
|
||||
height: auto;
|
||||
min-height: 22px;
|
||||
line-height: 1.2;
|
||||
font-size: 11px;
|
||||
font-weight: bold;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background-color: var(--color-3);
|
||||
color: var(--color-main);
|
||||
cursor: pointer;
|
||||
padding: 2px;
|
||||
}
|
||||
body.layout-modern.loop-button-visible .loop-toggle-button:hover {
|
||||
background-color: var(--color-4);
|
||||
}
|
||||
body.layout-modern.loop-button-visible .loop-toggle-button.active {
|
||||
background-color: var(--color-5) !important;
|
||||
color: var(--color-main);
|
||||
}
|
||||
body.layout-modern.band-range-visible #band-range-container {
|
||||
position: absolute;
|
||||
bottom: 0px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 12px;
|
||||
color: var(--color-text);
|
||||
opacity: 0.7;
|
||||
}
|
||||
body.layout-modern.band-range-visible .band-range-part {
|
||||
cursor: pointer;
|
||||
}
|
||||
body.layout-modern.band-range-visible .band-range-part:hover {
|
||||
opacity: 1;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* B4: Mobile View for Modern Layout */
|
||||
@media (max-width: 768px) {
|
||||
body.layout-modern.modern-buttons-visible .band-selector-layout-wrapper {
|
||||
display: block !important;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible .side-band-button-container,
|
||||
body.layout-modern.modern-buttons-visible .am-bands-view-container {
|
||||
display: none !important;
|
||||
}
|
||||
body.layout-modern #band-range-container,
|
||||
body.layout-modern .loop-toggle-button {
|
||||
display: none !important;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container {
|
||||
display: flex;
|
||||
gap: 5px;
|
||||
padding: 0 18px 10px 18px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
justify-content: center;
|
||||
align-items: baseline;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container::before,
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container > .dropdown,
|
||||
body.layout-modern.modern-buttons-visible #mobile-band-selector-wrapper,
|
||||
body.layout-modern.modern-buttons-visible #mobile-sw-band-selector-wrapper {
|
||||
width: 45% !important;
|
||||
flex: 0 1 auto !important;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container.sw-mode-active > .dropdown,
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container.sw-mode-active > #mobile-band-selector-wrapper,
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container.sw-mode-active > #mobile-sw-band-selector-wrapper {
|
||||
width: 30% !important;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #mobile-sw-band-selector-wrapper {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container:has(#mobile-band-selector-wrapper:only-child)::before,
|
||||
body.layout-modern.modern-buttons-visible #data-ant-container:has(#mobile-band-selector-wrapper:only-child)::after {
|
||||
display: none;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #mobile-band-selector-wrapper:only-child {
|
||||
width: 50% !important;
|
||||
margin: 0 auto;
|
||||
}
|
||||
body.layout-modern.modern-buttons-visible #mobile-band-selector,
|
||||
body.layout-modern.modern-buttons-visible #mobile-sw-band-selector {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
background-color: var(--color-4);
|
||||
color: var(--color-main);
|
||||
border: none;
|
||||
border-radius: 0 0 15px 15px;
|
||||
font-weight: normal;
|
||||
font-size: 14px;
|
||||
padding: 0 10px;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
background-image: url("data-image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23333333' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
background-size: 1em;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ========================================================================== */
|
||||
/* C: CLASSIC LAYOUT */
|
||||
/* ========================================================================== */
|
||||
|
||||
/* C1: Basic structure for Classic Layout */
|
||||
body.layout-classic .band-selector-button {
|
||||
background-color: rgba(0, 0, 0, 0.4);
|
||||
color: var(--color-text);
|
||||
border: 1px solid var(--color-2);
|
||||
border-radius: 4px;
|
||||
padding: 1px 6px;
|
||||
font-size: 10px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
opacity: 0.7;
|
||||
transition: all 0.2s ease;
|
||||
line-height: 1.4;
|
||||
}
|
||||
body.layout-classic #freq-container {
|
||||
position: relative !important;
|
||||
overflow: hidden;
|
||||
}
|
||||
body.layout-classic .plugin-top-container {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 6px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
}
|
||||
body.layout-classic .main-bands-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
body.layout-classic .main-band-button.active-band,
|
||||
body.layout-classic .sw-band-button.active-band,
|
||||
body.layout-classic #loop-toggle-button.active {
|
||||
background-color: var(--color-4);
|
||||
color: var(--color-main);
|
||||
opacity: 1;
|
||||
}
|
||||
body.layout-classic .sw-bands-container {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 6px;
|
||||
z-index: 9;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
body.layout-classic .sw-bands-grid {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
body.layout-classic .sw-bands-top-wrapper {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
body.layout-classic .sw-bands-bottom-wrapper {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
body.layout-classic .sw-band-button {
|
||||
padding: 1px 2px;
|
||||
text-align: center;
|
||||
}
|
||||
body.layout-classic #band-range-container {
|
||||
position: absolute;
|
||||
bottom: 0px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 5;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 11px;
|
||||
color: var(--color-text);
|
||||
opacity: 0.6;
|
||||
white-space: nowrap;
|
||||
}
|
||||
body.layout-classic .band-range-part {
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
body.layout-classic .band-range-part:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
body.layout-classic .range-separator {
|
||||
opacity: 0.7;
|
||||
pointer-events: none;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* C2: Mobile view for Classic Layout */
|
||||
@media (max-width: 768px) {
|
||||
body.layout-classic .plugin-top-container,
|
||||
body.layout-classic .sw-bands-container,
|
||||
body.layout-classic #band-range-container {
|
||||
display: none !important;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls {
|
||||
display: flex !important;
|
||||
gap: 5px;
|
||||
padding: 0 18px 10px 18px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
justify-content: center;
|
||||
align-items: baseline;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls::before,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls > .dropdown,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls #mobile-band-selector-wrapper,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls #mobile-sw-band-selector-wrapper {
|
||||
width: 45% !important;
|
||||
flex: 0 1 auto !important;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls.sw-mode-active > .dropdown,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls.sw-mode-active > #mobile-band-selector-wrapper,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls.sw-mode-active > #mobile-sw-band-selector-wrapper {
|
||||
width: 30% !important;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls #mobile-sw-band-selector-wrapper {
|
||||
display: none;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls:has(#mobile-band-selector-wrapper:only-child)::before,
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls:has(#mobile-band-selector-wrapper:only-child)::after {
|
||||
display: none;
|
||||
}
|
||||
body.layout-classic #data-ant-container.classic-mobile-controls #mobile-band-selector-wrapper:only-child {
|
||||
width: 50% !important;
|
||||
margin: 0 auto;
|
||||
}
|
||||
body.layout-classic #mobile-band-selector,
|
||||
body.layout-classic #mobile-sw-band-selector {
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
background-color: var(--color-4);
|
||||
color: var(--color-main);
|
||||
border: none;
|
||||
border-radius: 0 0 15px 15px;
|
||||
font-weight: normal;
|
||||
font-size: 14px;
|
||||
padding: 0 10px;
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
background-image: url("data-image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23333333' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
background-size: 1em;
|
||||
}
|
||||
}
|
||||
|
||||
/* ========================================================================== */
|
||||
/* FIX FOR BAND RANGE (Start <-> End) OVERLAP PÅ MOBIL / SMÅ SKJERMER */
|
||||
/* ========================================================================== */
|
||||
|
||||
#band-range-container {
|
||||
display: flex !important;
|
||||
flex-wrap: nowrap !important;
|
||||
white-space: nowrap !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.band-range-part {
|
||||
white-space: nowrap !important;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
#band-range-container {
|
||||
font-size: 10px !important;
|
||||
}
|
||||
|
||||
.band-range-unit {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
#magic-eye-wrapper { display: none !important; }
|
||||
.magic-eye-panel-override { display: block !important; }
|
||||
.magic-eye-text-wrapper { display: contents !important; }
|
||||
}
|
||||
.magic-eye-hidden { display: none !important; }
|
||||
|
||||
.bw-option-selected {
|
||||
background-color: var(--color-4) !important;
|
||||
color: #000 !important;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* ========================================================================== */
|
||||
/* D: ANALOG SCALE HIDE FIX (THE 1x1 PIXEL HACK) */
|
||||
/* ========================================================================== */
|
||||
body.et-analog-active #sdr-graph {
|
||||
display: block !important;
|
||||
position: absolute !important;
|
||||
top: 0 !important;
|
||||
left: 0 !important;
|
||||
z-index: 1 !important; /* Ligger skjult rett bak skalaen */
|
||||
opacity: 1 !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
/* Skjuler ALT ANNET som krever ytelse, inkludert det originale runde signal-canvaset! */
|
||||
body.et-analog-active #signal-canvas,
|
||||
body.et-analog-active #Antenna,
|
||||
body.et-analog-active #containerRotator,
|
||||
body.et-analog-active #sdr-graph-button-container,
|
||||
body.et-analog-active .spectrum-graph-update-text,
|
||||
body.et-analog-active #mm-mpx-combo-flex,
|
||||
body.et-analog-active #mm-signal-analyzer-flex,
|
||||
body.et-analog-active #mm-scope-flex {
|
||||
display: none !important;
|
||||
}
|
||||
+7
-7
@@ -101,15 +101,15 @@ li.active {
|
||||
height: 100%;
|
||||
z-index: 1000; /* Ensure it's above other content */
|
||||
transition: margin-left 0.3s ease; /* Smooth transition */
|
||||
}
|
||||
|
||||
.admin-wrapper {
|
||||
transition: margin-left 0.3s ease, width 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
||||
.admin-wrapper > .panel-full > .panel-full {
|
||||
.admin-wrapper {
|
||||
transition: margin-left 0.3s ease, width 0.3s ease;
|
||||
}
|
||||
|
||||
.admin-wrapper > .panel-full > .panel-full {
|
||||
min-height: 100vh;
|
||||
}
|
||||
}
|
||||
|
||||
#map {
|
||||
height:400px;
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
var audioStreamRestartInterval;
|
||||
var elapsedTimeConnectionWatchdog;
|
||||
var _3LAS = /** @class */ (function () {
|
||||
function _3LAS(url, logger) {
|
||||
this.wsurl = url;
|
||||
this.Logger = logger;
|
||||
if (!this.Logger) this.Logger = new Logging(null, null);
|
||||
|
||||
try {
|
||||
this.Fallback_Settings = new Fallback_Settings();
|
||||
this.Fallback = new Fallback(this.Logger, this.Fallback_Settings);
|
||||
this.Fallback.ActivityCallback = this.OnActivity.bind(this);
|
||||
} catch (_b) {
|
||||
this.Fallback = null;
|
||||
}
|
||||
|
||||
if (this.Fallback == null) {
|
||||
this.Logger.Log('3LAS: Browser does not support either media handling methods.');
|
||||
throw new Error();
|
||||
}
|
||||
if (isAndroid) this.WakeLock = new WakeLock(this.Logger);
|
||||
}
|
||||
Object.defineProperty(_3LAS.prototype, "Volume", {
|
||||
get: function () {
|
||||
return this.Fallback.Volume;
|
||||
},
|
||||
set: function (value) {
|
||||
this.Fallback.Volume = value;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
_3LAS.prototype.CanChangeVolume = function () {
|
||||
return true;
|
||||
};
|
||||
_3LAS.prototype.Start = function () {
|
||||
this.ConnectivityFlag = false;
|
||||
this.Stop(); // Attempt to mitigate the 0.5x speed/multiple stream bug
|
||||
|
||||
// Restart audio stream if radio data connection was reestablished
|
||||
// to prevent stuttering audio in some cases
|
||||
if (audioStreamRestartInterval) clearInterval(audioStreamRestartInterval);
|
||||
audioStreamRestartInterval = setInterval(() => {
|
||||
if (requiresAudioStreamRestart) {
|
||||
requiresAudioStreamRestart = false;
|
||||
if (Stream) {
|
||||
this.Stop();
|
||||
this.Start();
|
||||
console.log("Audio stream restarted after radio data loss.");
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
// Stream connection watchdog monitors mp3 frames
|
||||
console.log("Stream connection watchdog active.");
|
||||
let intervalReconnectWatchdog = setInterval(() => {
|
||||
if (Stream) {
|
||||
let endTimeConnectionWatchdog = performance.now();
|
||||
elapsedTimeConnectionWatchdog = endTimeConnectionWatchdog - window.startTimeConnectionWatchdog;
|
||||
//console.log(`Stream frame elapsed time: ${parseInt(elapsedTimeConnectionWatchdog)} ms`);
|
||||
if (elapsedTimeConnectionWatchdog > 2000 && shouldReconnect) {
|
||||
clearInterval(intervalReconnectWatchdog);
|
||||
setTimeout(() => {
|
||||
clearInterval(intervalReconnectWatchdog);
|
||||
console.log("Unstable internet connection detected, reconnecting... (" + parseInt(elapsedTimeConnectionWatchdog) + " ms)");
|
||||
this.Stop();
|
||||
this.Start();
|
||||
}, 2000);
|
||||
}
|
||||
} else {
|
||||
clearInterval(intervalReconnectWatchdog);
|
||||
this.Stop();
|
||||
console.log("Stream connection watchdog inactive.");
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
// This is stupid, but required for Android.... thanks Google :(
|
||||
if (this.WakeLock) this.WakeLock.Begin();
|
||||
try {
|
||||
this.WebSocket = new WebSocketClient(this.Logger, this.wsurl , this.OnSocketError.bind(this), this.OnSocketConnect.bind(this), this.OnSocketDataReady.bind(this), this.OnSocketDisconnect.bind(this));
|
||||
this.Logger.Log("Init of WebSocketClient succeeded");
|
||||
this.Logger.Log("Trying to connect to server.");
|
||||
}
|
||||
catch (e) {
|
||||
this.Logger.Log("Init of WebSocketClient failed: " + e);
|
||||
throw new Error();
|
||||
}
|
||||
};
|
||||
_3LAS.prototype.Stop = function () {
|
||||
try {
|
||||
// Close WebSocket connection
|
||||
if (this.WebSocket) {
|
||||
this.WebSocket.Close();
|
||||
this.WebSocket.OnClose();
|
||||
this.WebSocket = null;
|
||||
this.Logger.Log("WebSocket connection closed.");
|
||||
}
|
||||
|
||||
// Stop WakeLock if it exists and is an Android device
|
||||
if (isAndroid && this.WakeLock) {
|
||||
this.WakeLock.End();
|
||||
this.Logger.Log("WakeLock stopped.");
|
||||
}
|
||||
|
||||
// Reset Fallback if it exists
|
||||
if (this.Fallback) {
|
||||
this.Fallback.OnSocketDisconnect();
|
||||
this.Fallback.Stop();
|
||||
this.Fallback.Reset();
|
||||
this.Logger.Log("Fallback reset.");
|
||||
}
|
||||
|
||||
// Reset connectivity flag
|
||||
if (this.ConnectivityFlag) {
|
||||
this.ConnectivityFlag = null;
|
||||
if (this.ConnectivityCallback) {
|
||||
this.ConnectivityCallback(null);
|
||||
}
|
||||
}
|
||||
|
||||
this.Logger.Log("3LAS stopped successfully.");
|
||||
} catch (e) {
|
||||
this.Logger.Log("Error while stopping 3LAS: " + e);
|
||||
}
|
||||
};
|
||||
_3LAS.prototype.OnActivity = function () {
|
||||
if (this.ActivityCallback)
|
||||
this.ActivityCallback();
|
||||
if (!this.ConnectivityFlag) {
|
||||
this.ConnectivityFlag = true;
|
||||
if (this.ConnectivityCallback)
|
||||
this.ConnectivityCallback(true);
|
||||
}
|
||||
};
|
||||
// Callback function from socket connection
|
||||
_3LAS.prototype.OnSocketError = function (message) {
|
||||
this.Logger.Log("Network error: " + message);
|
||||
this.Fallback.OnSocketError(message);
|
||||
};
|
||||
_3LAS.prototype.OnSocketConnect = function () {
|
||||
this.Logger.Log("Established connection with server.");
|
||||
this.Fallback.OnSocketConnect();
|
||||
this.Fallback.Init(this.WebSocket);
|
||||
};
|
||||
_3LAS.prototype.OnSocketDisconnect = function () {
|
||||
this.Logger.Log("Lost connection to server.");
|
||||
this.Fallback.OnSocketDisconnect();
|
||||
this.Fallback.Reset();
|
||||
if (this.ConnectivityFlag) {
|
||||
this.ConnectivityFlag = false;
|
||||
if (this.ConnectivityCallback)
|
||||
this.ConnectivityCallback(false);
|
||||
}
|
||||
};
|
||||
|
||||
_3LAS.prototype.OnSocketDataReady = function (data) {
|
||||
this.Fallback.OnSocketDataReady(data);
|
||||
};
|
||||
return _3LAS;
|
||||
}());
|
||||
@@ -1,158 +0,0 @@
|
||||
/*
|
||||
Socket fallback is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var Fallback_Settings = /** @class */ (function () {
|
||||
function Fallback_Settings() {
|
||||
this.Formats = [
|
||||
{ "Mime": "audio/mpeg", "Name": "mp3" },
|
||||
{ "Mime": "audio/wave", "Name": "wav" }
|
||||
];
|
||||
this.MaxVolume = 1.0;
|
||||
this.AutoCorrectSpeed = false;
|
||||
this.InitialBufferLength = 1.0 / 3.0;
|
||||
}
|
||||
return Fallback_Settings;
|
||||
}());
|
||||
var Fallback = /** @class */ (function () {
|
||||
function Fallback(logger, settings) {
|
||||
this.Logger = logger;
|
||||
if (!this.Logger) this.Logger = new Logging(null, null);
|
||||
// Create audio context
|
||||
if (typeof AudioContext !== "undefined") this.Audio = new AudioContext();
|
||||
else if (typeof webkitAudioContext !== "undefined") this.Audio = new webkitAudioContext();
|
||||
else if (typeof mozAudioContext !== "undefined") this.Audio = new mozAudioContext();
|
||||
else {
|
||||
this.Logger.Log('3LAS: Browser does not support "AudioContext".');
|
||||
throw new Error();
|
||||
}
|
||||
this.Settings = settings;
|
||||
this.Logger.Log("Detected: " +
|
||||
(OSName == "MacOSX" ? "Mac OSX" : (OSName == "Unknown" ? "Unknown OS" : OSName)) + ", " +
|
||||
(BrowserName == "IE" ? "Internet Explorer" : (BrowserName == "NativeChrome" ? "Chrome legacy" : (BrowserName == "Unknown" ? "Unknown Browser" : BrowserName))));
|
||||
this.SelectedFormatMime = "";
|
||||
this.SelectedFormatName = "";
|
||||
for (var i = 0; i < this.Settings.Formats.length; i++) {
|
||||
if (!AudioFormatReader.CanDecodeTypes([this.Settings.Formats[i].Mime]))
|
||||
continue;
|
||||
this.SelectedFormatMime = this.Settings.Formats[i].Mime;
|
||||
this.SelectedFormatName = this.Settings.Formats[i].Name;
|
||||
break;
|
||||
}
|
||||
if (this.SelectedFormatMime == "" || this.SelectedFormatName == "") {
|
||||
this.Logger.Log("None of the available MIME types are supported.");
|
||||
throw new Error();
|
||||
}
|
||||
this.Logger.Log("Using websocket fallback with MIME: " + this.SelectedFormatMime);
|
||||
try {
|
||||
this.Player = new LiveAudioPlayer(this.Audio, this.Logger, this.Settings.MaxVolume, this.Settings.InitialBufferLength, this.Settings.AutoCorrectSpeed);
|
||||
this.Logger.Log("Init of LiveAudioPlayer succeeded");
|
||||
}
|
||||
catch (e) {
|
||||
this.Logger.Log("Init of LiveAudioPlayer failed: " + e);
|
||||
throw new Error();
|
||||
}
|
||||
try {
|
||||
this.FormatReader = AudioFormatReader.Create(this.SelectedFormatMime, this.Audio, this.Logger, this.OnReaderError.bind(this), this.Player.CheckBeforeDecode, this.OnReaderDataReady.bind(this), AudioFormatReader.DefaultSettings());
|
||||
this.Logger.Log("Init of AudioFormatReader succeeded");
|
||||
}
|
||||
catch (e) {
|
||||
this.Logger.Log("Init of AudioFormatReader failed: " + e);
|
||||
throw new Error();
|
||||
}
|
||||
this.PacketModCounter = 0;
|
||||
this.LastCheckTime = 0;
|
||||
this.FocusChecker = 0;
|
||||
}
|
||||
Fallback.prototype.Init = function (webSocket) {
|
||||
this.MobileUnmute();
|
||||
this.WebSocket = webSocket;
|
||||
this.WebSocket?.Send(JSON.stringify({
|
||||
"type": "fallback",
|
||||
"data": this.SelectedFormatName
|
||||
}));
|
||||
this.StartFocusChecker();
|
||||
};
|
||||
Fallback.prototype.MobileUnmute = function () {
|
||||
var amplification = this.Audio.createGain();
|
||||
// Set volume to max
|
||||
amplification.gain.value = 1.0;
|
||||
// Connect gain node to context
|
||||
amplification.connect(this.Audio.destination);
|
||||
// Create one second buffer with silence
|
||||
var audioBuffer = this.Audio.createBuffer(2, this.Audio.sampleRate, this.Audio.sampleRate);
|
||||
// Create new audio source for the buffer
|
||||
var sourceNode = this.Audio.createBufferSource();
|
||||
// Make sure the node deletes itself after playback
|
||||
sourceNode.onended = function (_ev) {
|
||||
sourceNode.disconnect();
|
||||
amplification.disconnect();
|
||||
};
|
||||
// Pass audio data to source
|
||||
sourceNode.buffer = audioBuffer;
|
||||
// Connect the source to the gain node
|
||||
sourceNode.connect(amplification);
|
||||
// Play source
|
||||
sourceNode.start();
|
||||
};
|
||||
Object.defineProperty(Fallback.prototype, "Volume", {
|
||||
get: function () {
|
||||
return this.Player.Volume / this.Settings.MaxVolume;
|
||||
},
|
||||
set: function (value) {
|
||||
this.Player.Volume = value * this.Settings.MaxVolume;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
// Callback functions from format reader
|
||||
Fallback.prototype.OnReaderError = function () {
|
||||
this.Logger.Log("Reader error: Decoding failed.");
|
||||
};
|
||||
Fallback.prototype.OnReaderDataReady = function () {
|
||||
while (this.FormatReader.SamplesAvailable()) {
|
||||
this.Player.PushBuffer(this.FormatReader.PopSamples());
|
||||
}
|
||||
};
|
||||
// Callback function from socket connection
|
||||
Fallback.prototype.OnSocketError = function (message) {};
|
||||
Fallback.prototype.OnSocketConnect = function () {};
|
||||
Fallback.prototype.OnSocketDisconnect = function () {};
|
||||
Fallback.prototype.OnSocketDataReady = function (data) {
|
||||
this.PacketModCounter++;
|
||||
if (this.PacketModCounter > 100) {
|
||||
if (this.ActivityCallback) this.ActivityCallback();
|
||||
this.PacketModCounter = 0;
|
||||
}
|
||||
this.FormatReader.PushData(new Uint8Array(data));
|
||||
};
|
||||
Fallback.prototype.StartFocusChecker = function () {
|
||||
if (!this.FocusChecker) {
|
||||
this.LastCheckTime = Date.now();
|
||||
this.FocusChecker = window.setInterval(this.CheckFocus.bind(this), 2000);
|
||||
}
|
||||
};
|
||||
Fallback.prototype.StopFocusChecker = function () {
|
||||
if (this.FocusChecker) {
|
||||
window.clearInterval(this.FocusChecker);
|
||||
this.FocusChecker = 0;
|
||||
}
|
||||
};
|
||||
Fallback.prototype.CheckFocus = function () {
|
||||
var checkTime = Date.now();
|
||||
// Check if focus was lost
|
||||
if (checkTime - this.LastCheckTime > 10000) {
|
||||
// If so, drop all samples in the buffer
|
||||
this.Logger.Log("Focus lost, purging format reader.");
|
||||
this.FormatReader.PurgeData();
|
||||
}
|
||||
this.LastCheckTime = checkTime;
|
||||
};
|
||||
Fallback.prototype.Reset = function () {
|
||||
this.StopFocusChecker();
|
||||
this.FormatReader.Reset();
|
||||
this.Player.Reset();
|
||||
this.WebSocket = null;
|
||||
};
|
||||
return Fallback;
|
||||
}());
|
||||
@@ -1,193 +0,0 @@
|
||||
/*
|
||||
Audio format reader is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var AudioFormatReader = /** @class */ (function () {
|
||||
function AudioFormatReader(audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback) {
|
||||
if (!audio)
|
||||
throw new Error('AudioFormatReader: audio must be specified');
|
||||
// Check callback argument
|
||||
if (typeof errorCallback !== 'function')
|
||||
throw new Error('AudioFormatReader: errorCallback must be specified');
|
||||
if (typeof beforeDecodeCheck !== 'function')
|
||||
throw new Error('AudioFormatReader: beforeDecodeCheck must be specified');
|
||||
if (typeof dataReadyCallback !== 'function')
|
||||
throw new Error('AudioFormatReader: dataReadyCallback must be specified');
|
||||
this.Audio = audio;
|
||||
this.Logger = logger;
|
||||
this.ErrorCallback = errorCallback;
|
||||
this.BeforeDecodeCheck = beforeDecodeCheck;
|
||||
this.DataReadyCallback = dataReadyCallback;
|
||||
this.Id = 0;
|
||||
this.LastPushedId = -1;
|
||||
this.Samples = new Array();
|
||||
this.BufferStore = {};
|
||||
this.DataBuffer = new Uint8Array(0);
|
||||
}
|
||||
// Pushes frame data into the buffer
|
||||
AudioFormatReader.prototype.PushData = function (data) {
|
||||
// Append data to framedata buffer
|
||||
this.DataBuffer = this.ConcatUint8Array(this.DataBuffer, data);
|
||||
// Try to extract frames
|
||||
this.ExtractAll();
|
||||
};
|
||||
// Check if samples are available
|
||||
AudioFormatReader.prototype.SamplesAvailable = function () {
|
||||
return (this.Samples.length > 0);
|
||||
};
|
||||
// Get a single bunch of sampels from the reader
|
||||
AudioFormatReader.prototype.PopSamples = function () {
|
||||
if (this.Samples.length > 0) {
|
||||
// Get first bunch of samples, remove said bunch from the array and hand it back to callee
|
||||
return this.Samples.shift();
|
||||
}
|
||||
else
|
||||
return null;
|
||||
};
|
||||
// Deletes all encoded and decoded data from the reader (does not effect headers, etc.)
|
||||
AudioFormatReader.prototype.PurgeData = function () {
|
||||
this.Id = 0;
|
||||
this.LastPushedId = -1;
|
||||
this.Samples = new Array();
|
||||
this.BufferStore = {};
|
||||
this.DataBuffer = new Uint8Array(0);
|
||||
};
|
||||
// Used to force frame extraction externaly
|
||||
AudioFormatReader.prototype.Poke = function () {
|
||||
this.ExtractAll();
|
||||
};
|
||||
// Deletes all data from the reader (does effect headers, etc.)
|
||||
AudioFormatReader.prototype.Reset = function () {
|
||||
this.PurgeData();
|
||||
};
|
||||
// Extracts and converts the raw data
|
||||
AudioFormatReader.prototype.ExtractAll = function () {
|
||||
};
|
||||
// Checks if a decode makes sense
|
||||
AudioFormatReader.prototype.OnBeforeDecode = function (id, duration) {
|
||||
return true;
|
||||
//TODO Fix this
|
||||
/*
|
||||
if(this.BeforeDecodeCheck(duration)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
this.OnDataReady(id, this.Audio.createBuffer(1, Math.ceil(duration * this.Audio.sampleRate), this.Audio.sampleRate));
|
||||
return false;
|
||||
}
|
||||
*/
|
||||
};
|
||||
// Stores the converted bnuches of samples in right order
|
||||
AudioFormatReader.prototype.OnDataReady = function (id, audioBuffer) {
|
||||
if (this.LastPushedId + 1 == id) {
|
||||
// Push samples into array
|
||||
this.Samples.push(audioBuffer);
|
||||
this.LastPushedId++;
|
||||
while (this.BufferStore[this.LastPushedId + 1]) {
|
||||
// Push samples we decoded earlier in correct order
|
||||
this.Samples.push(this.BufferStore[this.LastPushedId + 1]);
|
||||
delete this.BufferStore[this.LastPushedId + 1];
|
||||
this.LastPushedId++;
|
||||
}
|
||||
// Callback to tell that data is ready
|
||||
this.DataReadyCallback();
|
||||
}
|
||||
else {
|
||||
// Is out of order, will be pushed later
|
||||
this.BufferStore[id] = audioBuffer;
|
||||
}
|
||||
};
|
||||
// Used to concatenate two Uint8Array (b comes BEHIND a)
|
||||
AudioFormatReader.prototype.ConcatUint8Array = function (a, b) {
|
||||
var tmp = new Uint8Array(a.length + b.length);
|
||||
tmp.set(a, 0);
|
||||
tmp.set(b, a.length);
|
||||
return tmp;
|
||||
};
|
||||
AudioFormatReader.CanDecodeTypes = function (mimeTypes) {
|
||||
var audioTag = new Audio();
|
||||
var result = false;
|
||||
for (var i = 0; i < mimeTypes.length; i++) {
|
||||
var mimeType = mimeTypes[i];
|
||||
var answer = audioTag.canPlayType(mimeType);
|
||||
if (answer != "probably" && answer != "maybe")
|
||||
continue;
|
||||
result = true;
|
||||
break;
|
||||
}
|
||||
audioTag = null;
|
||||
return result;
|
||||
};
|
||||
AudioFormatReader.DefaultSettings = function () {
|
||||
var settings = {};
|
||||
// WAV
|
||||
settings["wav"] = {};
|
||||
// Duration of wave samples to decode together
|
||||
settings["wav"]["BatchDuration"] = 1 / 10; // 0.1 seconds
|
||||
/*
|
||||
if (isAndroid && isNativeChrome)
|
||||
settings["wav"]["BatchDuration"] = 96 / 375;
|
||||
else if (isAndroid && isFirefox)
|
||||
settings["wav"]["BatchDuration"] = 96 / 375;
|
||||
else
|
||||
settings["wav"]["BatchDuration"] = 16 / 375;
|
||||
*/
|
||||
// Duration of addtional samples to decode to account for edge effects
|
||||
settings["wav"]["ExtraEdgeDuration"] = 1 / 300; // 0.00333... seconds
|
||||
/*
|
||||
if (isAndroid && isNativeChrome)
|
||||
settings["wav"]["ExtraEdgeDuration"] = 1 / 1000;
|
||||
else if (isAndroid && isFirefox)
|
||||
settings["wav"]["ExtraEdgeDuration"] = 1 / 1000;
|
||||
else
|
||||
settings["wav"]["ExtraEdgeDuration"] = 1 / 1000;
|
||||
*/
|
||||
// MPEG
|
||||
settings["mpeg"] = {};
|
||||
// Adds a minimal ID3v2 tag before decoding frames.
|
||||
settings["mpeg"]["AddID3Tag"] = false;
|
||||
// Minimum number of frames to decode together
|
||||
// Theoretical minimum is 2.
|
||||
// Recommended value is 3 or higher.
|
||||
if (isAndroid)
|
||||
settings["mpeg"]["MinDecodeFrames"] = 3;
|
||||
else
|
||||
settings["mpeg"]["MinDecodeFrames"] = 3;
|
||||
return settings;
|
||||
};
|
||||
AudioFormatReader.Create = function (mime, audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback, settings) {
|
||||
if (settings === void 0) { settings = null; }
|
||||
if (typeof mime !== "string")
|
||||
throw new Error('CreateAudioFormatReader: Invalid MIME-Type, must be string');
|
||||
if (!settings)
|
||||
settings = this.DefaultSettings();
|
||||
var fullMime = mime;
|
||||
if (mime.indexOf("audio/pcm") == 0)
|
||||
mime = "audio/pcm";
|
||||
// Load format handler according to MIME-Type
|
||||
switch (mime.replace(/\s/g, "")) {
|
||||
// MPEG Audio (mp3)
|
||||
case "audio/mpeg":
|
||||
case "audio/MPA":
|
||||
case "audio/mpa-robust":
|
||||
if (!AudioFormatReader.CanDecodeTypes(new Array("audio/mpeg", "audio/MPA", "audio/mpa-robust")))
|
||||
throw new Error('CreateAudioFormatReader: Browser can not decode specified MIME-Type (' + mime + ')');
|
||||
return new AudioFormatReader_MPEG(audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback, settings["mpeg"]["AddID3Tag"], settings["mpeg"]["MinDecodeFrames"]);
|
||||
break;
|
||||
// Waveform Audio File Format
|
||||
case "audio/vnd.wave":
|
||||
case "audio/wav":
|
||||
case "audio/wave":
|
||||
case "audio/x-wav":
|
||||
if (!AudioFormatReader.CanDecodeTypes(new Array("audio/wav", "audio/wave")))
|
||||
throw new Error('CreateAudioFormatReader: Browser can not decode specified MIME-Type (' + mime + ')');
|
||||
return new AudioFormatReader_WAV(audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback, settings["wav"]["BatchDuration"], settings["wav"]["ExtraEdgeDuration"]);
|
||||
break;
|
||||
// Unknown codec
|
||||
default:
|
||||
throw new Error('CreateAudioFormatReader: Specified MIME-Type (' + mime + ') not supported');
|
||||
break;
|
||||
}
|
||||
};
|
||||
return AudioFormatReader;
|
||||
}());
|
||||
@@ -1,146 +0,0 @@
|
||||
/*
|
||||
Live audio player is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var LiveAudioPlayer = /** @class */ (function () {
|
||||
function LiveAudioPlayer(audio, logger, maxVolume, startOffset, variableSpeed) {
|
||||
if (maxVolume === void 0) { maxVolume = 1.0; }
|
||||
if (startOffset === void 0) { startOffset = 0.33; }
|
||||
if (variableSpeed === void 0) { variableSpeed = false; }
|
||||
this.Audio = audio;
|
||||
this.Logger = logger;
|
||||
this.MaxVolume = maxVolume;
|
||||
this.StartOffset = startOffset;
|
||||
this.VariableSpeed = variableSpeed;
|
||||
this.OffsetMin = this.StartOffset - LiveAudioPlayer.OffsetVariance;
|
||||
this.OffsetMax = this.StartOffset + LiveAudioPlayer.OffsetVariance;
|
||||
// Set speed to default
|
||||
this.PlaybackSpeed = 1.0;
|
||||
// Reset variable for scheduling times
|
||||
this.NextScheduleTime = 0.0;
|
||||
// Create gain node for volume control
|
||||
this.Amplification = this.Audio.createGain();
|
||||
// Set volume to max
|
||||
this.Amplification.gain.value = 1.0;
|
||||
// Connect gain node to context
|
||||
this.Amplification.connect(this.Audio.destination);
|
||||
}
|
||||
Object.defineProperty(LiveAudioPlayer.prototype, "Volume", {
|
||||
get: function () {
|
||||
// Get volume from gain node
|
||||
return this.Amplification.gain.value;
|
||||
},
|
||||
set: function (value) {
|
||||
// Clamp value to [1e-20 ; MaxVolume]
|
||||
if (value > 1.0)
|
||||
value = this.MaxVolume;
|
||||
else if (value <= 0.0)
|
||||
value = 1e-20;
|
||||
// Cancel any scheduled ramps
|
||||
this.Amplification.gain.cancelScheduledValues(this.Audio.currentTime);
|
||||
// Change volume following a ramp (more userfriendly)
|
||||
this.Amplification.gain.exponentialRampToValueAtTime(value, this.Audio.currentTime + 0.5);
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
// Recieves an audiobuffer and schedules it for seamless playback
|
||||
LiveAudioPlayer.prototype.PushBuffer = function (buffer) {
|
||||
// Check if this is the first buffer we received
|
||||
if (this.NextScheduleTime == 0.0) {
|
||||
// Start playing [StartOffset] s from now
|
||||
this.NextScheduleTime = this.Audio.currentTime + this.StartOffset;
|
||||
}
|
||||
var duration;
|
||||
if (this.VariableSpeed)
|
||||
duration = buffer.duration / this.PlaybackSpeed; // Use regular duration
|
||||
else
|
||||
duration = buffer.duration; // Use duration adjusted for playback speed
|
||||
// Before creating a buffer and scheduling playback, check if playing this buffer makes sense at all
|
||||
// If a buffer should have been started so far in the past that it would have finished playing by now, we are better of skipping it.
|
||||
// But we still need to move the time forward to keep future timings right.
|
||||
if (this.NextScheduleTime + duration > this.Audio.currentTime) {
|
||||
var skipDurationTime = void 0;
|
||||
// If the playback start time is in the past but the playback end time is in the future, we need to partially play the buffer.
|
||||
if (this.Audio.currentTime >= this.NextScheduleTime) {
|
||||
// Calculate the time we need to skip
|
||||
skipDurationTime = this.Audio.currentTime - this.NextScheduleTime + 0.05;
|
||||
}
|
||||
else {
|
||||
// No skipping needed
|
||||
skipDurationTime = 0.0;
|
||||
}
|
||||
// Check if we'd skip the whole buffer anyway
|
||||
if (skipDurationTime < duration) {
|
||||
// Create new audio source for the buffer
|
||||
var sourceNode_1 = this.Audio.createBufferSource();
|
||||
// Make sure the node deletes itself after playback
|
||||
sourceNode_1.onended = function (_ev) {
|
||||
sourceNode_1.disconnect();
|
||||
};
|
||||
// Prevent looping (the standard says that it should be off by default)
|
||||
sourceNode_1.loop = false;
|
||||
// Pass audio data to source
|
||||
sourceNode_1.buffer = buffer;
|
||||
//Connect the source to the gain node
|
||||
sourceNode_1.connect(this.Amplification);
|
||||
if (this.VariableSpeed) {
|
||||
var scheduleOffset = this.NextScheduleTime - this.Audio.currentTime;
|
||||
// Check if we are to far or too close to target schedule time
|
||||
if (this.NextScheduleTime - this.Audio.currentTime > this.OffsetMax) {
|
||||
if (this.PlaybackSpeed < 1.0 + LiveAudioPlayer.SpeedCorrectionFactor) {
|
||||
// We are too slow, speed up playback (somewhat noticeable)
|
||||
this.Logger.Log("Buffer size too large, speeding up playback.");
|
||||
this.PlaybackSpeed = 1.0 + LiveAudioPlayer.SpeedCorrectionFactor;
|
||||
duration = buffer.duration / this.PlaybackSpeed;
|
||||
}
|
||||
}
|
||||
else if (this.NextScheduleTime - this.Audio.currentTime < this.OffsetMin) {
|
||||
if (this.PlaybackSpeed > 1.0 - LiveAudioPlayer.SpeedCorrectionFactor) {
|
||||
// We are too fast, slow down playback (somewhat noticeable)
|
||||
this.Logger.Log("Buffer size too small, slowing down playback.");
|
||||
this.PlaybackSpeed = 1.0 - LiveAudioPlayer.SpeedCorrectionFactor;
|
||||
duration = buffer.duration / this.PlaybackSpeed;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Check if we are in time
|
||||
if ((this.PlaybackSpeed > 1.0 && (this.NextScheduleTime - this.Audio.currentTime < this.StartOffset)) ||
|
||||
(this.PlaybackSpeed < 1.0 && (this.NextScheduleTime - this.Audio.currentTime > this.StartOffset))) {
|
||||
// We are within our min/max offset, set playpacks to default
|
||||
this.Logger.Log("Buffer size within limits, using normal playback speed.");
|
||||
this.PlaybackSpeed = 1.0;
|
||||
duration = buffer.duration;
|
||||
}
|
||||
}
|
||||
// Set playback speed
|
||||
sourceNode_1.playbackRate.value = this.PlaybackSpeed;
|
||||
}
|
||||
// Schedule playback
|
||||
sourceNode_1.start(this.NextScheduleTime + skipDurationTime, skipDurationTime);
|
||||
}
|
||||
else {
|
||||
this.Logger.Log("Skipped buffer because it became too old.");
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.Logger.Log("Skipped buffer because it was too old.");
|
||||
}
|
||||
// Move time forward
|
||||
this.NextScheduleTime += duration;
|
||||
};
|
||||
LiveAudioPlayer.prototype.Reset = function () {
|
||||
this.NextScheduleTime = 0.0;
|
||||
};
|
||||
LiveAudioPlayer.prototype.CheckBeforeDecode = function (playbackLength) {
|
||||
if (this.NextScheduleTime == 0)
|
||||
return true;
|
||||
return this.NextScheduleTime + playbackLength > this.Audio.currentTime;
|
||||
};
|
||||
// Crystal oscillator have a variance of about +/- 20ppm
|
||||
// So worst case would be a difference of 40ppm between two oscillators.
|
||||
LiveAudioPlayer.SpeedCorrectionFactor = 40 / 1.0e6;
|
||||
// Hystersis value for speed up/down trigger
|
||||
LiveAudioPlayer.OffsetVariance = 0.2;
|
||||
return LiveAudioPlayer;
|
||||
}());
|
||||
@@ -1,310 +0,0 @@
|
||||
/*
|
||||
MPEG audio format reader is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
window.startTimeConnectionWatchdog = performance.now();
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
if (typeof b !== "function" && b !== null)
|
||||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
var MPEGFrameInfo = /** @class */ (function () {
|
||||
function MPEGFrameInfo(data, sampleCount, sampleRate) {
|
||||
this.Data = data;
|
||||
this.SampleCount = sampleCount;
|
||||
this.SampleRate = sampleRate;
|
||||
}
|
||||
return MPEGFrameInfo;
|
||||
}());
|
||||
var AudioFormatReader_MPEG = /** @class */ (function (_super) {
|
||||
__extends(AudioFormatReader_MPEG, _super);
|
||||
function AudioFormatReader_MPEG(audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback, addId3Tag, minDecodeFrames) {
|
||||
var _this = _super.call(this, audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback) || this;
|
||||
_this._OnDecodeSuccess = _this.OnDecodeSuccess.bind(_this);
|
||||
_this._OnDecodeError = _this.OnDecodeError.bind(_this);
|
||||
_this.AddId3Tag = addId3Tag;
|
||||
_this.MinDecodeFrames = minDecodeFrames;
|
||||
_this.Frames = new Array();
|
||||
_this.FrameStartIdx = -1;
|
||||
_this.FrameEndIdx = -1;
|
||||
_this.FrameSamples = 0;
|
||||
_this.FrameSampleRate = 0;
|
||||
_this.TimeBudget = 0;
|
||||
return _this;
|
||||
}
|
||||
// Deletes all frames from the databuffer and framearray and all samples from the samplearray
|
||||
AudioFormatReader_MPEG.prototype.PurgeData = function () {
|
||||
_super.prototype.PurgeData.call(this);
|
||||
this.Frames = new Array();
|
||||
this.FrameStartIdx = -1;
|
||||
this.FrameEndIdx = -1;
|
||||
this.FrameSamples = 0;
|
||||
this.FrameSampleRate = 0;
|
||||
this.TimeBudget = 0;
|
||||
};
|
||||
// Extracts all currently possible frames
|
||||
AudioFormatReader_MPEG.prototype.ExtractAll = function () {
|
||||
// Look for frames
|
||||
this.FindFrame();
|
||||
// Repeat as long as we can extract frames
|
||||
while (this.CanExtractFrame()) {
|
||||
// Extract frame and push into array
|
||||
this.Frames.push(this.ExtractFrame());
|
||||
// Look for frames
|
||||
this.FindFrame();
|
||||
}
|
||||
// Check if we have enough frames to decode
|
||||
if (this.Frames.length >= this.MinDecodeFrames) {
|
||||
// Note:
|
||||
// =====
|
||||
// mp3 frames have an overlap of [granule size] so we can't use the first or last [granule size] samples.
|
||||
// [granule size] is equal to half of a [frame size] in samples (using the mp3's sample rate).
|
||||
// Sum up the playback time of each decoded frame and data buffer lengths
|
||||
// Note: Since mp3-Frames overlap by half of their sample-length we expect the
|
||||
// first and last frame to be only half as long. Some decoders will still output
|
||||
// the full frame length by adding zeros.
|
||||
var bufferLength = 0;
|
||||
var expectedTotalPlayTime_1 = 0;
|
||||
var firstGranulePlayTime_1 = 0;
|
||||
var lastGranulePlayTime_1 = 0;
|
||||
firstGranulePlayTime_1 = this.Frames[0].SampleCount / this.Frames[0].SampleRate / 2.0; // Only half of data is usable due to overlap
|
||||
expectedTotalPlayTime_1 += firstGranulePlayTime_1;
|
||||
bufferLength += this.Frames[0].Data.length;
|
||||
for (var i = 1; i < this.Frames.length - 1; i++) {
|
||||
expectedTotalPlayTime_1 += this.Frames[i].SampleCount / this.Frames[i].SampleRate;
|
||||
bufferLength += this.Frames[i].Data.length;
|
||||
}
|
||||
lastGranulePlayTime_1 = this.Frames[this.Frames.length - 1].SampleCount / this.Frames[this.Frames.length - 1].SampleRate / 2.0; // Only half of data is usable due to overlap
|
||||
expectedTotalPlayTime_1 += lastGranulePlayTime_1;
|
||||
bufferLength += this.Frames[this.Frames.length - 1].Data.length;
|
||||
// If needed, add some space for the ID3v2 tag
|
||||
if (this.AddId3Tag) bufferLength += AudioFormatReader_MPEG.Id3v2Tag.length;
|
||||
// Create a buffer long enough to hold everything
|
||||
var decodeBuffer = new Uint8Array(bufferLength);
|
||||
var offset = 0;
|
||||
// If needed, add ID3v2 tag to beginning of buffer
|
||||
if (this.AddId3Tag) {
|
||||
decodeBuffer.set(AudioFormatReader_MPEG.Id3v2Tag, offset);
|
||||
offset += AudioFormatReader_MPEG.Id3v2Tag.length;
|
||||
}
|
||||
// Add the frames to the window
|
||||
for (var i = 0; i < this.Frames.length; i++) {
|
||||
decodeBuffer.set(this.Frames[i].Data, offset);
|
||||
offset += this.Frames[i].Data.length;
|
||||
}
|
||||
// Remove the used frames from the array
|
||||
this.Frames.splice(0, this.Frames.length - 1);
|
||||
// Increment Id
|
||||
var id_1 = this.Id++;
|
||||
// Check if decoded frames might be too far back in the past
|
||||
if (!this.OnBeforeDecode(id_1, expectedTotalPlayTime_1)) return;
|
||||
// Push window to the decoder
|
||||
this.Audio.decodeAudioData(decodeBuffer.buffer, (function (decodedData) {
|
||||
var _id = id_1;
|
||||
var _expectedTotalPlayTime = expectedTotalPlayTime_1;
|
||||
var _firstGranulePlayTime = firstGranulePlayTime_1;
|
||||
var _lastGranulePlayTime = lastGranulePlayTime_1;
|
||||
this._OnDecodeSuccess(decodedData, _id, _expectedTotalPlayTime, _firstGranulePlayTime, _lastGranulePlayTime);
|
||||
}).bind(this), this._OnDecodeError.bind(this));
|
||||
}
|
||||
};
|
||||
// Finds frame boundries within the data buffer
|
||||
AudioFormatReader_MPEG.prototype.FindFrame = function () {
|
||||
// Find frame start
|
||||
if (this.FrameStartIdx < 0) {
|
||||
var i = 0;
|
||||
// Make sure we don't exceed array bounds
|
||||
while ((i + 1) < this.DataBuffer.length) {
|
||||
// Look for MPEG sync word
|
||||
if (this.DataBuffer[i] == 0xFF && (this.DataBuffer[i + 1] & 0xE0) == 0xE0) {
|
||||
// Sync found, set frame start
|
||||
this.FrameStartIdx = i;
|
||||
break;
|
||||
} i++;
|
||||
}
|
||||
}
|
||||
// Find frame end
|
||||
if (this.FrameStartIdx >= 0 && this.FrameEndIdx < 0) {
|
||||
// Check if we have enough data to process the header
|
||||
if ((this.FrameStartIdx + 2) < this.DataBuffer.length) {
|
||||
// Get header data
|
||||
// Version index
|
||||
var ver = (this.DataBuffer[this.FrameStartIdx + 1] & 0x18) >>> 3;
|
||||
// Layer index
|
||||
var lyr = (this.DataBuffer[this.FrameStartIdx + 1] & 0x06) >>> 1;
|
||||
// Padding? 0/1
|
||||
var pad = (this.DataBuffer[this.FrameStartIdx + 2] & 0x02) >>> 1;
|
||||
// Bitrate index
|
||||
var brx = (this.DataBuffer[this.FrameStartIdx + 2] & 0xF0) >>> 4;
|
||||
// SampRate index
|
||||
var srx = (this.DataBuffer[this.FrameStartIdx + 2] & 0x0C) >>> 2;
|
||||
// Resolve flags to real values
|
||||
var bitrate = AudioFormatReader_MPEG.MPEG_bitrates[ver][lyr][brx] * 1000;
|
||||
var samprate = AudioFormatReader_MPEG.MPEG_srates[ver][srx];
|
||||
var samples = AudioFormatReader_MPEG.MPEG_frame_samples[ver][lyr];
|
||||
var slot_size = AudioFormatReader_MPEG.MPEG_slot_size[lyr];
|
||||
// In-between calculations
|
||||
var bps = samples / 8.0;
|
||||
var fsize = ((bps * bitrate) / samprate) + ((pad == 1) ? slot_size : 0);
|
||||
// Truncate to integer
|
||||
var frameSize = Math.floor(fsize);
|
||||
// Store number of samples and samplerate for frame
|
||||
this.FrameSamples = samples;
|
||||
this.FrameSampleRate = samprate;
|
||||
// Set end frame boundry
|
||||
this.FrameEndIdx = this.FrameStartIdx + frameSize;
|
||||
}
|
||||
}
|
||||
};
|
||||
// Checks if there is a frame ready to be extracted
|
||||
AudioFormatReader_MPEG.prototype.CanExtractFrame = function () {
|
||||
if (this.FrameStartIdx < 0 || this.FrameEndIdx < 0) return false;
|
||||
else if (this.FrameEndIdx <= this.DataBuffer.length) return true;
|
||||
else return false;
|
||||
};
|
||||
// Extract a single frame from the buffer
|
||||
AudioFormatReader_MPEG.prototype.ExtractFrame = function () {
|
||||
// Extract frame data from buffer
|
||||
var frameArray = this.DataBuffer.buffer.slice(this.FrameStartIdx, this.FrameEndIdx);
|
||||
// Remove frame from buffer
|
||||
if ((this.FrameEndIdx + 1) < this.DataBuffer.length) this.DataBuffer = new Uint8Array(this.DataBuffer.buffer.slice(this.FrameEndIdx));
|
||||
else this.DataBuffer = new Uint8Array(0);
|
||||
// Reset Start/End indices
|
||||
this.FrameStartIdx = 0;
|
||||
this.FrameEndIdx = -1;
|
||||
return new MPEGFrameInfo(new Uint8Array(frameArray), this.FrameSamples, this.FrameSampleRate);
|
||||
};
|
||||
// Is called if the decoding of the window succeeded
|
||||
AudioFormatReader_MPEG.prototype.OnDecodeSuccess = function (decodedData, id, expectedTotalPlayTime, firstGranulePlayTime, lastGranulePlayTime) {
|
||||
window.startTimeConnectionWatchdog = performance.now();
|
||||
var extractSampleCount;
|
||||
var extractSampleOffset;
|
||||
var delta = 0.001;
|
||||
// Check if we got the expected number of samples
|
||||
if (expectedTotalPlayTime > decodedData.duration) {
|
||||
// We got less samples than expect, we suspect that they were truncated equally at start and end.
|
||||
// This can happen in case of sample rate conversions.
|
||||
extractSampleCount = decodedData.length;
|
||||
extractSampleOffset = 0;
|
||||
this.TimeBudget += (expectedTotalPlayTime - decodedData.duration);
|
||||
}
|
||||
else if (expectedTotalPlayTime < decodedData.duration) {
|
||||
// We got more samples than expect, we suspect that zeros were added equally at start and end.
|
||||
// This can happen in case of sample rate conversions or edge frame handling.
|
||||
extractSampleCount = Math.ceil(expectedTotalPlayTime * decodedData.sampleRate);
|
||||
var budgetSamples = this.TimeBudget * decodedData.sampleRate;
|
||||
if (budgetSamples > 1.0) {
|
||||
if (budgetSamples > decodedData.length - extractSampleCount) {
|
||||
budgetSamples = decodedData.length - extractSampleCount;
|
||||
}
|
||||
extractSampleCount += budgetSamples;
|
||||
this.TimeBudget -= (budgetSamples / decodedData.sampleRate);
|
||||
}
|
||||
var diff = decodedData.duration - expectedTotalPlayTime;
|
||||
if ((diff - firstGranulePlayTime - lastGranulePlayTime) >= -delta) {
|
||||
// Both first and last granule are present. Cut out middle section.
|
||||
extractSampleOffset = Math.floor((decodedData.length - extractSampleCount) / 2);
|
||||
}
|
||||
if (Math.abs(firstGranulePlayTime - lastGranulePlayTime) <= delta) {
|
||||
// First and last granule are equal. We need to make an educated guess which one is present.
|
||||
if (isIOS || isIPadOS || isMacOSX) {
|
||||
// I don't know why, but Apple does things differently.
|
||||
extractSampleOffset = Math.floor((decodedData.length - extractSampleCount) / 2);
|
||||
}
|
||||
else {
|
||||
// Assume last granule is present.
|
||||
extractSampleOffset = decodedData.length - extractSampleCount;
|
||||
}
|
||||
}
|
||||
else if (Math.abs(diff - firstGranulePlayTime) <= delta) {
|
||||
// Last granule is present.
|
||||
extractSampleOffset = decodedData.length - extractSampleCount;
|
||||
}
|
||||
else if (Math.abs(diff - lastGranulePlayTime) <= delta) {
|
||||
// First granule is present.
|
||||
extractSampleOffset = 0;
|
||||
}
|
||||
else {
|
||||
// The difference is not equal to neither the first, the last nor the sum of both granule. So we just use the middle.
|
||||
extractSampleOffset = Math.floor((decodedData.length - extractSampleCount) / 2);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// We got the expected number of samples, no adaption needed
|
||||
extractSampleCount = decodedData.length;
|
||||
extractSampleOffset = 0;
|
||||
}
|
||||
// Create a buffer that can hold the frame to extract
|
||||
var audioBuffer = this.Audio.createBuffer(decodedData.numberOfChannels, extractSampleCount, decodedData.sampleRate);
|
||||
// Fill buffer with the last part of the decoded frame leave out last granule
|
||||
for (var i = 0; i < decodedData.numberOfChannels; i++)
|
||||
audioBuffer.getChannelData(i).set(decodedData.getChannelData(i).subarray(extractSampleOffset, extractSampleOffset + extractSampleCount));
|
||||
this.OnDataReady(id, audioBuffer);
|
||||
};
|
||||
// Is called in case the decoding of the window fails
|
||||
AudioFormatReader_MPEG.prototype.OnDecodeError = function (_error) {
|
||||
this.ErrorCallback();
|
||||
};
|
||||
// MPEG versions - use [version]
|
||||
AudioFormatReader_MPEG.MPEG_versions = new Array(25, 0, 2, 1);
|
||||
// Layers - use [layer]
|
||||
AudioFormatReader_MPEG.MPEG_layers = new Array(0, 3, 2, 1);
|
||||
// Bitrates - use [version][layer][bitrate]
|
||||
AudioFormatReader_MPEG.MPEG_bitrates = new Array(new Array(// Version 2.5
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Reserved
|
||||
new Array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0), // Layer 3
|
||||
new Array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0), // Layer 2
|
||||
new Array(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0) // Layer 1
|
||||
), new Array(// Reserved
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Invalid
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Invalid
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Invalid
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // Invalid
|
||||
), new Array(// Version 2
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Reserved
|
||||
new Array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0), // Layer 3
|
||||
new Array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0), // Layer 2
|
||||
new Array(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0) // Layer 1
|
||||
), new Array(// Version 1
|
||||
new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), // Reserved
|
||||
new Array(0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0), // Layer 3
|
||||
new Array(0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0), // Layer 2
|
||||
new Array(0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0) // Layer 1
|
||||
));
|
||||
// Sample rates - use [version][srate]
|
||||
AudioFormatReader_MPEG.MPEG_srates = new Array(new Array(11025, 12000, 8000, 0), // MPEG 2.5
|
||||
new Array(0, 0, 0, 0), // Reserved
|
||||
new Array(22050, 24000, 16000, 0), // MPEG 2
|
||||
new Array(44100, 48000, 32000, 0) // MPEG 1
|
||||
);
|
||||
// Samples per frame - use [version][layer]
|
||||
AudioFormatReader_MPEG.MPEG_frame_samples = new Array(
|
||||
// Rsvd 3 2 1 < Layer v Version
|
||||
new Array(0, 576, 1152, 384), // 2.5
|
||||
new Array(0, 0, 0, 0), // Reserved
|
||||
new Array(0, 576, 1152, 384), // 2
|
||||
new Array(0, 1152, 1152, 384) // 1
|
||||
);
|
||||
AudioFormatReader_MPEG.Id3v2Tag = new Uint8Array(new Array(0x49, 0x44, 0x33, // File identifier: "ID3"
|
||||
0x03, 0x00, // Version 2.3
|
||||
0x00, // Flags: no unsynchronisation, no extended header, no experimental indicator
|
||||
0x00, 0x00, 0x00, 0x0D, // Size of the (tag-)frames, extended header and padding
|
||||
0x54, 0x49, 0x54, 0x32, // Title frame: "TIT2"
|
||||
0x00, 0x00, 0x00, 0x02, // Size of the frame data
|
||||
0x00, 0x00, // Frame Flags
|
||||
0x00, 0x20, 0x00 // Frame data (space character) and padding
|
||||
));
|
||||
// Slot size (MPEG unit of measurement) - use [layer]
|
||||
AudioFormatReader_MPEG.MPEG_slot_size = new Array(0, 1, 1, 4); // Rsvd, 3, 2, 1
|
||||
return AudioFormatReader_MPEG;
|
||||
}(AudioFormatReader));
|
||||
@@ -1,222 +0,0 @@
|
||||
/*
|
||||
WAV audio format reader is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
if (typeof b !== "function" && b !== null)
|
||||
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
var AudioFormatReader_WAV = /** @class */ (function (_super) {
|
||||
__extends(AudioFormatReader_WAV, _super);
|
||||
function AudioFormatReader_WAV(audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback, batchDuration, extraEdgeDuration) {
|
||||
var _this = _super.call(this, audio, logger, errorCallback, beforeDecodeCheck, dataReadyCallback) || this;
|
||||
_this._OnDecodeSuccess = _this.OnDecodeSuccess.bind(_this);
|
||||
_this._OnDecodeError = _this.OnDecodeError.bind(_this);
|
||||
_this.BatchDuration = batchDuration;
|
||||
_this.ExtraEdgeDuration = extraEdgeDuration;
|
||||
_this.GotHeader = false;
|
||||
_this.RiffHeader = null;
|
||||
_this.WaveSampleRate = 0;
|
||||
_this.WaveBitsPerSample = 0;
|
||||
_this.WaveBytesPerSample = 0;
|
||||
_this.WaveBlockAlign = 0;
|
||||
_this.WaveChannels = 0;
|
||||
_this.BatchSamples = 0;
|
||||
_this.BatchBytes = 0;
|
||||
_this.ExtraEdgeSamples = 0;
|
||||
_this.TotalBatchSampleSize = 0;
|
||||
_this.TotalBatchByteSize = 0;
|
||||
_this.SampleBudget = 0;
|
||||
return _this;
|
||||
}
|
||||
// Deletes all samples from the databuffer and the samplearray
|
||||
AudioFormatReader_WAV.prototype.PurgeData = function () {
|
||||
_super.prototype.PurgeData.call(this);
|
||||
this.SampleBudget = 0;
|
||||
};
|
||||
// Deletes all data from the reader (deos effect headers, etc.)
|
||||
AudioFormatReader_WAV.prototype.Reset = function () {
|
||||
_super.prototype.Reset.call(this);
|
||||
this.GotHeader = false;
|
||||
this.RiffHeader = null;
|
||||
this.WaveSampleRate = 0;
|
||||
this.WaveBitsPerSample = 0;
|
||||
this.WaveBytesPerSample = 0;
|
||||
this.WaveBlockAlign = 0;
|
||||
this.WaveChannels = 0;
|
||||
this.BatchSamples = 0;
|
||||
this.BatchBytes = 0;
|
||||
this.ExtraEdgeSamples = 0;
|
||||
this.TotalBatchSampleSize = 0;
|
||||
this.TotalBatchByteSize = 0;
|
||||
this.SampleBudget = 0;
|
||||
};
|
||||
AudioFormatReader_WAV.prototype.ExtractAll = function () {
|
||||
if (!this.GotHeader)
|
||||
this.FindAndExtractHeader();
|
||||
else {
|
||||
var _loop_1 = function () {
|
||||
// Extract samples
|
||||
var tmpSamples = this_1.ExtractIntSamples();
|
||||
// Increment Id
|
||||
var id = this_1.Id++;
|
||||
if (!this_1.OnBeforeDecode(id, this_1.BatchDuration))
|
||||
return "continue";
|
||||
// Note:
|
||||
// =====
|
||||
// When audio data is resampled we get edge-effects at beginnging and end.
|
||||
// We should be able to compensate for that by keeping the last sample of the
|
||||
// previous batch and adding it to the beginning of the current one, but then
|
||||
// cutting it out AFTER the resampling (since the same effects apply to it)
|
||||
// The effects at the end can be compensated by cutting the resampled samples shorter
|
||||
// This is not trivial for non-natural ratios (e.g. 16kHz -> 44.1kHz). Because we would have
|
||||
// to cut out a non-natural number of samples at beginning and end.
|
||||
// TODO: All of the above...
|
||||
// Create a buffer long enough to hold everything
|
||||
var samplesBuffer = new Uint8Array(this_1.RiffHeader.length + tmpSamples.length);
|
||||
var offset = 0;
|
||||
// Add header
|
||||
samplesBuffer.set(this_1.RiffHeader, offset);
|
||||
offset += this_1.RiffHeader.length;
|
||||
// Add samples
|
||||
samplesBuffer.set(tmpSamples, offset);
|
||||
// Push pages to the decoder
|
||||
this_1.Audio.decodeAudioData(samplesBuffer.buffer, (function (decodedData) {
|
||||
var _id = id;
|
||||
this._OnDecodeSuccess(decodedData, _id);
|
||||
}).bind(this_1), this_1._OnDecodeError);
|
||||
};
|
||||
var this_1 = this;
|
||||
while (this.CanExtractSamples()) {
|
||||
_loop_1();
|
||||
}
|
||||
}
|
||||
};
|
||||
// Finds riff header within the data buffer and extracts it
|
||||
AudioFormatReader_WAV.prototype.FindAndExtractHeader = function () {
|
||||
var curpos = 0;
|
||||
// Make sure a whole header can fit
|
||||
if (!((curpos + 4) < this.DataBuffer.length))
|
||||
return;
|
||||
// Check chunkID, should be "RIFF"
|
||||
if (!(this.DataBuffer[curpos] == 0x52 && this.DataBuffer[curpos + 1] == 0x49 && this.DataBuffer[curpos + 2] == 0x46 && this.DataBuffer[curpos + 3] == 0x46))
|
||||
return;
|
||||
curpos += 8;
|
||||
if (!((curpos + 4) < this.DataBuffer.length))
|
||||
return;
|
||||
// Check riffType, should be "WAVE"
|
||||
if (!(this.DataBuffer[curpos] == 0x57 && this.DataBuffer[curpos + 1] == 0x41 && this.DataBuffer[curpos + 2] == 0x56 && this.DataBuffer[curpos + 3] == 0x45))
|
||||
return;
|
||||
curpos += 4;
|
||||
if (!((curpos + 4) < this.DataBuffer.length))
|
||||
return;
|
||||
// Check for format subchunk, should be "fmt "
|
||||
if (!(this.DataBuffer[curpos] == 0x66 && this.DataBuffer[curpos + 1] == 0x6d && this.DataBuffer[curpos + 2] == 0x74 && this.DataBuffer[curpos + 3] == 0x20))
|
||||
return;
|
||||
curpos += 4;
|
||||
if (!((curpos + 4) < this.DataBuffer.length))
|
||||
return;
|
||||
var subChunkSize = this.DataBuffer[curpos] | this.DataBuffer[curpos + 1] << 8 | this.DataBuffer[curpos + 2] << 16 | this.DataBuffer[curpos + 3] << 24;
|
||||
if (!((curpos + 4 + subChunkSize) < this.DataBuffer.length))
|
||||
return;
|
||||
curpos += 6;
|
||||
this.WaveChannels = this.DataBuffer[curpos] | this.DataBuffer[curpos + 1] << 8;
|
||||
curpos += 2;
|
||||
this.WaveSampleRate = this.DataBuffer[curpos] | this.DataBuffer[curpos + 1] << 8 | this.DataBuffer[curpos + 2] << 16 | this.DataBuffer[curpos + 3] << 24;
|
||||
curpos += 8;
|
||||
this.WaveBlockAlign = this.DataBuffer[curpos] | this.DataBuffer[curpos + 1] << 8;
|
||||
curpos += 2;
|
||||
this.WaveBitsPerSample = this.DataBuffer[curpos] | this.DataBuffer[curpos + 1] << 8;
|
||||
this.WaveBytesPerSample = this.WaveBitsPerSample / 8;
|
||||
curpos += subChunkSize - 14;
|
||||
while (true) {
|
||||
if ((curpos + 8) < this.DataBuffer.length) {
|
||||
subChunkSize = this.DataBuffer[curpos + 4] | this.DataBuffer[curpos + 5] << 8 | this.DataBuffer[curpos + 6] << 16 | this.DataBuffer[curpos + 7] << 24;
|
||||
// Check for data subchunk, should be "data"
|
||||
if (this.DataBuffer[curpos] == 0x64 && this.DataBuffer[curpos + 1] == 0x61 && this.DataBuffer[curpos + 2] == 0x74 && this.DataBuffer[curpos + 3] == 0x61) // Data chunk found
|
||||
break;
|
||||
else
|
||||
curpos += 8 + subChunkSize;
|
||||
}
|
||||
else
|
||||
return;
|
||||
}
|
||||
curpos += 8;
|
||||
this.RiffHeader = new Uint8Array(this.DataBuffer.buffer.slice(0, curpos));
|
||||
this.BatchSamples = Math.ceil(this.BatchDuration * this.WaveSampleRate);
|
||||
this.ExtraEdgeSamples = Math.ceil(this.ExtraEdgeDuration * this.WaveSampleRate);
|
||||
this.BatchBytes = this.BatchSamples * this.WaveBlockAlign;
|
||||
this.TotalBatchSampleSize = (this.BatchSamples + this.ExtraEdgeSamples);
|
||||
this.TotalBatchByteSize = this.TotalBatchSampleSize * this.WaveBlockAlign;
|
||||
var chunkSize = this.RiffHeader.length + this.TotalBatchByteSize - 8;
|
||||
// Fix header chunksizes
|
||||
this.RiffHeader[4] = chunkSize & 0xFF;
|
||||
this.RiffHeader[5] = (chunkSize & 0xFF00) >>> 8;
|
||||
this.RiffHeader[6] = (chunkSize & 0xFF0000) >>> 16;
|
||||
this.RiffHeader[7] = (chunkSize & 0xFF000000) >>> 24;
|
||||
this.RiffHeader[this.RiffHeader.length - 4] = (this.TotalBatchByteSize & 0xFF);
|
||||
this.RiffHeader[this.RiffHeader.length - 3] = (this.TotalBatchByteSize & 0xFF00) >>> 8;
|
||||
this.RiffHeader[this.RiffHeader.length - 2] = (this.TotalBatchByteSize & 0xFF0000) >>> 16;
|
||||
this.RiffHeader[this.RiffHeader.length - 1] = (this.TotalBatchByteSize & 0xFF000000) >>> 24;
|
||||
this.GotHeader = true;
|
||||
};
|
||||
// Checks if there is a samples ready to be extracted
|
||||
AudioFormatReader_WAV.prototype.CanExtractSamples = function () {
|
||||
if (this.DataBuffer.length >= this.TotalBatchByteSize)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
};
|
||||
// Extract a single batch of samples from the buffer
|
||||
AudioFormatReader_WAV.prototype.ExtractIntSamples = function () {
|
||||
// Extract sample data from buffer
|
||||
var intSampleArray = new Uint8Array(this.DataBuffer.buffer.slice(0, this.TotalBatchByteSize));
|
||||
// Remove samples from buffer
|
||||
this.DataBuffer = new Uint8Array(this.DataBuffer.buffer.slice(this.BatchBytes));
|
||||
return intSampleArray;
|
||||
};
|
||||
// Is called if the decoding of the samples succeeded
|
||||
AudioFormatReader_WAV.prototype.OnDecodeSuccess = function (decodedData, id) {
|
||||
// Calculate the length of the parts
|
||||
var pickSize = this.BatchDuration * decodedData.sampleRate;
|
||||
this.SampleBudget += (pickSize - Math.ceil(pickSize));
|
||||
pickSize = Math.ceil(pickSize);
|
||||
var pickOffset = (decodedData.length - pickSize) / 2.0;
|
||||
if (pickOffset < 0)
|
||||
pickOffset = 0; // This should never happen!
|
||||
else
|
||||
pickOffset = Math.floor(pickOffset);
|
||||
if (this.SampleBudget < -1.0) {
|
||||
var correction = -1.0 * Math.floor(Math.abs(this.SampleBudget));
|
||||
this.SampleBudget -= correction;
|
||||
pickSize += correction;
|
||||
}
|
||||
else if (this.SampleBudget > 1.0) {
|
||||
var correction = Math.floor(this.SampleBudget);
|
||||
this.SampleBudget -= correction;
|
||||
pickSize += correction;
|
||||
}
|
||||
// Create a buffer that can hold a single part
|
||||
var audioBuffer = this.Audio.createBuffer(decodedData.numberOfChannels, pickSize, decodedData.sampleRate);
|
||||
// Fill buffer with the last part of the decoded frame
|
||||
for (var i = 0; i < decodedData.numberOfChannels; i++)
|
||||
audioBuffer.getChannelData(i).set(decodedData.getChannelData(i).slice(pickOffset, -pickOffset));
|
||||
this.OnDataReady(id, audioBuffer);
|
||||
};
|
||||
// Is called in case the decoding of the window fails
|
||||
AudioFormatReader_WAV.prototype.OnDecodeError = function (_error) {
|
||||
this.ErrorCallback();
|
||||
};
|
||||
return AudioFormatReader_WAV;
|
||||
}(AudioFormatReader));
|
||||
@@ -1,140 +0,0 @@
|
||||
/*
|
||||
Helpers is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var isAndroid;
|
||||
var isIOS;
|
||||
var isIPadOS;
|
||||
var isWindows;
|
||||
var isLinux;
|
||||
var isBSD;
|
||||
var isMacOSX;
|
||||
var isInternetExplorer;
|
||||
var isEdge;
|
||||
;
|
||||
var isSafari;
|
||||
;
|
||||
var isOpera;
|
||||
;
|
||||
var isChrome;
|
||||
;
|
||||
var isFirefox;
|
||||
;
|
||||
var webkitVer;
|
||||
var isNativeChrome;
|
||||
;
|
||||
var BrowserName;
|
||||
var OSName;
|
||||
{
|
||||
var ua = navigator.userAgent.toLowerCase();
|
||||
isAndroid = (ua.match('android') ? true : false);
|
||||
isIOS = (ua.match(/(iphone|ipod)/g) ? true : false);
|
||||
isIPadOS = ((ua.match('ipad') || (navigator.platform == 'MacIntel' && navigator.maxTouchPoints > 1)) ? true : false);
|
||||
isWindows = (ua.match('windows') ? true : false);
|
||||
isLinux = (ua.match('android') ? false : (ua.match('linux') ? true : false));
|
||||
isBSD = (ua.match('bsd') ? true : false);
|
||||
isMacOSX = !isIOS && !isIPadOS && (ua.match('mac os x') ? true : false);
|
||||
isInternetExplorer = (ua.match('msie') ? true : false);
|
||||
isEdge = (ua.match('edg') ? true : false);
|
||||
isSafari = (ua.match(/(chromium|chrome|crios)/g) ? false : (ua.match('safari') ? true : false));
|
||||
isOpera = (ua.match('opera') ? true : false);
|
||||
isChrome = !isSafari && (ua.match(/(chromium|chrome|crios)/g) ? true : false);
|
||||
isFirefox = (ua.match('like gecko') ? false : (ua.match(/(gecko|fennec|firefox)/g) ? true : false));
|
||||
webkitVer = parseInt((/WebKit\/([0-9]+)/.exec(navigator.appVersion) || ["", "0"])[1], 10) || void 0; // also match AppleWebKit
|
||||
isNativeChrome = isAndroid && webkitVer <= 537 && navigator.vendor.toLowerCase().indexOf('google') == 0;
|
||||
BrowserName = "Unknown";
|
||||
if (isInternetExplorer)
|
||||
BrowserName = "IE";
|
||||
else if (isEdge)
|
||||
BrowserName = "Edge";
|
||||
else if (isSafari)
|
||||
BrowserName = "Safari";
|
||||
else if (isOpera)
|
||||
BrowserName = "Opera";
|
||||
else if (isChrome)
|
||||
BrowserName = "Chrome";
|
||||
else if (isFirefox)
|
||||
BrowserName = "Firefox";
|
||||
else if (isNativeChrome)
|
||||
BrowserName = "NativeChrome";
|
||||
else
|
||||
BrowserName = "Unknown";
|
||||
OSName = "Unknown";
|
||||
if (isAndroid)
|
||||
OSName = "Android";
|
||||
else if (isIOS)
|
||||
OSName = "iOS";
|
||||
else if (isIPadOS)
|
||||
OSName = "iPadOS";
|
||||
else if (isWindows)
|
||||
OSName = "Windows";
|
||||
else if (isLinux)
|
||||
OSName = "Linux";
|
||||
else if (isBSD)
|
||||
OSName = "BSD";
|
||||
else if (isMacOSX)
|
||||
OSName = "MacOSX";
|
||||
else
|
||||
OSName = "Unknown";
|
||||
}
|
||||
;
|
||||
var WakeLock = /** @class */ (function () {
|
||||
function WakeLock(logger) {
|
||||
this.Logger = logger;
|
||||
this.Logger.Log("Preparing WakeLock");
|
||||
if (typeof navigator.wakeLock == "undefined") {
|
||||
this.Logger.Log("Using video loop method.");
|
||||
var video = document.createElement('video');
|
||||
video.setAttribute('loop', '');
|
||||
video.setAttribute('style', 'position: fixed; opacity: 0.1; pointer-events: none;');
|
||||
WakeLock.AddSourceToVideo(video, 'webm', 'data:video/webm;base64,' + WakeLock.VideoWebm);
|
||||
WakeLock.AddSourceToVideo(video, 'mp4', 'data:video/mp4;base64,' + WakeLock.VideoMp4);
|
||||
document.body.appendChild(video);
|
||||
this.LockElement = video;
|
||||
}
|
||||
else {
|
||||
this.Logger.Log("Using WakeLock API.");
|
||||
this.LockElement = null;
|
||||
}
|
||||
}
|
||||
WakeLock.prototype.Begin = function () {
|
||||
var _this = this;
|
||||
if (this.LockElement == null) {
|
||||
try {
|
||||
navigator.wakeLock.request("screen").then(function (obj) {
|
||||
_this.Logger.Log("WakeLock request successful. Lock acquired.");
|
||||
_this.LockElement = obj; // Not an audio/video element
|
||||
console.log("WakeLock request successful.");
|
||||
}, function () {
|
||||
_this.Logger.Log("WakeLock request failed.");
|
||||
console.log("WakeLock request failed.");
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
this.Logger.Log("WakeLock request failed.");
|
||||
console.log("WakeLock request failed.");
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.Logger.Log("WakeLock video loop started.");
|
||||
|
||||
// Ensure it's an audio/video element before calling play()
|
||||
if (_this.LockElement instanceof HTMLMediaElement) {
|
||||
_this.LockElement.play().catch(err => {
|
||||
console.error("LockElement failed:", err);
|
||||
});
|
||||
} else {
|
||||
console.warn("LockElement not a media element or already assigned.");
|
||||
}
|
||||
}
|
||||
};
|
||||
WakeLock.AddSourceToVideo = function (element, type, dataURI) {
|
||||
var source = document.createElement('source');
|
||||
source.src = dataURI;
|
||||
source.type = 'video/' + type;
|
||||
element.appendChild(source);
|
||||
};
|
||||
WakeLock.VideoWebm = 'GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA=';
|
||||
WakeLock.VideoMp4 = 'AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw==';
|
||||
return WakeLock;
|
||||
}());
|
||||
@@ -1,26 +0,0 @@
|
||||
/*
|
||||
Logging is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var Logging = /** @class */ (function () {
|
||||
function Logging(parentElement, childElementType) {
|
||||
this.ParentElement = parentElement;
|
||||
this.ChildElementType = childElementType;
|
||||
}
|
||||
Logging.prototype.Log = function (message) {
|
||||
var dateTime = new Date();
|
||||
var lineText = "[" + (dateTime.getHours() > 9 ? dateTime.getHours() : "0" + dateTime.getHours()) + ":" +
|
||||
(dateTime.getMinutes() > 9 ? dateTime.getMinutes() : "0" + dateTime.getMinutes()) + ":" +
|
||||
(dateTime.getSeconds() > 9 ? dateTime.getSeconds() : "0" + dateTime.getSeconds()) +
|
||||
"] " + message;
|
||||
if (this.ParentElement && this.ChildElementType) {
|
||||
var line = document.createElement(this.ChildElementType);
|
||||
line.innerText = lineText;
|
||||
this.ParentElement.appendChild(line);
|
||||
}
|
||||
else {
|
||||
//console.log(lineText);
|
||||
}
|
||||
};
|
||||
return Logging;
|
||||
}());
|
||||
@@ -1,83 +0,0 @@
|
||||
/*
|
||||
WebSocket client is part of 3LAS (Low Latency Live Audio Streaming)
|
||||
https://github.com/JoJoBond/3LAS
|
||||
*/
|
||||
var WebSocketClient = /** @class */ (function () {
|
||||
function WebSocketClient(logger, uri, errorCallback, connectCallback, dataReadyCallback, disconnectCallback) {
|
||||
this.Logger = logger;
|
||||
this.Uri = uri;
|
||||
// Check callback argument
|
||||
if (typeof errorCallback !== 'function')
|
||||
throw new Error('WebSocketClient: ErrorCallback must be specified');
|
||||
if (typeof connectCallback !== 'function')
|
||||
throw new Error('WebSocketClient: ConnectCallback must be specified');
|
||||
if (typeof dataReadyCallback !== 'function')
|
||||
throw new Error('WebSocketClient: DataReadyCallback must be specified');
|
||||
if (typeof disconnectCallback !== 'function')
|
||||
throw new Error('WebSocketClient: DisconnectCallback must be specified');
|
||||
this.ErrorCallback = errorCallback;
|
||||
this.ConnectCallback = connectCallback;
|
||||
this.DataReadyCallback = dataReadyCallback;
|
||||
this.DisconnectCallback = disconnectCallback;
|
||||
// Client is not yet connected
|
||||
this.IsConnected = false;
|
||||
// Create socket, connect to URI
|
||||
if (typeof WebSocket !== "undefined")
|
||||
this.Socket = new WebSocket(this.Uri);
|
||||
else if (typeof webkitWebSocket !== "undefined")
|
||||
this.Socket = new webkitWebSocket(this.Uri);
|
||||
else if (typeof mozWebSocket !== "undefined")
|
||||
this.Socket = new mozWebSocket(this.Uri);
|
||||
else
|
||||
throw new Error('WebSocketClient: Browser does not support "WebSocket".');
|
||||
this.Socket.binaryType = 'arraybuffer';
|
||||
this.Socket.addEventListener("open", this.OnOpen.bind(this));
|
||||
this.Socket.addEventListener("error", this.OnError.bind(this));
|
||||
this.Socket.addEventListener("close", this.OnClose.bind(this));
|
||||
this.Socket.addEventListener("message", this.OnMessage.bind(this));
|
||||
}
|
||||
Object.defineProperty(WebSocketClient.prototype, "Connected", {
|
||||
get: function () {
|
||||
return this.IsConnected;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
WebSocketClient.prototype.Send = function (message) {
|
||||
if (!this.IsConnected)
|
||||
return;
|
||||
this.Socket.send(message);
|
||||
};
|
||||
// Handle errors
|
||||
WebSocketClient.prototype.OnError = function (_ev) {
|
||||
if (this.IsConnected == true)
|
||||
this.ErrorCallback("Socket fault.");
|
||||
else
|
||||
this.ErrorCallback("Could not connect to server.");
|
||||
};
|
||||
// Change connetion status once connected
|
||||
WebSocketClient.prototype.OnOpen = function (_ev) {
|
||||
if (this.Socket.readyState == 1) {
|
||||
this.IsConnected = true;
|
||||
this.ConnectCallback();
|
||||
}
|
||||
};
|
||||
// Change connetion status on disconnect
|
||||
WebSocketClient.prototype.OnClose = function (_ev) {
|
||||
if (this.IsConnected == true && (this.Socket.readyState == 2 || this.Socket.readyState == 3)) {
|
||||
this.IsConnected = false;
|
||||
this.DisconnectCallback();
|
||||
}
|
||||
};
|
||||
WebSocketClient.prototype.Close = function () {
|
||||
if (this.Socket) {
|
||||
this.Socket.close();
|
||||
}
|
||||
};
|
||||
// Handle incomping data
|
||||
WebSocketClient.prototype.OnMessage = function (ev) {
|
||||
// Trigger callback
|
||||
this.DataReadyCallback(ev.data);
|
||||
};
|
||||
return WebSocketClient;
|
||||
}());
|
||||
+28
-26
@@ -1,41 +1,43 @@
|
||||
function tuneUp() {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
getCurrentFreq();
|
||||
let addVal = 0;
|
||||
if (currentFreq < 0.52) addVal = 9 - (Math.round(currentFreq*1000) % 9);
|
||||
else if (currentFreq < 1.71) {
|
||||
var step = 9;
|
||||
if(localStorage.getItem('rdsMode') == 'true') step = 10
|
||||
addVal = step - (Math.round(currentFreq*1000) % step);
|
||||
} else if (currentFreq < 29.6) addVal = 5 - (Math.round(currentFreq*1000) % 5);
|
||||
else if (currentFreq >= 65.9 && currentFreq < 74) addVal = 30 - ((Math.round(currentFreq*1000) - 65900) % 30);
|
||||
else addVal = 100 - (Math.round(currentFreq*1000) % 100);
|
||||
socket.send("T" + (Math.round(currentFreq*1000) + addVal));
|
||||
}
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
getCurrentFreq();
|
||||
let addVal = 0;
|
||||
if (currentFreq < 0.52) addVal = 9 - (Math.round(currentFreq*1000) % 9);
|
||||
else if (currentFreq < 1.71) {
|
||||
var step = 9;
|
||||
if(localStorage.getItem('rdsMode') == 'true') step = 10
|
||||
addVal = step - (Math.round(currentFreq*1000) % step);
|
||||
} else if (currentFreq < 29.6) addVal = 5 - (Math.round(currentFreq*1000) % 5);
|
||||
else if (currentFreq >= 65.9 && currentFreq < 74) addVal = 30 - ((Math.round(currentFreq*1000) - 65900) % 30);
|
||||
else addVal = 100 - (Math.round(currentFreq*1000) % 100);
|
||||
socket.send("T" + (Math.round(currentFreq*1000) + addVal));
|
||||
}
|
||||
|
||||
function tuneDown() {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
getCurrentFreq();
|
||||
let subVal = 0;
|
||||
if (currentFreq < 0.52) subVal = (Math.round(currentFreq*1000) % 9 == 0) ? 9 : (Math.round(currentFreq*1000) % 9);
|
||||
else if (currentFreq < 1.71) {
|
||||
var step = 9;
|
||||
if(localStorage.getItem('rdsMode') == 'true') step = 10
|
||||
subVal = (Math.round(currentFreq*1000) % step == 0) ? step : (Math.round(currentFreq*1000) % step);
|
||||
} else if (currentFreq < 29.6) subVal = (Math.round(currentFreq*1000) % 5 == 0) ? 5 : (Math.round(currentFreq*1000) % 5);
|
||||
else if (currentFreq > 65.9 && currentFreq <= 74) subVal = ((Math.round(currentFreq*1000) - 65900) % 30 == 0) ? 30 : ((Math.round(currentFreq*1000) - 65900) % 30);
|
||||
else subVal = (Math.round(currentFreq*1000) % 100 == 0) ? 100 : (Math.round(currentFreq*1000) % 100);
|
||||
socket.send("T" + (Math.round(currentFreq*1000) - subVal));
|
||||
}
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
getCurrentFreq();
|
||||
let subVal = 0;
|
||||
if (currentFreq < 0.52) subVal = (Math.round(currentFreq*1000) % 9 == 0) ? 9 : (Math.round(currentFreq*1000) % 9);
|
||||
else if (currentFreq < 1.71) {
|
||||
var step = 9;
|
||||
if(localStorage.getItem('rdsMode') == 'true') step = 10
|
||||
subVal = (Math.round(currentFreq*1000) % step == 0) ? step : (Math.round(currentFreq*1000) % step);
|
||||
} else if (currentFreq < 29.6) subVal = (Math.round(currentFreq*1000) % 5 == 0) ? 5 : (Math.round(currentFreq*1000) % 5);
|
||||
else if (currentFreq > 65.9 && currentFreq <= 74) subVal = ((Math.round(currentFreq*1000) - 65900) % 30 == 0) ? 30 : ((Math.round(currentFreq*1000) - 65900) % 30);
|
||||
else subVal = (Math.round(currentFreq*1000) % 100 == 0) ? 100 : (Math.round(currentFreq*1000) % 100);
|
||||
socket.send("T" + (Math.round(currentFreq*1000) - subVal));
|
||||
}
|
||||
|
||||
function tuneTo(freq) {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
previousFreq = getCurrentFreq();
|
||||
socket.send("T" + ((parseFloat(freq)) * 1000).toFixed(0));
|
||||
}
|
||||
|
||||
function resetRDS() {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
socket.send("T0");
|
||||
}
|
||||
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
class WebSocketAudioPlayer {
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.ws = null;
|
||||
this.audio = null;
|
||||
this.mediaSource = null;
|
||||
this.sourceBuffer = null;
|
||||
this.queue = [];
|
||||
this.started = false;
|
||||
this._volume = 1;
|
||||
}
|
||||
|
||||
supported() {
|
||||
return MediaSource.isTypeSupported("audio/mpeg")
|
||||
}
|
||||
|
||||
_syncToLive() {
|
||||
if (!this.audio || !this.sourceBuffer) return;
|
||||
const buffered = this.sourceBuffer.buffered;
|
||||
if (buffered.length === 0) return;
|
||||
|
||||
const liveEdge = buffered.end(buffered.length - 1);
|
||||
const lag = liveEdge - this.audio.currentTime;
|
||||
|
||||
if (lag > 1) this.audio.currentTime = liveEdge - 0.25; // snap to near live edge
|
||||
}
|
||||
|
||||
Start() {
|
||||
this.audio = new Audio();
|
||||
this.mediaSource = new MediaSource();
|
||||
this.audio.src = URL.createObjectURL(this.mediaSource);
|
||||
|
||||
this.mediaSource.addEventListener('sourceopen', () => {
|
||||
this.sourceBuffer = this.mediaSource.addSourceBuffer('audio/mpeg');
|
||||
this.sourceBuffer.addEventListener('updateend', () => this._appendNext());
|
||||
this.audio.addEventListener('waiting', () => this._syncToLive());
|
||||
this.audio.addEventListener('stalled', () => this._syncToLive());
|
||||
|
||||
this.ws = new WebSocket(this.url);
|
||||
this.ws.binaryType = 'arraybuffer';
|
||||
this.ws.onmessage = (event) => {
|
||||
this.queue.push(event.data);
|
||||
this._appendNext();
|
||||
if (!this.started && this.queue.length === 0) { this.audio.play(); this.started = true; }
|
||||
};
|
||||
this.ws.onclose = () => {
|
||||
if (this.mediaSource.readyState === 'open') this.mediaSource.endOfStream();
|
||||
};
|
||||
});
|
||||
|
||||
this.audio.addEventListener('canplay', () => {
|
||||
if (!this.started) { this.audio.play(); this.started = true; }
|
||||
});
|
||||
}
|
||||
|
||||
Stop() { // capital to match 3las
|
||||
this.ws?.close();
|
||||
this.audio?.pause();
|
||||
this.queue = [];
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
get Volume() {
|
||||
return this._volume;
|
||||
}
|
||||
set Volume(v) {
|
||||
const actual = Math.max(0, Math.min(1, v))
|
||||
if (this.audio) this.audio.volume = actual;
|
||||
this._volume = actual;
|
||||
}
|
||||
|
||||
_appendNext() {
|
||||
if (this.sourceBuffer.updating || this.queue.length === 0) return;
|
||||
this.sourceBuffer.appendBuffer(this.queue.shift());
|
||||
this._syncToLive();
|
||||
}
|
||||
}
|
||||
|
||||
let Stream = null;
|
||||
let shouldReconnect = true;
|
||||
let firefox = false;
|
||||
|
||||
function Init(_ev) {
|
||||
$(".playbutton").off('click').on('click', OnPlayButtonClick);
|
||||
$("#volumeSlider").off("input").on("input", updateVolume);
|
||||
}
|
||||
|
||||
function createStream() {
|
||||
try {
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const url = `${wsProtocol}//${location.hostname}/audio`;
|
||||
|
||||
if (MediaSource.isTypeSupported("audio/mpeg")) {
|
||||
firefox = false;
|
||||
Stream = new WebSocketAudioPlayer(url);
|
||||
} else {
|
||||
firefox = true;
|
||||
alert("Your browser does not support MP3 over MSE, meaning we have to use 3LAS which is terrible and gives terrible audio quality. If you want better sound, switch to anything chromium based")
|
||||
Stream = new _3LAS(url, null);
|
||||
}
|
||||
Stream.Volume = $('#volumeSlider').val();
|
||||
} catch (error) {
|
||||
console.error("Initialization Error: ", error);
|
||||
}
|
||||
}
|
||||
|
||||
function destroyStream() {
|
||||
if (Stream) {
|
||||
Stream.Stop();
|
||||
Stream = null;
|
||||
}
|
||||
}
|
||||
|
||||
function OnPlayButtonClick(_ev) {
|
||||
const $playbutton = $('.playbutton');
|
||||
const isAppleiOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
|
||||
|
||||
if (Stream) {
|
||||
console.log("Stopping stream...");
|
||||
shouldReconnect = false;
|
||||
destroyStream();
|
||||
$playbutton.find('.fa-solid')?.toggleClass('fa-stop fa-play');
|
||||
if (isAppleiOS && 'audioSession' in navigator) navigator.audioSession.type = "none";
|
||||
} else {
|
||||
console.log("Starting stream...");
|
||||
shouldReconnect = true;
|
||||
createStream();
|
||||
Stream.Start();
|
||||
$playbutton.find('.fa-solid')?.toggleClass('fa-play fa-stop');
|
||||
if (isAppleiOS && 'audioSession' in navigator) navigator.audioSession.type = "playback";
|
||||
}
|
||||
|
||||
$playbutton.addClass('bg-gray').prop('disabled', true);
|
||||
setTimeout(() => $playbutton.removeClass('bg-gray').prop('disabled', false), 2000);
|
||||
}
|
||||
|
||||
function updateVolume() {
|
||||
const newVolume = $(this).val();
|
||||
if(!Stream) {
|
||||
console.warn("Stream is not initialized.");
|
||||
return;
|
||||
}
|
||||
|
||||
Stream.Volume = newVolume;
|
||||
}
|
||||
|
||||
$(document).ready(Init);
|
||||
window.addEventListener('load', Init, false);
|
||||
@@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
let Stream;
|
||||
let shouldReconnect = true;
|
||||
let audioStreamRestartInterval;
|
||||
|
||||
function Init() {
|
||||
$('.playbutton').off('click').on('click', OnPlayButtonClick);
|
||||
$('#volumeSlider').off('input').on('input', updateVolume);
|
||||
}
|
||||
|
||||
function createStream() {
|
||||
try {
|
||||
Stream = new AudioWsMp3Player();
|
||||
Stream.Volume = $('#volumeSlider').val();
|
||||
} catch (e) {
|
||||
console.error('Audio init error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
function destroyStream() {
|
||||
if (Stream) {
|
||||
Stream.Reset();
|
||||
Stream = null;
|
||||
}
|
||||
if (audioStreamRestartInterval) {
|
||||
clearInterval(audioStreamRestartInterval);
|
||||
audioStreamRestartInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
function OnPlayButtonClick() {
|
||||
const $btn = $('.playbutton');
|
||||
const isAppleiOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
|
||||
|
||||
if (Stream) {
|
||||
shouldReconnect = false;
|
||||
destroyStream();
|
||||
$btn.find('.fa-solid').toggleClass('fa-stop fa-play');
|
||||
if (isAppleiOS && 'audioSession' in navigator) {
|
||||
navigator.audioSession.type = 'none';
|
||||
}
|
||||
} else {
|
||||
shouldReconnect = true;
|
||||
createStream();
|
||||
Stream.Start();
|
||||
$btn.find('.fa-solid').toggleClass('fa-play fa-stop');
|
||||
if (isAppleiOS && 'audioSession' in navigator) {
|
||||
navigator.audioSession.type = 'playback';
|
||||
}
|
||||
if (audioStreamRestartInterval) clearInterval(audioStreamRestartInterval);
|
||||
audioStreamRestartInterval = setInterval(() => {
|
||||
if (typeof requiresAudioStreamRestart !== 'undefined' && requiresAudioStreamRestart && Stream) {
|
||||
requiresAudioStreamRestart = false;
|
||||
Stream.Reset();
|
||||
Stream.Start();
|
||||
console.log('Audio stream restarted after radio data loss.');
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
$btn.addClass('bg-gray').prop('disabled', true);
|
||||
setTimeout(() => $btn.removeClass('bg-gray').prop('disabled', false), 3000);
|
||||
}
|
||||
|
||||
function updateVolume() {
|
||||
if (Stream) {
|
||||
Stream.Volume = $(this).val();
|
||||
}
|
||||
}
|
||||
|
||||
$(document).ready(Init);
|
||||
@@ -0,0 +1,405 @@
|
||||
/*
|
||||
* Parts of this file are derived from 3LAS (Low Latency Live Audio Streaming)
|
||||
* by JoJoBond — https://github.com/JoJoBond/3LAS
|
||||
* Licensed under GPL-2.0 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
|
||||
*
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
class AudioWsMp3Player {
|
||||
constructor() {
|
||||
this._audioCtx = null;
|
||||
this._gainNode = null;
|
||||
this._ws = null;
|
||||
this._dataBuffer = new Uint8Array(0);
|
||||
this._frames = [];
|
||||
this._frameStartIdx = -1;
|
||||
this._frameEndIdx = -1;
|
||||
this._frameSamples = 0;
|
||||
this._frameSampleRate = 0;
|
||||
this._timeBudget = 0;
|
||||
this._nextPlayTime = 0;
|
||||
this._volume = 1.0;
|
||||
this._watchdogTimer = null;
|
||||
this._shouldReconnect = false;
|
||||
this._decoding = false;
|
||||
this._lastDecodeTime = 0;
|
||||
}
|
||||
|
||||
get Volume() {
|
||||
return this._volume;
|
||||
}
|
||||
|
||||
set Volume(value) {
|
||||
this._volume = Number(value);
|
||||
if (this._gainNode && this._audioCtx) {
|
||||
const clamped = Math.max(1e-20, Math.min(1.0, this._volume));
|
||||
this._gainNode.gain.cancelScheduledValues(this._audioCtx.currentTime);
|
||||
this._gainNode.gain.exponentialRampToValueAtTime(clamped, this._audioCtx.currentTime + 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
Start() {
|
||||
this._audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
this._gainNode = this._audioCtx.createGain();
|
||||
this._gainNode.gain.value = Math.max(1e-20, Math.min(1.0, this._volume));
|
||||
this._gainNode.connect(this._audioCtx.destination);
|
||||
this._nextPlayTime = 0;
|
||||
this._dataBuffer = new Uint8Array(0);
|
||||
this._frames = [];
|
||||
this._frameStartIdx = -1;
|
||||
this._frameEndIdx = -1;
|
||||
this._timeBudget = 0;
|
||||
this._shouldReconnect = true;
|
||||
this._lastDecodeTime = performance.now();
|
||||
this._mobileUnmute();
|
||||
this._connect();
|
||||
}
|
||||
|
||||
Reset() {
|
||||
this._shouldReconnect = false;
|
||||
this._stopWatchdog();
|
||||
if (this._ws) {
|
||||
const ws = this._ws;
|
||||
this._ws = null;
|
||||
ws.onopen = null;
|
||||
ws.onmessage = null;
|
||||
ws.onclose = null;
|
||||
ws.onerror = null;
|
||||
ws.close();
|
||||
}
|
||||
if (this._audioCtx) {
|
||||
this._audioCtx.close();
|
||||
this._audioCtx = null;
|
||||
}
|
||||
this._gainNode = null;
|
||||
this._dataBuffer = new Uint8Array(0);
|
||||
this._frames = [];
|
||||
this._nextPlayTime = 0;
|
||||
this._timeBudget = 0;
|
||||
this._decoding = false;
|
||||
}
|
||||
|
||||
// Mobile workaround - play silent stereo buffer to unblock AudioContext.
|
||||
_mobileUnmute() {
|
||||
if (!this._audioCtx) return;
|
||||
const gain = this._audioCtx.createGain();
|
||||
gain.gain.value = 1.0;
|
||||
gain.connect(this._audioCtx.destination);
|
||||
const silentBuf = this._audioCtx.createBuffer(2, this._audioCtx.sampleRate, this._audioCtx.sampleRate);
|
||||
const src = this._audioCtx.createBufferSource();
|
||||
src.onended = () => { src.disconnect(); gain.disconnect(); };
|
||||
src.buffer = silentBuf;
|
||||
src.connect(gain);
|
||||
src.start();
|
||||
}
|
||||
|
||||
// Open the websocket for audio and set up handlers.
|
||||
_connect() {
|
||||
if (!this._shouldReconnect) return;
|
||||
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
this._ws = new WebSocket(`${protocol}//${location.host}${location.pathname}audio`);
|
||||
this._ws.binaryType = 'arraybuffer';
|
||||
|
||||
this._ws.onopen = () => {
|
||||
this._lastDecodeTime = performance.now();
|
||||
this._startWatchdog();
|
||||
if (this._audioCtx && this._audioCtx.state === 'suspended') {
|
||||
this._audioCtx.resume();
|
||||
}
|
||||
this._mobileUnmute();
|
||||
};
|
||||
|
||||
this._ws.onmessage = (event) => {
|
||||
const chunk = new Uint8Array(event.data);
|
||||
const merged = new Uint8Array(this._dataBuffer.length + chunk.length);
|
||||
merged.set(this._dataBuffer);
|
||||
merged.set(chunk, this._dataBuffer.length);
|
||||
this._dataBuffer = merged;
|
||||
this._extractAndSchedule();
|
||||
};
|
||||
|
||||
this._ws.onclose = () => {
|
||||
this._stopWatchdog();
|
||||
this._ws = null;
|
||||
if (this._shouldReconnect) {
|
||||
this._dataBuffer = new Uint8Array(0);
|
||||
this._frames = [];
|
||||
this._frameStartIdx = -1;
|
||||
this._frameEndIdx = -1;
|
||||
this._nextPlayTime = 0;
|
||||
this._decoding = false;
|
||||
setTimeout(() => this._connect(), 1000);
|
||||
}
|
||||
};
|
||||
|
||||
this._ws.onerror = () => {
|
||||
if (this._ws) this._ws.close();
|
||||
};
|
||||
}
|
||||
|
||||
// Check every 3 seconds if the connection has died, and if so schedule a re-connect.
|
||||
_startWatchdog() {
|
||||
this._stopWatchdog();
|
||||
this._watchdogTimer = setInterval(() => {
|
||||
if (!this._shouldReconnect) { this._stopWatchdog(); return; }
|
||||
if (performance.now() - this._lastDecodeTime > 2000) {
|
||||
this._stopWatchdog();
|
||||
if (this._ws) {
|
||||
const ws = this._ws;
|
||||
this._ws = null;
|
||||
ws.onopen = null;
|
||||
ws.onmessage = null;
|
||||
ws.onclose = null;
|
||||
ws.onerror = null;
|
||||
ws.close();
|
||||
}
|
||||
this._dataBuffer = new Uint8Array(0);
|
||||
this._frames = [];
|
||||
this._frameStartIdx = -1;
|
||||
this._frameEndIdx = -1;
|
||||
this._nextPlayTime = 0;
|
||||
this._decoding = false;
|
||||
setTimeout(() => this._connect(), 1000);
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Clear any pre-existing re-connect check
|
||||
_stopWatchdog() {
|
||||
if (this._watchdogTimer !== null) {
|
||||
clearInterval(this._watchdogTimer);
|
||||
this._watchdogTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Find an MP3 frame start and its length in the data buffer, by searching byte-by-byte for the MPEG sync word if the start byte is not known.
|
||||
_findFrame() {
|
||||
if (this._frameStartIdx < 0) {
|
||||
for (let i = 0; i + 1 < this._dataBuffer.length; i++) {
|
||||
if (this._dataBuffer[i] === 0xFF && (this._dataBuffer[i + 1] & 0xE0) === 0xE0) {
|
||||
this._frameStartIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this._frameStartIdx >= 0 && this._frameEndIdx < 0) {
|
||||
if (this._frameStartIdx + 3 < this._dataBuffer.length) {
|
||||
const b1 = this._dataBuffer[this._frameStartIdx + 1];
|
||||
const b2 = this._dataBuffer[this._frameStartIdx + 2];
|
||||
const ver = (b1 & 0x18) >>> 3;
|
||||
const lyr = (b1 & 0x06) >>> 1;
|
||||
const pad = (b2 & 0x02) >>> 1;
|
||||
const brx = (b2 & 0xF0) >>> 4;
|
||||
const srx = (b2 & 0x0C) >>> 2;
|
||||
const bitrate = AudioWsMp3Player.MPEG_bitrates[ver][lyr][brx] * 1000;
|
||||
const samprate = AudioWsMp3Player.MPEG_srates[ver][srx];
|
||||
const samples = AudioWsMp3Player.MPEG_frame_samples[ver][lyr];
|
||||
const slotSize = AudioWsMp3Player.MPEG_slot_size[lyr];
|
||||
if (bitrate > 0 && samprate > 0) {
|
||||
this._frameSamples = samples;
|
||||
this._frameSampleRate = samprate;
|
||||
this._frameEndIdx = this._frameStartIdx + Math.floor((samples / 8.0 * bitrate) / samprate + (pad ? slotSize : 0));
|
||||
} else {
|
||||
this._frameStartIdx = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a complete frame boundary has been found and enough bytes have arrived in the buffer to extract.
|
||||
_canExtractFrame() {
|
||||
return this._frameStartIdx >= 0 && this._frameEndIdx >= 0 && this._frameEndIdx <= this._dataBuffer.length;
|
||||
}
|
||||
|
||||
// Extract the MPEG audio frame from the buffer, and reset the data buffer indexes ready for the next frame.
|
||||
_extractFrame() {
|
||||
const frameData = new Uint8Array(this._dataBuffer.buffer.slice(this._frameStartIdx, this._frameEndIdx));
|
||||
this._dataBuffer = this._frameEndIdx + 1 < this._dataBuffer.length
|
||||
? new Uint8Array(this._dataBuffer.buffer.slice(this._frameEndIdx))
|
||||
: new Uint8Array(0);
|
||||
this._frameStartIdx = 0;
|
||||
this._frameEndIdx = -1;
|
||||
return { data: frameData, sampleCount: this._frameSamples, sampleRate: this._frameSampleRate };
|
||||
}
|
||||
|
||||
// Central processing loop to find all frames within the incoming buffer data each time a websocket message is received.
|
||||
_extractAndSchedule() {
|
||||
if (!this._audioCtx) return;
|
||||
this._findFrame();
|
||||
while (this._canExtractFrame()) {
|
||||
this._frames.push(this._extractFrame());
|
||||
this._findFrame();
|
||||
}
|
||||
if (this._decoding || this._frames.length < 3) return;
|
||||
|
||||
const first = this._frames[0];
|
||||
const last = this._frames[this._frames.length - 1];
|
||||
const firstGranule = first.sampleCount / first.sampleRate / 2.0;
|
||||
const lastGranule = last.sampleCount / last.sampleRate / 2.0;
|
||||
let expectedTime = firstGranule + lastGranule;
|
||||
let bufLen = first.data.length + last.data.length;
|
||||
for (let i = 1; i < this._frames.length - 1; i++) {
|
||||
expectedTime += this._frames[i].sampleCount / this._frames[i].sampleRate;
|
||||
bufLen += this._frames[i].data.length;
|
||||
}
|
||||
if (this._nextPlayTime !== 0 && this._nextPlayTime + expectedTime <= this._audioCtx.currentTime) return;
|
||||
|
||||
const decodeBuffer = new Uint8Array(bufLen);
|
||||
let offset = 0;
|
||||
for (const frame of this._frames) {
|
||||
decodeBuffer.set(frame.data, offset);
|
||||
offset += frame.data.length;
|
||||
}
|
||||
|
||||
this._frames.splice(0, this._frames.length - 1);
|
||||
|
||||
this._decoding = true;
|
||||
this._audioCtx.decodeAudioData(
|
||||
decodeBuffer.buffer,
|
||||
(decoded) => {
|
||||
this._decoding = false;
|
||||
this._onDecoded(decoded, expectedTime, firstGranule, lastGranule);
|
||||
this._extractAndSchedule();
|
||||
},
|
||||
() => {
|
||||
this._decoding = false;
|
||||
this._extractAndSchedule();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Each time we call to decode, trim artefacts created by decoder cold start to stop audio glitches.
|
||||
_onDecoded(decoded, expectedTime, firstGranule, lastGranule) {
|
||||
if (!this._audioCtx || !this._gainNode) return;
|
||||
this._lastDecodeTime = performance.now();
|
||||
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
const isApple = /iphone|ipod/.test(ua) ||
|
||||
/ipad/.test(ua) ||
|
||||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) ||
|
||||
/mac os x/.test(ua);
|
||||
|
||||
const delta = 0.001;
|
||||
let sampleCount, sampleOffset = 0;
|
||||
|
||||
if (expectedTime > decoded.duration) {
|
||||
sampleCount = decoded.length;
|
||||
sampleOffset = 0;
|
||||
this._timeBudget += expectedTime - decoded.duration;
|
||||
} else if (expectedTime < decoded.duration) {
|
||||
sampleCount = Math.ceil(expectedTime * decoded.sampleRate);
|
||||
const budgetSamples = this._timeBudget * decoded.sampleRate;
|
||||
if (budgetSamples > 1.0) {
|
||||
const extra = Math.min(budgetSamples, decoded.length - sampleCount);
|
||||
sampleCount += extra;
|
||||
this._timeBudget -= extra / decoded.sampleRate;
|
||||
}
|
||||
const diff = decoded.duration - expectedTime;
|
||||
if ((diff - firstGranule - lastGranule) >= -delta) {
|
||||
sampleOffset = Math.floor((decoded.length - sampleCount) / 2);
|
||||
}
|
||||
if (Math.abs(firstGranule - lastGranule) <= delta) {
|
||||
sampleOffset = isApple
|
||||
? Math.floor((decoded.length - sampleCount) / 2)
|
||||
: decoded.length - sampleCount;
|
||||
} else if (Math.abs(diff - firstGranule) <= delta) {
|
||||
sampleOffset = decoded.length - sampleCount;
|
||||
} else if (Math.abs(diff - lastGranule) <= delta) {
|
||||
sampleOffset = 0;
|
||||
} else {
|
||||
sampleOffset = Math.floor((decoded.length - sampleCount) / 2);
|
||||
}
|
||||
} else {
|
||||
sampleCount = decoded.length;
|
||||
sampleOffset = 0;
|
||||
}
|
||||
|
||||
const buf = this._audioCtx.createBuffer(decoded.numberOfChannels, sampleCount, decoded.sampleRate);
|
||||
for (let ch = 0; ch < decoded.numberOfChannels; ch++) {
|
||||
buf.getChannelData(ch).set(decoded.getChannelData(ch).subarray(sampleOffset, sampleOffset + sampleCount));
|
||||
}
|
||||
this._scheduleBuffer(buf);
|
||||
}
|
||||
|
||||
// Schedule a decoded buffer for playback at the correct AudioContext time. Reset if it's falled behind (on reconnect etc.).
|
||||
_scheduleBuffer(buffer) {
|
||||
if (!this._audioCtx || !this._gainNode) return;
|
||||
if (this._audioCtx.state === 'suspended') {
|
||||
this._audioCtx.resume();
|
||||
}
|
||||
const INITIAL_OFFSET = 0.33;
|
||||
|
||||
if (this._nextPlayTime === 0) {
|
||||
this._nextPlayTime = this._audioCtx.currentTime + INITIAL_OFFSET;
|
||||
}
|
||||
|
||||
const duration = buffer.duration;
|
||||
if (this._nextPlayTime + duration <= this._audioCtx.currentTime) {
|
||||
this._nextPlayTime = this._audioCtx.currentTime + INITIAL_OFFSET;
|
||||
}
|
||||
|
||||
let skipDuration = 0;
|
||||
if (this._audioCtx.currentTime >= this._nextPlayTime) {
|
||||
skipDuration = this._audioCtx.currentTime - this._nextPlayTime + 0.05;
|
||||
}
|
||||
|
||||
if (skipDuration < duration) {
|
||||
const src = this._audioCtx.createBufferSource();
|
||||
src.loop = false;
|
||||
src.buffer = buffer;
|
||||
src.onended = () => src.disconnect();
|
||||
src.connect(this._gainNode);
|
||||
src.start(this._nextPlayTime + skipDuration, skipDuration);
|
||||
}
|
||||
this._nextPlayTime += duration;
|
||||
}
|
||||
}
|
||||
|
||||
// MPEG bitrate table [version][layer][index] in kbps
|
||||
AudioWsMp3Player.MPEG_bitrates = [
|
||||
[ // MPEG 2.5
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],
|
||||
[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],
|
||||
[0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0]
|
||||
],
|
||||
[ // Reserved
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
|
||||
],
|
||||
[ // MPEG 2
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],
|
||||
[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],
|
||||
[0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0]
|
||||
],
|
||||
[ // MPEG 1
|
||||
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
|
||||
[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0],
|
||||
[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,0],
|
||||
[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0]
|
||||
]
|
||||
];
|
||||
|
||||
// Sample rates [version][index] in Hz
|
||||
AudioWsMp3Player.MPEG_srates = [
|
||||
[11025,12000,8000,0],
|
||||
[0,0,0,0],
|
||||
[22050,24000,16000,0],
|
||||
[44100,48000,32000,0]
|
||||
];
|
||||
|
||||
// Samples per frame [version][layer]
|
||||
AudioWsMp3Player.MPEG_frame_samples = [
|
||||
[0,576,1152,384],
|
||||
[0,0,0,0],
|
||||
[0,576,1152,384],
|
||||
[0,1152,1152,384]
|
||||
];
|
||||
|
||||
// Slot size [layer]: Reserved, Layer3, Layer2, Layer1
|
||||
AudioWsMp3Player.MPEG_slot_size = [0,1,1,4];
|
||||
+3
-3
@@ -24,7 +24,7 @@ $(document).ready(function() {
|
||||
}
|
||||
|
||||
// Load nickname from localStorage on page load
|
||||
let savedNickname = localStorage.getItem('nickname') || `User ${generateRandomString(5)}`;
|
||||
let savedNickname = localStorage.getItem('nickname') || `User ${generateRandomString(6)}`;
|
||||
chatNicknameInput.val(savedNickname);
|
||||
chatIdentityNickname.text(savedNickname);
|
||||
|
||||
@@ -60,7 +60,7 @@ $(document).ready(function() {
|
||||
|
||||
$('.chat-send-message-btn').click(sendMessage);
|
||||
chatNicknameSave.click(function() {
|
||||
const currentNickname = chatNicknameInput.val().trim() || `Anonymous User ${generateRandomString(5)}`;
|
||||
const currentNickname = chatNicknameInput.val().trim() || `Anonymous User ${generateRandomString(6)}`;
|
||||
localStorage.setItem('nickname', currentNickname);
|
||||
savedNickname = currentNickname;
|
||||
chatIdentityNickname.text(savedNickname);
|
||||
@@ -87,7 +87,7 @@ $(document).ready(function() {
|
||||
});
|
||||
|
||||
function sendMessage() {
|
||||
const nickname = savedNickname || `Anonymous User ${generateRandomString(5)}`;
|
||||
const nickname = savedNickname || `Anonymous User ${generateRandomString(6)}`;
|
||||
const message = chatSendInput.val().trim();
|
||||
|
||||
if (message) {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
let configData = {}; // Store the original data structure globally
|
||||
|
||||
$(document).ready(function() {
|
||||
fetchConfig();
|
||||
});
|
||||
|
||||
function submitConfig() {
|
||||
updateConfigData(configData);
|
||||
if ($("#password-adminPass").val().length < 1) {
|
||||
alert('You need to fill in the admin password before continuing further.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: './saveData',
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify(configData),
|
||||
success: function (message) {
|
||||
sendToast('success', 'Data saved!', message, true, true);
|
||||
setTimeout(function () {
|
||||
location.reload(true);
|
||||
}, 1500);
|
||||
},
|
||||
error: function (error) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function fetchConfig() {
|
||||
$.getJSON("./getData")
|
||||
.done(data => {
|
||||
configData = data;
|
||||
populateFields(configData);
|
||||
initVolumeSlider();
|
||||
initConnectionToggle();
|
||||
})
|
||||
.fail(error => console.error("Error fetching data:", error.message));
|
||||
}
|
||||
|
||||
function populateFields(data, prefix = "") {
|
||||
$.each(data, (key, value) => {
|
||||
if (value === null) value = ""; // Convert null to an empty string
|
||||
|
||||
let id = `${prefix}${prefix ? "-" : ""}${key}`;
|
||||
const $element = $(`#${id}`);
|
||||
|
||||
if (key === "plugins" && $element.is('select[multiple]')) {
|
||||
if (Array.isArray(value)) {
|
||||
$element.find('option').each(function() {
|
||||
const $option = $(this);
|
||||
const dataName = $option.data('name');
|
||||
if (value.includes(dataName)) $option.prop('selected', true);
|
||||
else $option.prop('selected', false);
|
||||
});
|
||||
|
||||
$element.trigger('change');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === "object" && value !== null) {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, index) => {
|
||||
const arrayId = `${id}-${index + 1}`;
|
||||
const $arrayElement = $(`#${arrayId}`);
|
||||
|
||||
if ($arrayElement.length) $arrayElement.val(item);
|
||||
else console.log(`Element with id ${arrayId} not found`);
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
populateFields(value, id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$element.length) {
|
||||
console.log(`Element with id ${id} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === "boolean") {
|
||||
$element.prop("checked", value);
|
||||
} else if ($element.is('input[type="text"]') && $element.closest('.dropdown').length) {
|
||||
const $dropdownOption = $element.siblings('ul.options').find(`li[data-value="${value}"]`);
|
||||
$element.val($dropdownOption.length ? $dropdownOption.text() : value);
|
||||
$element.attr('data-value', value);
|
||||
} else $element.val(value);
|
||||
});
|
||||
}
|
||||
|
||||
function updateConfigData(data, prefix = "") {
|
||||
$.each(data, (key, value) => {
|
||||
const id = `${prefix}${prefix ? "-" : ""}${key}`;
|
||||
const $element = $(`#${id}`);
|
||||
|
||||
if (key === "presets") {
|
||||
data[key] = [];
|
||||
let index = 1;
|
||||
while (true) {
|
||||
const $presetElement = $(`#${prefix}${prefix ? "-" : ""}${key}-${index}`);
|
||||
if ($presetElement.length) {
|
||||
data[key].push($presetElement.val() || null); // Allow null if necessary
|
||||
index++;
|
||||
} else break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "plugins") {
|
||||
data[key] = [];
|
||||
const $selectedOptions = $element.find('option:selected');
|
||||
$selectedOptions.each(function() {
|
||||
const dataName = $(this).attr('data-name');
|
||||
if (dataName) data[key].push(dataName);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === "object" && value !== null && !Array.isArray(value)) return updateConfigData(value, id);
|
||||
|
||||
if ($element.length) {
|
||||
const newValue = $element.attr("data-value") ?? $element.val() ?? null;
|
||||
data[key] = typeof value === "boolean" ? $element.is(":checked") : newValue;
|
||||
}
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+122
-238
@@ -1,3 +1,6 @@
|
||||
const isMobileDevice = /android|iphone|ipod|ipad/i.test(navigator.userAgent) ||
|
||||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
|
||||
|
||||
var parsedData, signalChart, previousFreq;
|
||||
var data = [];
|
||||
var signalData = [];
|
||||
@@ -6,7 +9,6 @@ let lastReconnectAttempt = 0;
|
||||
let messageCounter = 0; // Count for WebSocket data length returning 0
|
||||
let messageData = 800; // Initial value anything above 0
|
||||
let messageLength = 800; // Retain value of messageData until value is updated
|
||||
let pingTimeLimit = false; // WebSocket becomes unresponsive with high ping
|
||||
|
||||
const europe_programmes = [
|
||||
"No PTY", "News", "Current Affairs", "Info",
|
||||
@@ -110,7 +112,7 @@ $(document).ready(function () {
|
||||
}
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (socket.readyState === WebSocket.OPEN) tuneTo(textInput.val());
|
||||
tuneTo(textInput.val());
|
||||
textInput.val('');
|
||||
}
|
||||
});
|
||||
@@ -126,10 +128,8 @@ $(document).ready(function () {
|
||||
e.preventDefault();
|
||||
const now = Date.now();
|
||||
|
||||
if (now - lastExecutionTime < throttleDelay) {
|
||||
// Ignore this event as it's within the throttle delay
|
||||
return;
|
||||
}
|
||||
// Ignore this event as it's within the throttle delay
|
||||
if (now - lastExecutionTime < throttleDelay) return;
|
||||
|
||||
lastExecutionTime = now; // Update the last execution time
|
||||
|
||||
@@ -150,8 +150,6 @@ $(document).ready(function () {
|
||||
return false;
|
||||
});
|
||||
|
||||
setInterval(getServerTime, 10000);
|
||||
getServerTime();
|
||||
setInterval(sendPingRequest, 5000);
|
||||
sendPingRequest();
|
||||
|
||||
@@ -259,98 +257,11 @@ $(document).ready(function () {
|
||||
initTooltips();
|
||||
});
|
||||
|
||||
function getServerTime() {
|
||||
$.ajax({
|
||||
url: "./server_time",
|
||||
dataType: "json",
|
||||
success: function(data) {
|
||||
const serverTimeUtc = data.serverTime;
|
||||
|
||||
const options = {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false
|
||||
};
|
||||
|
||||
const serverOptions = {
|
||||
...options,
|
||||
timeZone: 'Etc/UTC'
|
||||
};
|
||||
|
||||
const formattedServerTime = new Date(serverTimeUtc).toLocaleString(navigator.language ? navigator.language : 'en-US', serverOptions);
|
||||
|
||||
$("#server-time").text(formattedServerTime);
|
||||
},
|
||||
error: function(jqXHR, textStatus, errorThrown) {
|
||||
console.error("Error fetching server time:", errorThrown);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sendPingRequest() {
|
||||
const timeoutDuration = 5000;
|
||||
const startTime = new Date().getTime();
|
||||
|
||||
const fetchWithTimeout = (url, options, timeout = timeoutDuration) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timerTimeout = setTimeout(() => {
|
||||
reject(new Error('Request timed out'));
|
||||
}, timeout);
|
||||
|
||||
fetch(url, options)
|
||||
.then(response => {
|
||||
clearTimeout(timerTimeout);
|
||||
resolve(response);
|
||||
})
|
||||
.catch(error => {
|
||||
clearTimeout(timerTimeout);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
fetchWithTimeout('./ping', { cache: 'no-store' }, timeoutDuration)
|
||||
.then(response => {
|
||||
const endTime = new Date().getTime();
|
||||
const pingTime = endTime - startTime;
|
||||
$('#current-ping').text(`Ping: ${pingTime}ms`);
|
||||
pingTimeLimit = false;
|
||||
})
|
||||
.catch(error => {
|
||||
console.warn('Ping request failed');
|
||||
$('#current-ping').text(`Ping: unknown`);
|
||||
if (!pingTimeLimit) { // Force reconnection as WebSocket could be unresponsive even though it's reported as OPEN
|
||||
if (messageLength === 0) window.socket.close(1000, 'Normal closure');
|
||||
if (connectionLost) sendToast('warning', 'Connection lost', 'Attempting to reconnect...', false, false);
|
||||
console.log("Reconnecting due to high ping...");
|
||||
pingTimeLimit = true;
|
||||
}
|
||||
});
|
||||
|
||||
function handleMessage(message) {
|
||||
messageData = JSON.parse(message.data.length);
|
||||
socket.removeEventListener('message', handleMessage);
|
||||
}
|
||||
socket.addEventListener('message', handleMessage);
|
||||
messageLength = messageData;
|
||||
messageData = 0;
|
||||
|
||||
// Force reconnection if no WebSocket data after several queries
|
||||
if (messageLength === 0) {
|
||||
messageCounter++;
|
||||
if (messageCounter === 5) {
|
||||
messageCounter = 0;
|
||||
window.socket.close(1000, 'Normal closure');
|
||||
if (connectionLost) sendToast('warning', 'Connection lost', 'Attempting to reconnect...', false, false);
|
||||
console.log("Reconnecting due to no data received...");
|
||||
}
|
||||
} else messageCounter = 0;
|
||||
|
||||
// Automatic reconnection on WebSocket close with cooldown
|
||||
const now = Date.now();
|
||||
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(`PING ${now}`);
|
||||
|
||||
if (
|
||||
(socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) &&
|
||||
(now - lastReconnectAttempt > TIMEOUT_DURATION)
|
||||
@@ -362,9 +273,7 @@ function sendPingRequest() {
|
||||
socket.onopen = () => {
|
||||
sendToast('info', 'Connected', 'Reconnected successfully!', false, false);
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
handleWebSocketMessage(event);
|
||||
};
|
||||
socket.onmessage = handleWebSocketMessage;
|
||||
socket.onerror = (error) => {
|
||||
console.error("Main/UI WebSocket error during reconnection:", error);
|
||||
};
|
||||
@@ -372,29 +281,33 @@ function sendPingRequest() {
|
||||
console.warn("Main/UI WebSocket closed during reconnection. Will attempt to reconnect...");
|
||||
};
|
||||
}
|
||||
if (connectionLost) {
|
||||
if (dataTimeout == dataTimeoutPrevious) {
|
||||
connectionLost = true;
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
window.socket.close(1000, 'Normal closure'); // Force reconnection to unfreeze browser UI
|
||||
}, 8000); // Timeout must be higher than TIMEOUT_DURATION
|
||||
connectionLost = false;
|
||||
requiresAudioStreamRestart = true;
|
||||
console.log("Radio data restored.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleWebSocketMessage(event) {
|
||||
if (event.data == 'KICK') {
|
||||
console.log('Kick initiated.')
|
||||
console.log('Kick initiated.');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/403';
|
||||
window.location.href = `/403?reason=${encodeURIComponent("You have been kicked")}`;
|
||||
}, 100);
|
||||
return;
|
||||
} else if (event.data.startsWith("!")) {
|
||||
sendToast('info', 'Info from server', event.data.slice(1), false, false)
|
||||
}
|
||||
if (event.data.startsWith("!")) {
|
||||
sendToast('info', 'Info from server', event.data.slice(1), false, false);
|
||||
return;
|
||||
}
|
||||
if (event.data == "a0") {
|
||||
console.log('Too many users');
|
||||
setTimeout(() => {
|
||||
window.location.href = `/403?reason=${encodeURIComponent("Too many users")}`;
|
||||
}, 100);
|
||||
return;
|
||||
}
|
||||
if (event.data.startsWith("PING ")) {
|
||||
const sentTime = Number(event.data.substring(5));
|
||||
const ping = Date.now() - sentTime;
|
||||
|
||||
$('#current-ping').text(`Ping: ${ping}ms`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -403,12 +316,22 @@ function handleWebSocketMessage(event) {
|
||||
resetDataTimeout();
|
||||
updatePanels(parsedData);
|
||||
|
||||
const sum = signalData.reduce((acc, strNum) => acc + parseFloat(strNum), 0);
|
||||
const averageSignal = sum / signalData.length;
|
||||
data.push(averageSignal);
|
||||
}
|
||||
data.push(signalData.reduce((acc, strNum) => acc + parseFloat(strNum), 0) / signalData.length);
|
||||
|
||||
// Attach the message handler
|
||||
if(parsedData.timestamp) {
|
||||
const options = {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
timeZone: 'Etc/UTC'
|
||||
};
|
||||
const formattedServerTime = new Date(parsedData.timestamp * 1000).toLocaleString(navigator.language ? navigator.language : 'en-US', options);
|
||||
$("#server-time").text(formattedServerTime);
|
||||
}
|
||||
}
|
||||
socket.onmessage = handleWebSocketMessage;
|
||||
|
||||
const signalBuffer = [];
|
||||
@@ -453,12 +376,12 @@ function initCanvas() {
|
||||
grid: { display: false, borderWidth: 0, borderColor: "transparent" },
|
||||
realtime: {
|
||||
duration: 30000,
|
||||
refresh: 75,
|
||||
refresh: 100,
|
||||
delay: 150,
|
||||
frameRate: 30, // default is 30
|
||||
frameRate: 24,
|
||||
onRefresh: (chart) => {
|
||||
if (!chart?.data?.datasets || parsedData?.sig === undefined) return;
|
||||
if ((isAndroid || isIOS || isIPadOS) && (document.hidden || !document.hasFocus())) return;
|
||||
if (isMobileDevice && (document.hidden || !document.hasFocus())) return;
|
||||
|
||||
const sig = parsedData.sig;
|
||||
signalBuffer.push(sig);
|
||||
@@ -572,18 +495,16 @@ function initCanvas() {
|
||||
}
|
||||
|
||||
function setRefreshRate(rate) {
|
||||
const rt = signalChart.options.scales.x.realtime;
|
||||
rt.refresh = rate;
|
||||
signalChart.options.scales.x.realtime.refresh = rate;
|
||||
signalChart.update('none');
|
||||
console.log(`Graph refresh rate set to ${rate} ms`);
|
||||
}
|
||||
|
||||
window.addEventListener("focus", () => {
|
||||
if (isAndroid || isIOS || isIPadOS) setRefreshRate(75);
|
||||
if(isMobileDevice) setRefreshRate(100);
|
||||
});
|
||||
|
||||
window.addEventListener("blur", () => {
|
||||
if (isAndroid || isIOS || isIPadOS) setRefreshRate(3000);
|
||||
if(isMobileDevice) setRefreshRate(3000);
|
||||
});
|
||||
|
||||
let reconnectTimer = null;
|
||||
@@ -603,34 +524,10 @@ const resetDataTimeout = () => {
|
||||
}, TIMEOUT_DURATION);
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
if (event.data === 'KICK') {
|
||||
console.log('Kick initiated.');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/403';
|
||||
}, 100);
|
||||
return;
|
||||
}
|
||||
|
||||
parsedData = JSON.parse(event.data);
|
||||
|
||||
resetDataTimeout();
|
||||
updatePanels(parsedData);
|
||||
|
||||
const sum = signalData.reduce((acc, strNum) => acc + parseFloat(strNum), 0);
|
||||
const averageSignal = sum / signalData.length;
|
||||
data.push(averageSignal);
|
||||
};
|
||||
|
||||
function compareNumbers(a, b) {
|
||||
// Really?
|
||||
return a - b;
|
||||
}
|
||||
|
||||
function escapeHTML(unsafeText) {
|
||||
let div = document.createElement('div');
|
||||
div.innerText = unsafeText;
|
||||
return div.innerHTML.replace(' ', ' ');
|
||||
function escapeHTML(text) {
|
||||
const div = document.createElement("div");
|
||||
div.innerText = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function processString(string, errors) {
|
||||
@@ -650,90 +547,84 @@ function processString(string, errors) {
|
||||
}
|
||||
|
||||
function checkKey(e) {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
e = e || window.event;
|
||||
|
||||
if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) {
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) return;
|
||||
|
||||
if ($('#password:focus').length > 0
|
||||
|| $('#chat-send-message:focus').length > 0
|
||||
|| $('#volumeSlider:focus').length > 0
|
||||
|| $('#chat-nickname:focus').length > 0
|
||||
|| $('.option:focus').length > 0) {
|
||||
return;
|
||||
}
|
||||
|| $('.option:focus').length > 0) return;
|
||||
|
||||
getCurrentFreq();
|
||||
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
switch (e.keyCode) {
|
||||
case 66: // Back to previous frequency
|
||||
tuneTo(previousFreq);
|
||||
break;
|
||||
case 82: // RDS Reset (R key)
|
||||
tuneTo(Number(currentFreq));
|
||||
break;
|
||||
case 83: // Screenshot (S key)
|
||||
break;
|
||||
case 38:
|
||||
socket.send("T" + (Math.round(currentFreq*1000) + ((currentFreq > 30) ? 10 : 1)));
|
||||
break;
|
||||
case 40:
|
||||
socket.send("T" + (Math.round(currentFreq*1000) - ((currentFreq > 30) ? 10 : 1)));
|
||||
break;
|
||||
case 37:
|
||||
tuneDown();
|
||||
break;
|
||||
case 39:
|
||||
tuneUp();
|
||||
break;
|
||||
case 46:
|
||||
let $dropdown = $(".data-ant");
|
||||
let $input = $dropdown.find("input");
|
||||
let $options = $dropdown.find("ul.options .option");
|
||||
switch (e.keyCode) {
|
||||
case 66: // Back to previous frequency
|
||||
tuneTo(previousFreq);
|
||||
break;
|
||||
case 82: // RDS Reset (R key)
|
||||
tuneTo(Number(currentFreq));
|
||||
break;
|
||||
case 83: // Screenshot (S key)
|
||||
break;
|
||||
case 38:
|
||||
socket.send("T" + (Math.round(currentFreq*1000) + ((currentFreq > 30) ? 10 : 1)));
|
||||
break;
|
||||
case 40:
|
||||
socket.send("T" + (Math.round(currentFreq*1000) - ((currentFreq > 30) ? 10 : 1)));
|
||||
break;
|
||||
case 37:
|
||||
tuneDown();
|
||||
break;
|
||||
case 39:
|
||||
tuneUp();
|
||||
break;
|
||||
case 46:
|
||||
let $dropdown = $(".data-ant");
|
||||
let $input = $dropdown.find("input");
|
||||
let $options = $dropdown.find("ul.options .option");
|
||||
|
||||
if ($options.length === 0) return; // No antennas available
|
||||
if ($options.length === 0) return; // No antennas available
|
||||
|
||||
// Find the currently selected antenna
|
||||
let currentText = $input.val().trim();
|
||||
let currentIndex = $options.index($options.filter(function () {
|
||||
return $(this).text().trim() === currentText;
|
||||
}));
|
||||
// Find the currently selected antenna
|
||||
let currentText = $input.val().trim();
|
||||
let currentIndex = $options.index($options.filter(function () {
|
||||
return $(this).text().trim() === currentText;
|
||||
}));
|
||||
|
||||
console.log(currentIndex, currentText);
|
||||
console.log(currentIndex, currentText);
|
||||
|
||||
// Cycle to the next option
|
||||
let nextIndex = (currentIndex + 1) % $options.length;
|
||||
let $nextOption = $options.eq(nextIndex);
|
||||
// Cycle to the next option
|
||||
let nextIndex = (currentIndex + 1) % $options.length;
|
||||
let $nextOption = $options.eq(nextIndex);
|
||||
|
||||
// Update UI
|
||||
$input.attr("placeholder", $nextOption.text());
|
||||
$input.data("value", $nextOption.data("value"));
|
||||
// Update UI
|
||||
$input.attr("placeholder", $nextOption.text());
|
||||
$input.data("value", $nextOption.data("value"));
|
||||
|
||||
let socketMessage = "Z" + $nextOption.data("value");
|
||||
socket.send(socketMessage);
|
||||
break;
|
||||
case 112: // F1
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset1')));
|
||||
break;
|
||||
case 113: // F2
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset2')));
|
||||
break;
|
||||
case 114: // F3
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset3')));
|
||||
break;
|
||||
case 115: // F4
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset4')));
|
||||
break;
|
||||
default:
|
||||
// Handle default case if needed
|
||||
let socketMessage = "Z" + $nextOption.data("value");
|
||||
socket.send(socketMessage);
|
||||
break;
|
||||
case 112: // F1
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset1')));
|
||||
break;
|
||||
case 113: // F2
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset2')));
|
||||
break;
|
||||
case 114: // F3
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset3')));
|
||||
break;
|
||||
case 115: // F4
|
||||
e.preventDefault();
|
||||
tuneTo(Number(localStorage.getItem('preset4')));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -769,11 +660,8 @@ async function copyTx() {
|
||||
}
|
||||
|
||||
async function copyRt() {
|
||||
var rt0 = $('#data-rt0 span').text();
|
||||
var rt1 = $('#data-rt1 span').text();
|
||||
|
||||
try {
|
||||
await copyToClipboard("[0] RT: " + rt0 + "\n[1] RT: " + rt1);
|
||||
await copyToClipboard("[0] RT: " + $('#data-rt0 span').text() + "\n[1] RT: " + $('#data-rt1 span').text());
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
@@ -809,13 +697,10 @@ function copyToClipboard(textToCopy) {
|
||||
|
||||
function findOnMaps() {
|
||||
var frequency = parseFloat($('#data-frequency').text());
|
||||
var pi = $('#data-pi').text();
|
||||
var latitude = localStorage.getItem('qthLongitude');
|
||||
var longitude = localStorage.getItem('qthLatitude');
|
||||
|
||||
frequency > 74 ? frequency = frequency.toFixed(1) : null;
|
||||
|
||||
window.open(`https://maps.fmdx.org/#qth=${longitude},${latitude}&freq=${frequency}&findPi=${pi}`, "_blank");
|
||||
window.open(`https://maps.fmdx.org/#qth=${localStorage.getItem('qthLatitude')},${localStorage.getItem('qthLongitude')}&freq=${frequency}&findPi=${$('#data-pi').text()}`, "_blank");
|
||||
}
|
||||
|
||||
function updateSignalUnits(parsedData, averageSignal) {
|
||||
@@ -832,7 +717,7 @@ function updateSignalUnits(parsedData, averageSignal) {
|
||||
signalValue = currentSignal - 11.25;
|
||||
highestSignal = highestSignal - 11.25;
|
||||
signalText.text('dBµV');
|
||||
break;
|
||||
break;
|
||||
case 'dbm':
|
||||
signalValue = currentSignal - 120;
|
||||
highestSignal = highestSignal - 120;
|
||||
@@ -1024,7 +909,7 @@ function updatePanels(parsedData) {
|
||||
const sum = signalData.reduce((acc, strNum) => acc + parseFloat(strNum), 0);
|
||||
const averageSignal = sum / signalData.length;
|
||||
|
||||
const sortedAf = parsedData.af.sort(compareNumbers);
|
||||
const sortedAf = parsedData.af.sort(function (a, b){return a-b});
|
||||
const scaledArray = sortedAf.map(element => element / 1000);
|
||||
|
||||
const listContainer = $('#af-list');
|
||||
@@ -1048,8 +933,7 @@ function updatePanels(parsedData) {
|
||||
// Add the event listener only once
|
||||
if (!isEventListenerAdded) {
|
||||
ul.on('click', 'a', function () {
|
||||
const frequency = parseFloat($(this).text());
|
||||
tuneTo(frequency);
|
||||
tuneTo(parseFloat($(this).text()));
|
||||
});
|
||||
isEventListenerAdded = true;
|
||||
}
|
||||
|
||||
+51
-128
@@ -3,6 +3,7 @@
|
||||
* FM-DX Webserver WHEP Audio Plugin
|
||||
* ************************************************
|
||||
* Created by techkrzysiek
|
||||
* Stolen by me (thanks man)
|
||||
* ************************************************
|
||||
*/
|
||||
|
||||
@@ -16,15 +17,15 @@ window.addEventListener('load', (() => {
|
||||
const SELECT_LOADING_VALUE = 'webrtc:loading';
|
||||
const MANAGED_PLAYBUTTON_CLASS = 'fmdx-webrtc-playbutton';
|
||||
const LEGACY_PROXY_BUTTON_ID = 'fmdx-webrtc-legacy-playbutton';
|
||||
const SELECT_TOOLTIP_HTML = '<strong>WebRTC</strong> - very low latency audio<br>If audio starts stuttering,<br>switch to <strong>3LAS (TCP)</strong>.';
|
||||
const SELECT_TOOLTIP_HTML = '<strong>WebRTC</strong> - very low latency audio.';
|
||||
const DEBUG_WEBRTC_AUDIO = false;
|
||||
const RECONNECT_DELAY = 3000;
|
||||
const FIRST_DISCONNECT_RECONNECT_DELAY = 500;
|
||||
const MAX_RECONNECT_ATTEMPTS = 50;
|
||||
const UI_ATTACH_INITIAL_DELAY = 250;
|
||||
const UI_ATTACH_INITIAL_DELAY = 100;
|
||||
const ONDEMAND_STARTUP_404_GRACE_ATTEMPTS = 5;
|
||||
const ONDEMAND_STARTUP_RECONNECT_MS_FAST = 500;
|
||||
const ONDEMAND_STARTUP_RECONNECT_MS_SLOW = 1000;
|
||||
const ONDEMAND_STARTUP_RECONNECT_MS_SLOW = 750;
|
||||
const ONDEMAND_STARTUP_FAST_RETRY_COUNT = 2;
|
||||
|
||||
const webrtcCss = `
|
||||
@@ -152,7 +153,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
}`;
|
||||
|
||||
let disable3las = false;
|
||||
let disablews = false;
|
||||
let disableMobileSelect = true;
|
||||
|
||||
let peerConnection = null;
|
||||
@@ -192,9 +193,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function logWebRTCDebug(message, details = undefined) {
|
||||
if (!DEBUG_WEBRTC_AUDIO) {
|
||||
return;
|
||||
}
|
||||
if (!DEBUG_WEBRTC_AUDIO) return;
|
||||
|
||||
const elapsedMs = currentDebugSessionStartedAt
|
||||
? Math.round(performance.now() - currentDebugSessionStartedAt)
|
||||
@@ -231,7 +230,7 @@ window.addEventListener('load', (() => {
|
||||
return;
|
||||
}
|
||||
const flags = await response.json();
|
||||
disable3las = Boolean(flags.disable3las);
|
||||
disablews = Boolean(flags.disablews);
|
||||
} catch (error) {
|
||||
console.warn('[WHEP] Failed to fetch flags:', error);
|
||||
}
|
||||
@@ -243,9 +242,9 @@ window.addEventListener('load', (() => {
|
||||
|
||||
function getCookieDomainAttribute() {
|
||||
const hostname = String(window.location.hostname || '').toLowerCase();
|
||||
if (hostname === 'fmdx.pro' || hostname.endsWith('.fmdx.pro')) {
|
||||
return '; domain=.fmdx.pro';
|
||||
}
|
||||
// if (hostname === 'fmtuner.org' || hostname.endsWith('.fmtuner.org')) {
|
||||
// return '; domain=.fmtuner.org';
|
||||
// }
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -283,9 +282,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function persistSelectedSource(value) {
|
||||
if (value) {
|
||||
setPersistentCookie(LAST_SOURCE_COOKIE_NAME, value);
|
||||
}
|
||||
if (value) setPersistentCookie(LAST_SOURCE_COOKIE_NAME, value);
|
||||
}
|
||||
|
||||
function parseWhepProfiles(rawConfig) {
|
||||
@@ -328,7 +325,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function getLegacyOptionLabel() {
|
||||
return '3LAS (TCP)';
|
||||
return 'Websocket';
|
||||
}
|
||||
|
||||
function getSelectedBitrateLabel() {
|
||||
@@ -336,9 +333,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function parseSelectedBitrate(value) {
|
||||
if (typeof value !== 'string' || !value.startsWith('webrtc:')) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string' || !value.startsWith('webrtc:')) return null;
|
||||
|
||||
const bitrate = Number(value.slice('webrtc:'.length));
|
||||
return Number.isFinite(bitrate) && bitrate > 0 ? bitrate : null;
|
||||
@@ -365,9 +360,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function ensureAudioElement() {
|
||||
if (audioElement) {
|
||||
return audioElement;
|
||||
}
|
||||
if (audioElement) return audioElement;
|
||||
|
||||
audioElement = new Audio();
|
||||
audioElement.autoplay = true;
|
||||
@@ -392,9 +385,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function maybeMarkAudioPlaybackStarted(source) {
|
||||
if (!audioElement || hasAudioPlaybackStarted) {
|
||||
return;
|
||||
}
|
||||
if (!audioElement || hasAudioPlaybackStarted) return;
|
||||
|
||||
const currentTime = Number(audioElement.currentTime || 0);
|
||||
if (currentTime <= 0.05) {
|
||||
@@ -440,9 +431,7 @@ window.addEventListener('load', (() => {
|
||||
isConnecting,
|
||||
audio: getAudioElementDebugState()
|
||||
});
|
||||
if (!peerConnection || !isPeerConnectionReady || !hasAudioPlaybackStarted || isActive) {
|
||||
return;
|
||||
}
|
||||
if (!peerConnection || !isPeerConnectionReady || !hasAudioPlaybackStarted || isActive) return;
|
||||
|
||||
isConnecting = false;
|
||||
isActive = true;
|
||||
@@ -481,22 +470,14 @@ window.addEventListener('load', (() => {
|
||||
const $managedButton = getManagedPlayButtons()
|
||||
.filter((_, element) => $(element).closest('#mobileTray').length > 0)
|
||||
.first();
|
||||
if ($managedButton.length > 0) {
|
||||
return $managedButton;
|
||||
}
|
||||
|
||||
if ($managedButton.length > 0) return $managedButton;
|
||||
return $('#mobileTray .playbutton').first();
|
||||
}
|
||||
|
||||
function ensureManagedDesktopPlayButton() {
|
||||
let $desktopButton = getDesktopPlayButton();
|
||||
if ($desktopButton.length === 0) {
|
||||
return $desktopButton;
|
||||
}
|
||||
|
||||
if ($desktopButton.hasClass(MANAGED_PLAYBUTTON_CLASS)) {
|
||||
return $desktopButton;
|
||||
}
|
||||
if ($desktopButton.length === 0) return $desktopButton;
|
||||
if ($desktopButton.hasClass(MANAGED_PLAYBUTTON_CLASS)) return $desktopButton;
|
||||
|
||||
const $proxyButton = $desktopButton;
|
||||
const $managedButton = $proxyButton.clone(false);
|
||||
@@ -515,13 +496,8 @@ window.addEventListener('load', (() => {
|
||||
|
||||
function ensureManagedMobilePlayButton() {
|
||||
let $mobileButton = getMobilePlayButton();
|
||||
if ($mobileButton.length === 0) {
|
||||
return $mobileButton;
|
||||
}
|
||||
|
||||
if ($mobileButton.hasClass(MANAGED_PLAYBUTTON_CLASS)) {
|
||||
return $mobileButton;
|
||||
}
|
||||
if ($mobileButton.length === 0) return $mobileButton;
|
||||
if ($mobileButton.hasClass(MANAGED_PLAYBUTTON_CLASS)) return $mobileButton;
|
||||
|
||||
$mobileButton.removeClass('playbutton').addClass(MANAGED_PLAYBUTTON_CLASS);
|
||||
$mobileButton.off();
|
||||
@@ -535,9 +511,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
const $icon = $proxyButton.find('i');
|
||||
if ($icon.hasClass('fa-stop')) {
|
||||
return 'connected';
|
||||
}
|
||||
if ($icon.hasClass('fa-stop')) return 'connected';
|
||||
return 'disconnected';
|
||||
}
|
||||
|
||||
@@ -545,9 +519,7 @@ window.addEventListener('load', (() => {
|
||||
const legacyState = getLegacyProxyState();
|
||||
const $buttons = getManagedPlayButtons();
|
||||
$buttons.removeClass('rtc-active rtc-connecting');
|
||||
if (legacyState === 'connected') {
|
||||
$buttons.addClass('rtc-active');
|
||||
}
|
||||
if (legacyState === 'connected') $buttons.addClass('rtc-active');
|
||||
updatePlayButtonIcon(legacyState === 'connected' ? 'connected' : 'disconnected');
|
||||
updatePlayButtonTitle(legacyState === 'connected' ? 'connected' : 'disconnected');
|
||||
}
|
||||
@@ -601,9 +573,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function normalizeStoredSourceValue(value) {
|
||||
if (value === LEGACY_SOURCE_VALUE) {
|
||||
return value;
|
||||
}
|
||||
if (value === LEGACY_SOURCE_VALUE) return value;
|
||||
|
||||
const storedBitrate = parseSelectedBitrate(value);
|
||||
if (storedBitrate) {
|
||||
@@ -616,14 +586,10 @@ window.addEventListener('load', (() => {
|
||||
|
||||
function getDefaultSourceValue() {
|
||||
const storedValue = normalizeStoredSourceValue(getStoredSource());
|
||||
if (storedValue === LEGACY_SOURCE_VALUE && !disable3las) {
|
||||
return LEGACY_SOURCE_VALUE;
|
||||
}
|
||||
if (storedValue === LEGACY_SOURCE_VALUE && !disablews) return LEGACY_SOURCE_VALUE;
|
||||
|
||||
const storedBitrate = parseSelectedBitrate(storedValue);
|
||||
if (profiles.length === 0) {
|
||||
return storedValue || SELECT_LOADING_VALUE;
|
||||
}
|
||||
if (profiles.length === 0) return storedValue || SELECT_LOADING_VALUE;
|
||||
|
||||
const matchingProfile = Number.isFinite(storedBitrate)
|
||||
? profiles.find((profile) => profile.bitrate === storedBitrate)
|
||||
@@ -636,21 +602,15 @@ window.addEventListener('load', (() => {
|
||||
const $selects = $(`.fmdx-webrtc-mode-select`);
|
||||
const buttonState = getActivePlaybackBackend() ? 'connected' : 'disconnected';
|
||||
|
||||
if (value === LEGACY_SOURCE_VALUE && !disable3las) {
|
||||
if (syncSelect) {
|
||||
$selects.val(LEGACY_SOURCE_VALUE);
|
||||
}
|
||||
if (persist) {
|
||||
persistSelectedSource(LEGACY_SOURCE_VALUE);
|
||||
}
|
||||
if (value === LEGACY_SOURCE_VALUE && !disablews) {
|
||||
if (syncSelect) $selects.val(LEGACY_SOURCE_VALUE);
|
||||
if (persist) persistSelectedSource(LEGACY_SOURCE_VALUE);
|
||||
updatePlayButtonTitle(buttonState);
|
||||
return LEGACY_SOURCE_VALUE;
|
||||
}
|
||||
|
||||
if (profiles.length === 0) {
|
||||
if (syncSelect) {
|
||||
$selects.val(SELECT_LOADING_VALUE);
|
||||
}
|
||||
if (syncSelect) $selects.val(SELECT_LOADING_VALUE);
|
||||
updatePlayButtonTitle(buttonState);
|
||||
return SELECT_LOADING_VALUE;
|
||||
}
|
||||
@@ -664,12 +624,8 @@ window.addEventListener('load', (() => {
|
||||
persistSelectedBitrate();
|
||||
|
||||
const appliedValue = `webrtc:${currentBitrate}`;
|
||||
if (syncSelect) {
|
||||
$selects.val(appliedValue);
|
||||
}
|
||||
if (persist) {
|
||||
persistSelectedSource(appliedValue);
|
||||
}
|
||||
if (syncSelect) $selects.val(appliedValue);
|
||||
if (persist) persistSelectedSource(appliedValue);
|
||||
|
||||
updatePlayButtonTitle(buttonState);
|
||||
return appliedValue;
|
||||
@@ -679,18 +635,14 @@ window.addEventListener('load', (() => {
|
||||
const $selects = $(`.fmdx-webrtc-mode-select`);
|
||||
for (let i = 0; i < $selects.length; i++) {
|
||||
const value = $selects[i].value;
|
||||
if (value && value !== SELECT_LOADING_VALUE) {
|
||||
return value;
|
||||
}
|
||||
if (value && value !== SELECT_LOADING_VALUE) return value;
|
||||
}
|
||||
return getDefaultSourceValue();
|
||||
}
|
||||
|
||||
function getSelectedSourceLabel() {
|
||||
const selectedValue = getSelectedSourceValue();
|
||||
if (selectedValue === LEGACY_SOURCE_VALUE) {
|
||||
return getLegacyOptionLabel();
|
||||
}
|
||||
if (selectedValue === LEGACY_SOURCE_VALUE) return getLegacyOptionLabel();
|
||||
|
||||
const selectedBitrate = parseSelectedBitrate(selectedValue) ?? currentBitrate;
|
||||
return selectedBitrate ? formatWebRtcOptionLabel(selectedBitrate) : 'WebRTC';
|
||||
@@ -701,12 +653,8 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function getActivePlaybackBackend() {
|
||||
if (isConnecting || isActive || shouldReconnect) {
|
||||
return 'webrtc';
|
||||
}
|
||||
if (isLegacyPlaybackActive()) {
|
||||
return LEGACY_SOURCE_VALUE;
|
||||
}
|
||||
if (isConnecting || isActive || shouldReconnect) return 'webrtc';
|
||||
if (isLegacyPlaybackActive()) return LEGACY_SOURCE_VALUE;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -745,7 +693,7 @@ window.addEventListener('load', (() => {
|
||||
});
|
||||
}
|
||||
|
||||
if (!disable3las) {
|
||||
if (!disablews) {
|
||||
options.push({
|
||||
value: LEGACY_SOURCE_VALUE,
|
||||
label: getLegacyOptionLabel()
|
||||
@@ -760,9 +708,7 @@ window.addEventListener('load', (() => {
|
||||
}
|
||||
|
||||
function attachSelectToButton($button, selectId) {
|
||||
if ($button.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if ($button.length === 0) return null;
|
||||
|
||||
const $host = $button.closest('.panel-10').length > 0
|
||||
? $button.closest('.panel-10')
|
||||
@@ -802,13 +748,9 @@ window.addEventListener('load', (() => {
|
||||
const $desktopButton = ensureManagedDesktopPlayButton();
|
||||
|
||||
let $mobileButton = $();
|
||||
if (!disableMobileSelect) {
|
||||
$mobileButton = ensureManagedMobilePlayButton();
|
||||
}
|
||||
if (!disableMobileSelect) $mobileButton = ensureManagedMobilePlayButton();
|
||||
|
||||
if ($desktopButton.length === 0 && $mobileButton.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if ($desktopButton.length === 0 && $mobileButton.length === 0) return false;
|
||||
|
||||
const optionsHtml = buildOptionsHtml();
|
||||
|
||||
@@ -819,9 +761,7 @@ window.addEventListener('load', (() => {
|
||||
|
||||
if (!disableMobileSelect) {
|
||||
const $mobileSelect = attachSelectToButton($mobileButton, SELECT_ID + '-mobile');
|
||||
if ($mobileSelect) {
|
||||
$mobileSelect.html(optionsHtml);
|
||||
}
|
||||
if ($mobileSelect) $mobileSelect.html(optionsHtml);
|
||||
}
|
||||
|
||||
applySelectedSourceValue(getDefaultSourceValue(), { persist: false, syncSelect: true });
|
||||
@@ -830,9 +770,7 @@ window.addEventListener('load', (() => {
|
||||
|
||||
function bindPlayButtons() {
|
||||
const $buttons = getManagedPlayButtons();
|
||||
if ($buttons.length === 0) {
|
||||
return false;
|
||||
}
|
||||
if ($buttons.length === 0) return false;
|
||||
|
||||
$buttons
|
||||
.off('click')
|
||||
@@ -849,13 +787,9 @@ window.addEventListener('load', (() => {
|
||||
bindPlayButtons();
|
||||
|
||||
const activeBackend = getActivePlaybackBackend();
|
||||
if (activeBackend === 'webrtc') {
|
||||
updateButtonState(isConnecting ? 'connecting' : 'connected');
|
||||
} else if (!activeBackend) {
|
||||
updateButtonState('disconnected');
|
||||
} else {
|
||||
syncManagedButtonWithLegacyState();
|
||||
}
|
||||
if (activeBackend === 'webrtc') updateButtonState(isConnecting ? 'connecting' : 'connected');
|
||||
else if (!activeBackend) updateButtonState('disconnected');
|
||||
else syncManagedButtonWithLegacyState();
|
||||
}
|
||||
|
||||
async function fetchAvailableBitrates({ preserveSelection = true } = {}) {
|
||||
@@ -954,21 +888,15 @@ window.addEventListener('load', (() => {
|
||||
if (audioElement) {
|
||||
audioElement.pause();
|
||||
audioElement.srcObject = null;
|
||||
if (audioElement.parentNode) {
|
||||
audioElement.parentNode.removeChild(audioElement);
|
||||
}
|
||||
if (audioElement.parentNode) audioElement.parentNode.removeChild(audioElement);
|
||||
audioElement = null;
|
||||
}
|
||||
|
||||
if (deleteSession) {
|
||||
await deleteWhepSession();
|
||||
}
|
||||
if (deleteSession) await deleteWhepSession();
|
||||
}
|
||||
|
||||
function scheduleReconnect({ countAttempt = true, delayMs = RECONNECT_DELAY } = {}) {
|
||||
if (!shouldReconnect) {
|
||||
return;
|
||||
}
|
||||
if (!shouldReconnect) return;
|
||||
|
||||
if (countAttempt && reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
||||
sendToast('error', 'WebRTC Audio', 'Reconnect limit reached', false, false);
|
||||
@@ -1014,11 +942,8 @@ window.addEventListener('load', (() => {
|
||||
isActive = false;
|
||||
await cleanupConnection();
|
||||
|
||||
if (wasRequested) {
|
||||
scheduleReconnect();
|
||||
} else {
|
||||
updateButtonState('disconnected');
|
||||
}
|
||||
if (wasRequested) scheduleReconnect();
|
||||
else updateButtonState('disconnected');
|
||||
}
|
||||
|
||||
async function startWebRTC({ refreshProfiles = false } = {}) {
|
||||
@@ -1102,9 +1027,7 @@ window.addEventListener('load', (() => {
|
||||
};
|
||||
|
||||
pc.onconnectionstatechange = () => {
|
||||
if (pc !== peerConnection) {
|
||||
return;
|
||||
}
|
||||
if (pc !== peerConnection) return;
|
||||
|
||||
logWebRTCDebug('pc.connectionstatechange', {
|
||||
connectionState: pc.connectionState,
|
||||
|
||||
+20
-23
@@ -25,12 +25,11 @@ const signalUnits = {
|
||||
};
|
||||
|
||||
$(document).ready(() => {
|
||||
|
||||
getInitialSettings();
|
||||
|
||||
|
||||
$('#login-form').submit(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
|
||||
$.ajax({
|
||||
type: 'POST',
|
||||
url: './login',
|
||||
@@ -45,11 +44,11 @@ $(document).ready(() => {
|
||||
if (xhr.status === 403) sendToast('error', 'Login failed!', xhr.responseJSON.message, false, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
$('.logout-link').click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
|
||||
$.ajax({
|
||||
type: 'GET', // Assuming the logout is a GET request, adjust accordingly
|
||||
url: './logout',
|
||||
@@ -60,9 +59,7 @@ $(document).ready(() => {
|
||||
}, 500);
|
||||
},
|
||||
error: function (xhr, status, error) {
|
||||
if (xhr.status === 403) {
|
||||
sendToast('error', 'Logout failed!', xhr.responseJSON.message, false, true);
|
||||
}
|
||||
if (xhr.status === 403) sendToast('error', 'Logout failed!', xhr.responseJSON.message, false, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -132,7 +129,7 @@ function getInitialSettings() {
|
||||
['qthLatitude', 'qthLongitude', 'defaultTheme', 'bgImage', 'rdsMode', 'rdsTimeout'].forEach(key => {
|
||||
if (data[key] !== undefined) localStorage.setItem(key, data[key]);
|
||||
});
|
||||
|
||||
|
||||
data.presets.forEach((preset, index) => localStorage.setItem(`preset${index + 1}`, preset));
|
||||
|
||||
loadInitialSettings();
|
||||
@@ -150,7 +147,7 @@ function loadInitialSettings() {
|
||||
const savedUnit = localStorage.getItem('signalUnit');
|
||||
|
||||
themeSelector.find('input').val(themeSelector.find('.option[data-value="' + defaultTheme + '"]').text());
|
||||
|
||||
|
||||
if(defaultTheme && themes[defaultTheme]) {
|
||||
setTheme(defaultTheme);
|
||||
}
|
||||
@@ -160,12 +157,12 @@ function loadInitialSettings() {
|
||||
setTheme(themeParameter);
|
||||
themeSelector.find('input').val(themeSelector.find('.option[data-value="' + themeParameter + '"]').text());
|
||||
}
|
||||
|
||||
|
||||
if (savedTheme && themes[savedTheme]) {
|
||||
setTheme(savedTheme);
|
||||
themeSelector.find('input').val(themeSelector.find('.option[data-value="' + savedTheme + '"]').text());
|
||||
}
|
||||
|
||||
|
||||
themeSelector.on('click', '.option', (event) => {
|
||||
const selectedTheme = $(event.target).data('value');
|
||||
setTheme(selectedTheme);
|
||||
@@ -173,15 +170,15 @@ function loadInitialSettings() {
|
||||
localStorage.setItem('theme', selectedTheme);
|
||||
setBg();
|
||||
});
|
||||
|
||||
|
||||
const signalSelector = $('#signal-selector');
|
||||
|
||||
|
||||
const signalParameter = getQueryParameter('signalUnits');
|
||||
if(signalParameter && !localStorage.getItem('signalUnit')) {
|
||||
signalSelector.find('input').val(signalSelector.find('.option[data-value="' + signalParameter + '"]').text());
|
||||
localStorage.setItem('signalUnit', signalParameter);
|
||||
} else signalSelector.find('input').val(signalSelector.find('.option[data-value="' + savedUnit + '"]').text());
|
||||
|
||||
|
||||
signalSelector.on('click', '.option', (event) => {
|
||||
const selectedSignalUnit = $(event.target).data('value');
|
||||
signalSelector.find('input').val($(event.target).text()); // Set the text of the clicked option to the input
|
||||
@@ -192,23 +189,23 @@ function loadInitialSettings() {
|
||||
if (extendedFreqRange === "true") {
|
||||
$("#extended-frequency-range").prop("checked", true);
|
||||
}
|
||||
|
||||
|
||||
$("#extended-frequency-range").change(function() {
|
||||
var isChecked = $(this).is(":checked");
|
||||
localStorage.setItem("extendedFreqRange", isChecked);
|
||||
});
|
||||
|
||||
|
||||
const psUnderscoreParameter = getQueryParameter('psUnderscores');
|
||||
if(psUnderscoreParameter) {
|
||||
$("#ps-underscores").prop("checked", JSON.parse(psUnderscoreParameter));
|
||||
}
|
||||
|
||||
|
||||
var psUnderscores = localStorage.getItem("psUnderscores");
|
||||
if (psUnderscores) {
|
||||
$("#ps-underscores").prop("checked", JSON.parse(psUnderscores));
|
||||
localStorage.setItem("psUnderscores", psUnderscores);
|
||||
}
|
||||
|
||||
|
||||
$("#ps-underscores").change(function() {
|
||||
var isChecked = $(this).is(":checked");
|
||||
localStorage.setItem("psUnderscores", isChecked);
|
||||
@@ -219,13 +216,13 @@ function loadInitialSettings() {
|
||||
$("#imperial-units").prop("checked", JSON.parse(imperialUnits));
|
||||
localStorage.setItem("imperialUnits", imperialUnits);
|
||||
}
|
||||
|
||||
|
||||
$("#imperial-units").change(function() {
|
||||
var isChecked = $(this).is(":checked");
|
||||
localStorage.setItem("imperialUnits", isChecked);
|
||||
});
|
||||
|
||||
|
||||
$('.version-string').text(currentVersion);
|
||||
|
||||
|
||||
setBg();
|
||||
}
|
||||
+2
-235
@@ -4,214 +4,9 @@ var tilesURL=' https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
var mapAttrib='© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>';
|
||||
|
||||
$(document).ready(function() {
|
||||
mapCreate();
|
||||
loadConsoleLogs();
|
||||
|
||||
showPanelFromHash();
|
||||
initNav();
|
||||
initBanlist();
|
||||
|
||||
checkTunnelServers();
|
||||
setInterval(checkTunnelServers, 10000);
|
||||
});
|
||||
|
||||
function mapCreate() {
|
||||
if (!(typeof map == "object")) {
|
||||
map = L.map('map', {
|
||||
center: [40, 0],
|
||||
zoom: 3,
|
||||
worldCopyJump: true
|
||||
});
|
||||
} else map.setZoom(3).panTo([40, 0]);
|
||||
|
||||
L.tileLayer(tilesURL, {
|
||||
attribution: mapAttrib,
|
||||
maxZoom: 19
|
||||
}).addTo(map);
|
||||
|
||||
// Check for initial lat/lon values
|
||||
const latVal = parseFloat($('#identification-lat').val());
|
||||
const lonVal = parseFloat($('#identification-lon').val());
|
||||
|
||||
if (!isNaN(latVal) && !isNaN(lonVal)) {
|
||||
const initialLatLng = L.latLng(latVal, lonVal);
|
||||
pin = L.marker(initialLatLng, { riseOnHover: true, draggable: true }).addTo(map);
|
||||
map.setView(initialLatLng, 8); // Optional: Zoom in closer to the pin
|
||||
|
||||
pin.on('dragend', function(ev) {
|
||||
$('#identification-lat').val(ev.target.getLatLng().lat.toFixed(6));
|
||||
$('#identification-lon').val(ev.target.getLatLng().lng.toFixed(6));
|
||||
});
|
||||
}
|
||||
|
||||
map.on('click', function(ev) {
|
||||
$('#identification-lat').val(ev.latlng.lat.toFixed(6));
|
||||
$('#identification-lon').val(ev.latlng.lng.toFixed(6));
|
||||
|
||||
if (typeof pin == "object") {
|
||||
pin.setLatLng(ev.latlng.wrap());
|
||||
} else {
|
||||
pin = L.marker(ev.latlng.wrap(), { riseOnHover: true, draggable: true }).addTo(map);
|
||||
pin.on('dragend', function(ev) {
|
||||
$('#identification-lat').val(ev.target.getLatLng().lat.toFixed(6));
|
||||
$('#identification-lon').val(ev.target.getLatLng().lng.toFixed(6));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
mapReload();
|
||||
}
|
||||
|
||||
function mapReload() {
|
||||
setTimeout(function () {
|
||||
map.invalidateSize();
|
||||
}, 200);
|
||||
}
|
||||
|
||||
function showPanelFromHash() {
|
||||
var panelId = window.location.hash.substring(1) || 'dashboard';
|
||||
|
||||
$('.tab-content').hide();
|
||||
$('#' + panelId).show();
|
||||
|
||||
$('.nav li').removeClass('active');
|
||||
$('.nav li[data-panel="' + panelId + '"]').addClass('active');
|
||||
}
|
||||
|
||||
function initNav() {
|
||||
$('.nav li').click(function() {
|
||||
$('.nav li').removeClass('active');
|
||||
$(this).addClass('active');
|
||||
var panelId = $(this).data('panel');
|
||||
window.location.hash = panelId;
|
||||
$('.tab-content').hide();
|
||||
$('#' + panelId).show();
|
||||
|
||||
panelId == 'identification' ? mapReload() : null;
|
||||
});
|
||||
|
||||
$('[role="tab"]').on('keydown', function(event) {
|
||||
if (event.key === 'Enter') {
|
||||
$(this).find('a').click();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initBanlist() {
|
||||
$('.banlist-add').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const ipAddress = $('#banlist-add-ip').val();
|
||||
const reason = $('#banlist-add-reason').val();
|
||||
|
||||
$.ajax({
|
||||
url: '/addToBanlist',
|
||||
method: 'GET',
|
||||
data: { ip: ipAddress, reason: reason },
|
||||
success: function(response) {
|
||||
// Refresh the page if the request was successful
|
||||
if (response.success) location.reload();
|
||||
else console.error('Failed to add to banlist');
|
||||
},
|
||||
error: function() {
|
||||
console.error('Error occurred during the request');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('.banlist-remove').on('click', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const ipAddress = $(this).closest('tr').find('td').first().text();
|
||||
|
||||
$.ajax({
|
||||
url: '/removeFromBanlist',
|
||||
method: 'GET',
|
||||
data: { ip: ipAddress },
|
||||
success: function(response) {
|
||||
if (response.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
console.error('Failed to remove from banlist');
|
||||
}
|
||||
},
|
||||
error: function() {
|
||||
console.error('Error occurred during the request');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function toggleNav() {
|
||||
const navOpen = $("#navigation").css('margin-left') === '0px';
|
||||
const isMobile = window.innerWidth <= 768;
|
||||
|
||||
if (navOpen) {
|
||||
if (isMobile) {
|
||||
// Do nothing to .admin-wrapper on mobile (since we're overlaying)
|
||||
$(".admin-wrapper").css({
|
||||
'margin-left': '32px',
|
||||
'width': '100%' // Reset content to full width on close
|
||||
});
|
||||
$("#navigation").css('margin-left', 'calc(64px - 100vw)');
|
||||
} else {
|
||||
// On desktop, adjust the content margin and width
|
||||
$(".admin-wrapper").css({
|
||||
'margin-left': '64px',
|
||||
'width': 'calc(100% - 64px)'
|
||||
});
|
||||
$("#navigation").css('margin-left', '-356px');
|
||||
}
|
||||
$(".sidenav-close").html('<i class="fa-solid fa-chevron-right"></i>');
|
||||
} else {
|
||||
$("#navigation").css('margin-left', '0');
|
||||
if (isMobile) {
|
||||
$(".admin-wrapper").css({
|
||||
'margin-left': '0', // Keep content in place when sidenav is open
|
||||
'width': '100%' // Keep content at full width
|
||||
});
|
||||
} else {
|
||||
// On desktop, push the content
|
||||
$(".admin-wrapper").css({
|
||||
'margin-left': '420px',
|
||||
'width': 'calc(100% - 420px)'
|
||||
});
|
||||
}
|
||||
$(".sidenav-close").html('<i class="fa-solid fa-chevron-left"></i>');
|
||||
}
|
||||
}
|
||||
|
||||
function initVolumeSlider() {
|
||||
const $volumeInput = $('#audio-startupVolume');
|
||||
const $percentageValue = $('#volume-percentage-value');
|
||||
|
||||
const updateDisplay = () => {
|
||||
$percentageValue.text(($volumeInput.val() * 100).toFixed(0) + '%');
|
||||
};
|
||||
|
||||
updateDisplay();
|
||||
$volumeInput.on('change', updateDisplay);
|
||||
}
|
||||
|
||||
function initConnectionToggle() {
|
||||
const connectionToggle = $('#xdrd-wirelessConnection');
|
||||
const tunerUSB = $('#tuner-usb');
|
||||
const tunerWireless = $('#tuner-wireless');
|
||||
|
||||
function toggleType() {
|
||||
if (connectionToggle.is(":checked")) {
|
||||
tunerUSB.hide();
|
||||
tunerWireless.show();
|
||||
} else {
|
||||
tunerWireless.hide();
|
||||
tunerUSB.show();
|
||||
}
|
||||
}
|
||||
|
||||
toggleType();
|
||||
connectionToggle.change(toggleType);
|
||||
}
|
||||
|
||||
function stripAnsi(str) {
|
||||
return str.replace(/\u001b\[\d+m/g, '');
|
||||
}
|
||||
@@ -222,11 +17,10 @@ async function loadConsoleLogs() {
|
||||
html = stripAnsi(html);
|
||||
|
||||
const logColors = {
|
||||
INFO: "lime",
|
||||
DEBUG: "cyan",
|
||||
CHAT: "cyan",
|
||||
ERROR: "red",
|
||||
INFO: "lime",
|
||||
WARN: "yellow",
|
||||
ERROR: "red"
|
||||
};
|
||||
|
||||
let firstBracketProcessed = false;
|
||||
@@ -247,30 +41,3 @@ async function loadConsoleLogs() {
|
||||
});
|
||||
$("#console-output").length ? $("#console-output").scrollTop($("#console-output")[0].scrollHeight) : null;
|
||||
}
|
||||
|
||||
function checkTunnelServers() {
|
||||
$.ajax({
|
||||
url: '/tunnelservers',
|
||||
method: 'GET',
|
||||
success: function(servers) {
|
||||
const $options = $('#tunnel-regionselect ul.options');
|
||||
const $input = $('#tunnel-region');
|
||||
const selectedValue = $input.val(); // currently selected value (label or value?)
|
||||
|
||||
servers.forEach(server => {
|
||||
const $li = $options.find(`li[data-value="${server.value}"]`);
|
||||
|
||||
if ($li.length) {
|
||||
$li.text(server.label);
|
||||
|
||||
// If this li is the currently selected one, update input text too
|
||||
// Note: input.val() holds the label, so match by label is safer
|
||||
if ($li.text() === selectedValue || server.value === selectedValue) $input.val(server.label);
|
||||
}
|
||||
});
|
||||
},
|
||||
error: function() {
|
||||
console.error('Failed to load server latency data');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+3
-4
@@ -43,11 +43,10 @@ function sendToast(type, title, message, persistent, important) {
|
||||
|
||||
function closeToast($toast) {
|
||||
$toast.removeClass('show');
|
||||
setTimeout(function () {
|
||||
$toast.remove();
|
||||
}, 300);
|
||||
setTimeout(() => $toast.remove(), 300);
|
||||
}
|
||||
|
||||
function capitalizeFirstLetter(string) {
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
// JS doesn't have a native capitilzation function? What the actual fuck in the toy language?
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
const versionDate = new Date('Apr 11, 2026 13:30:00');
|
||||
const versionDate = new Date('Jul 10, 2026 21:20:00');
|
||||
const currentVersion = `v1.4.0b [${versionDate.getDate()}/${versionDate.getMonth() + 1}/${versionDate.getFullYear()}]`;
|
||||
+2
-2
@@ -17,9 +17,9 @@ if (!window.socket || window.socket.readyState === WebSocket.CLOSED || window.so
|
||||
reject(error);
|
||||
});
|
||||
|
||||
socket.addEventListener('close', () => {
|
||||
socket.addEventListener('close', (event) => {
|
||||
setTimeout(() => {
|
||||
console.warn('WebSocket connection closed');
|
||||
console.warn(`WebSocket connection closed (${event.code} '${event.reason}' ${event.wasClean})`);
|
||||
}, 100);
|
||||
reject(new Error('WebSocket connection closed'));
|
||||
});
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
$(document).ready(function() {
|
||||
$('.btn-prev').toggle($('.step:visible').index() !== 0);
|
||||
$('.btn-next').click(() => navigateStep(true));
|
||||
$('.btn-prev').click(() => navigateStep(false));
|
||||
});
|
||||
|
||||
function updateProgressBar(currentStep) {
|
||||
var stepIndex = $('.step').index(currentStep) + 1;
|
||||
$('.btn-rounded-cube').removeClass('activated');
|
||||
$('.btn-rounded-cube:lt(' + stepIndex + ')').addClass('activated');
|
||||
}
|
||||
|
||||
function updateWizardContent() {
|
||||
var visibleStepIndex = $('.step:visible').index();
|
||||
|
||||
$('.btn-prev').toggle(visibleStepIndex !== 0);
|
||||
$('.btn-next').text(visibleStepIndex === 4 ? 'Save' : 'Next');
|
||||
|
||||
visibleStepIndex === 3 && mapReload(); // What is this? Javascript?
|
||||
}
|
||||
|
||||
function navigateStep(isNext) {
|
||||
var currentStep = $('.step:visible');
|
||||
var targetStep = isNext ? currentStep.next('.step') : currentStep.prev('.step');
|
||||
|
||||
if (targetStep.length !== 0) {
|
||||
currentStep.hide();
|
||||
targetStep.show();
|
||||
updateProgressBar(targetStep);
|
||||
} else if (isNext) submitConfig();
|
||||
updateWizardContent();
|
||||
}
|
||||
Reference in New Issue
Block a user