@oxiaom/adoremix 1.0.64 → 1.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cli.js +56 -0
- package/src/config/defaults.js +5 -0
- package/src/doctor.js +27 -0
- package/src/mp3server-server.js +184 -0
- package/src/mp3server.js +241 -0
- package/templates/mp3server-winservice.js.tmpl +35 -0
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -539,6 +539,62 @@ function buildProgram() {
|
|
|
539
539
|
}
|
|
540
540
|
});
|
|
541
541
|
|
|
542
|
+
const mp3srv = program
|
|
543
|
+
.command('mp3server')
|
|
544
|
+
.description('MP3Server 选装:TCP 分块推流 MP3 文件(端口 6665,docroot 与 nginx 共用),开机自启');
|
|
545
|
+
|
|
546
|
+
mp3srv
|
|
547
|
+
.command('install')
|
|
548
|
+
.description('注册 MP3Server 系统服务(Linux systemd / Windows 服务,开机自启),写 config.ini [MP3Server]')
|
|
549
|
+
.option('--workdir <path>')
|
|
550
|
+
.action(async (opts) => {
|
|
551
|
+
const mod = require('./mp3server');
|
|
552
|
+
try {
|
|
553
|
+
process.exitCode = await mod.install({ workdir: resolveWorkdir(opts.workdir) });
|
|
554
|
+
} catch (e) {
|
|
555
|
+
logger.error(e.message);
|
|
556
|
+
process.exitCode = 1;
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
mp3srv
|
|
561
|
+
.command('uninstall')
|
|
562
|
+
.description('卸载 MP3Server 服务(保留 config.ini 与 docroot 媒体文件)')
|
|
563
|
+
.option('--workdir <path>')
|
|
564
|
+
.action((opts) => {
|
|
565
|
+
const mod = require('./mp3server');
|
|
566
|
+
try {
|
|
567
|
+
process.exitCode = mod.uninstall({ workdir: resolveWorkdir(opts.workdir) });
|
|
568
|
+
} catch (e) {
|
|
569
|
+
logger.error(e.message);
|
|
570
|
+
process.exitCode = 1;
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
mp3srv
|
|
575
|
+
.command('status')
|
|
576
|
+
.description('检查 MP3Server 服务/端口/docroot 状态')
|
|
577
|
+
.option('--workdir <path>')
|
|
578
|
+
.action(async (opts) => {
|
|
579
|
+
const mod = require('./mp3server');
|
|
580
|
+
try {
|
|
581
|
+
process.exitCode = await mod.status({ workdir: resolveWorkdir(opts.workdir) });
|
|
582
|
+
} catch (e) {
|
|
583
|
+
logger.error(e.message);
|
|
584
|
+
process.exitCode = 1;
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
|
|
588
|
+
mp3srv
|
|
589
|
+
.command('serve')
|
|
590
|
+
.description('前台运行 MP3Server(systemd/Windows 服务内部使用,也可手动调试)')
|
|
591
|
+
.option('--workdir <path>')
|
|
592
|
+
.option('--host <addr>', '监听地址,默认 0.0.0.0')
|
|
593
|
+
.action((opts) => {
|
|
594
|
+
const mod = require('./mp3server');
|
|
595
|
+
mod.serve({ workdir: resolveWorkdir(opts.workdir), host: opts.host });
|
|
596
|
+
});
|
|
597
|
+
|
|
542
598
|
const cfgmgr = program
|
|
543
599
|
.command('config-manager')
|
|
544
600
|
.description('设备配置管理 UI(配置 IP / 修改 config.ini / 查看日志),端口 9877,开机自启');
|
package/src/config/defaults.js
CHANGED
package/src/doctor.js
CHANGED
|
@@ -439,6 +439,33 @@ function runDoctor(workdir, opts) {
|
|
|
439
439
|
}
|
|
440
440
|
}
|
|
441
441
|
|
|
442
|
+
// 8.5 MP3Server 选装体检(部署过才检查,未部署仅提示可选)
|
|
443
|
+
if (process.platform !== 'darwin') {
|
|
444
|
+
const mp3 = require('./mp3server');
|
|
445
|
+
const unitExists = process.platform === 'linux' && fs.existsSync('/etc/systemd/system/adoremix-mp3server.service');
|
|
446
|
+
if (unitExists) {
|
|
447
|
+
logger.log('');
|
|
448
|
+
logger.log('=== MP3Server 检查 ===');
|
|
449
|
+
const mp3Port = (cfgObj.MP3Server && parseInt(cfgObj.MP3Server.port, 10)) || mp3.DEFAULT_PORT;
|
|
450
|
+
const mp3Docroot = (cfgObj.MP3Server && cfgObj.MP3Server.docroot) || path.join(workdir, 'etc', 'docroot');
|
|
451
|
+
if (fs.existsSync(mp3Docroot)) logger.ok(`✓ docroot ${mp3Docroot}`);
|
|
452
|
+
else {
|
|
453
|
+
issues.push({ type: 'mp3server-docroot', severity: 'warn', msg: `MP3Server docroot 不存在:${mp3Docroot}` });
|
|
454
|
+
logger.warn(`⚠ docroot 不存在:${mp3Docroot}`);
|
|
455
|
+
}
|
|
456
|
+
let st = 'unknown';
|
|
457
|
+
try { st = execSync('systemctl is-active adoremix-mp3server 2>/dev/null', { encoding: 'utf8' }).trim(); } catch (e) {}
|
|
458
|
+
if (st === 'active') {
|
|
459
|
+
logger.ok(`✓ adoremix-mp3server 运行中(端口 ${mp3Port})`);
|
|
460
|
+
} else {
|
|
461
|
+
issues.push({ type: 'mp3server-active', severity: 'warn', msg: `adoremix-mp3server 未运行(${st}):systemctl restart adoremix-mp3server,日志 journalctl -u adoremix-mp3server -n 30` });
|
|
462
|
+
logger.warn(`⚠ adoremix-mp3server 未运行(${st})`);
|
|
463
|
+
}
|
|
464
|
+
} else {
|
|
465
|
+
logger.log('○ MP3Server 未安装(选装:adoremix mp3server install)');
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
442
469
|
// 9. Audio8 本机部署体检(Linux + 本机装了 audio8 或 provider=audio8 且指向本机时)
|
|
443
470
|
if (process.platform === 'linux') {
|
|
444
471
|
const a8 = require('./doctor-audio8');
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* MP3Server 协议服务(Node 版,与 Adore_mix2/MP3Server C++ 版逐条对齐)
|
|
5
|
+
*
|
|
6
|
+
* 协议:
|
|
7
|
+
* 1. 客户端连上后发一行相对路径(music/a.mp3\n)
|
|
8
|
+
* 2. 服务端回一行音频字节数(已跳过 ID3v2 标签)+"\n"
|
|
9
|
+
* 3. 客户端发一行字节数 N,服务端回 N 字节音频;重复
|
|
10
|
+
* 4. 读到文件尾:服务端回 "close\n" 并断开;客户端可随时发 "close"
|
|
11
|
+
*
|
|
12
|
+
* 与原 C++ 版差异(仅健壮性,不改变线协议):
|
|
13
|
+
* - 路径按行读取(原版 readAll().trimmed(),路径分包时会出错)
|
|
14
|
+
* - 空闲 10 分钟自动断开(原版无超时,掉线客户端会挂住)
|
|
15
|
+
* - 错误响应 "error: ...\n" 与原版一致
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const net = require('net');
|
|
20
|
+
const path = require('path');
|
|
21
|
+
|
|
22
|
+
const MAX_CHUNK = 1024 * 1024; // 单次最多 1MB(与原版一致)
|
|
23
|
+
const IDLE_TIMEOUT_MS = 10 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
// MP3 帧头校验(与 C++ isValidMp3Header 完全一致)
|
|
26
|
+
function isValidMp3Header(buf, i) {
|
|
27
|
+
if (buf[i] !== 0xFF || (buf[i + 1] & 0xE0) !== 0xE0) return false;
|
|
28
|
+
const versionBits = (buf[i + 1] >> 3) & 0x03;
|
|
29
|
+
if (versionBits === 0x01) return false;
|
|
30
|
+
const layerBits = (buf[i + 1] >> 1) & 0x03;
|
|
31
|
+
if (layerBits === 0x00) return false;
|
|
32
|
+
const bitrateBits = (buf[i + 2] >> 4) & 0x0F;
|
|
33
|
+
if (bitrateBits === 0x00 || bitrateBits === 0x0F) return false;
|
|
34
|
+
const samplerateBits = (buf[i + 2] >> 2) & 0x03;
|
|
35
|
+
if (samplerateBits === 0x03) return false;
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 查找首个 MP3 音频帧位置(跳过 ID3v2 标签 + 扫描帧同步字),带缓存
|
|
40
|
+
function findFirstAudioFrame(fd, fileSize, cachePath, cache) {
|
|
41
|
+
if (cache.has(cachePath)) return cache.get(cachePath);
|
|
42
|
+
|
|
43
|
+
const header = Buffer.alloc(10);
|
|
44
|
+
let audioStart = 0;
|
|
45
|
+
const hn = fs.readSync(fd, header, 0, 10, 0);
|
|
46
|
+
if (hn >= 10 && header.toString('latin1', 0, 3) === 'ID3') {
|
|
47
|
+
audioStart = 10 + (
|
|
48
|
+
((header[6] & 0x7F) << 21) |
|
|
49
|
+
((header[7] & 0x7F) << 14) |
|
|
50
|
+
((header[8] & 0x7F) << 7) |
|
|
51
|
+
(header[9] & 0x7F)
|
|
52
|
+
);
|
|
53
|
+
} else {
|
|
54
|
+
audioStart = 0;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const BUF = 4096;
|
|
58
|
+
const buf = Buffer.alloc(BUF);
|
|
59
|
+
let found = false;
|
|
60
|
+
let pos = audioStart;
|
|
61
|
+
while (!found && pos < fileSize) {
|
|
62
|
+
const n = fs.readSync(fd, buf, 0, BUF, pos);
|
|
63
|
+
if (n < 4) break;
|
|
64
|
+
for (let i = 0; i <= n - 4; i++) {
|
|
65
|
+
if (isValidMp3Header(buf, i)) { audioStart = pos + i; found = true; break; }
|
|
66
|
+
}
|
|
67
|
+
if (!found) pos += Math.max(1, n - 3); // 回退 3 字节防帧头跨块
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const result = found ? audioStart : 0;
|
|
71
|
+
cache.set(cachePath, result);
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function validateRelPath(rel, root) {
|
|
76
|
+
if (!rel || rel.indexOf('../') >= 0 || rel.startsWith('/')) return null;
|
|
77
|
+
const abs = path.resolve(root, rel);
|
|
78
|
+
const rootAbs = path.resolve(root);
|
|
79
|
+
if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) return null;
|
|
80
|
+
return abs;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function startServer(opts) {
|
|
84
|
+
const root = path.resolve(opts.docroot);
|
|
85
|
+
const port = opts.port || 6665;
|
|
86
|
+
const host = opts.host || '0.0.0.0';
|
|
87
|
+
const log = opts.log || ((m) => console.log(m));
|
|
88
|
+
const frameCache = new Map();
|
|
89
|
+
|
|
90
|
+
const server = net.createServer((sock) => {
|
|
91
|
+
const peer = `${sock.remoteAddress}:${sock.remotePort}`;
|
|
92
|
+
let fd = null;
|
|
93
|
+
let audioStart = 0;
|
|
94
|
+
let fileSize = 0;
|
|
95
|
+
let filePath = '';
|
|
96
|
+
let state = 'path'; // path → chunks
|
|
97
|
+
let pending = Buffer.alloc(0);
|
|
98
|
+
let closed = false;
|
|
99
|
+
|
|
100
|
+
const cleanup = () => {
|
|
101
|
+
if (closed) return;
|
|
102
|
+
closed = true;
|
|
103
|
+
if (fd !== null) { try { fs.closeSync(fd); } catch (e) {} fd = null; }
|
|
104
|
+
};
|
|
105
|
+
const fail = (msg) => {
|
|
106
|
+
log(`[warn] ${peer} ${msg}`);
|
|
107
|
+
try { sock.write('error: ' + msg + '\n'); } catch (e) {}
|
|
108
|
+
try { sock.end(); } catch (e) {}
|
|
109
|
+
cleanup();
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
sock.setTimeout(IDLE_TIMEOUT_MS, () => { log(`[info] ${peer} 空闲超时`); sock.destroy(); });
|
|
113
|
+
sock.on('error', (err) => { log(`[warn] ${peer} socket: ${err.message}`); cleanup(); });
|
|
114
|
+
sock.on('close', () => { cleanup(); log(`[info] ${peer} 断开`); });
|
|
115
|
+
|
|
116
|
+
const handleLine = (lineRaw) => {
|
|
117
|
+
const line = lineRaw.trim();
|
|
118
|
+
if (state === 'path') {
|
|
119
|
+
const abs = validateRelPath(line, root);
|
|
120
|
+
if (!abs) return fail('Invalid file path');
|
|
121
|
+
let st;
|
|
122
|
+
try { st = fs.statSync(abs); } catch (e) { return fail('File not found or cannot open'); }
|
|
123
|
+
if (!st.isFile()) return fail('File not found or cannot open');
|
|
124
|
+
try { fd = fs.openSync(abs, 'r'); } catch (e) { return fail('File not found or cannot open'); }
|
|
125
|
+
try {
|
|
126
|
+
audioStart = findFirstAudioFrame(fd, st.size, abs, frameCache);
|
|
127
|
+
} catch (e) {
|
|
128
|
+
return fail('Invalid MP3 file format');
|
|
129
|
+
}
|
|
130
|
+
filePath = line;
|
|
131
|
+
fileSize = st.size - audioStart;
|
|
132
|
+
state = 'chunks';
|
|
133
|
+
log(`[info] ${peer} 推送 ${line} 起始=${audioStart} 大小=${fileSize}`);
|
|
134
|
+
sock.write(String(fileSize) + '\n');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// chunks 状态
|
|
139
|
+
if (line.toLowerCase() === 'close') {
|
|
140
|
+
try { sock.end(); } catch (e) {}
|
|
141
|
+
cleanup();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
let n = parseInt(line, 10);
|
|
145
|
+
if (!isFinite(n) || n <= 0) return fail('Invalid chunk size');
|
|
146
|
+
n = Math.min(n, MAX_CHUNK);
|
|
147
|
+
|
|
148
|
+
const buf = Buffer.alloc(n);
|
|
149
|
+
let got;
|
|
150
|
+
try { got = fs.readSync(fd, buf, 0, n, null); } catch (e) { return fail('File read error'); }
|
|
151
|
+
if (got === 0) {
|
|
152
|
+
// 到文件尾:回 close 并断开(与 C++ 一致)
|
|
153
|
+
try { sock.write('close\n', () => sock.end()); } catch (e) {}
|
|
154
|
+
cleanup();
|
|
155
|
+
log(`[info] ${peer} 完成 ${filePath}`);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (!sock.write(buf.subarray(0, got))) {
|
|
159
|
+
// 背压:等 drain 再继续读下一行(简单起见暂停处理)
|
|
160
|
+
sock.pause();
|
|
161
|
+
sock.once('drain', () => sock.resume());
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
sock.on('data', (chunk) => {
|
|
166
|
+
pending = Buffer.concat([pending, chunk]);
|
|
167
|
+
let idx;
|
|
168
|
+
while ((idx = pending.indexOf(0x0A)) >= 0) {
|
|
169
|
+
const line = pending.subarray(0, idx);
|
|
170
|
+
pending = pending.subarray(idx + 1);
|
|
171
|
+
handleLine(line.toString('utf8'));
|
|
172
|
+
if (closed) return;
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
server.on('error', (err) => log(`[error] ${err.message}`));
|
|
178
|
+
server.listen(port, host, () => {
|
|
179
|
+
log(`[ok] MP3Server 监听 ${host}:${port},docroot=${root}`);
|
|
180
|
+
});
|
|
181
|
+
return server;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = { startServer, findFirstAudioFrame, isValidMp3Header, validateRelPath };
|
package/src/mp3server.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* MP3Server 选装组件:TCP 分块推流 MP3 文件(默认端口 6665)
|
|
5
|
+
*
|
|
6
|
+
* 协议见 mp3server-server.js(与 Adore_mix2/MP3Server C++ 版线协议一致)。
|
|
7
|
+
* 实现用 Node(跨平台零编译,与 AdoreMix 主包同一套分发),
|
|
8
|
+
* 由 systemd(Linux)/ node-windows(Windows)托管,开机自启。
|
|
9
|
+
*
|
|
10
|
+
* 配置:config.ini [MP3Server] port=6665 docroot=(空=工作目录/etc/docroot,与 nginx 共用)
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const net = require('net');
|
|
16
|
+
const os = require('os');
|
|
17
|
+
const { execSync } = require('child_process');
|
|
18
|
+
const logger = require('./logger');
|
|
19
|
+
const paths = require('./paths');
|
|
20
|
+
|
|
21
|
+
const UNIT_NAME = 'adoremix-mp3server';
|
|
22
|
+
const SYSTEM_UNIT_PATH = `/etc/systemd/system/${UNIT_NAME}.service`;
|
|
23
|
+
const WINSVC_NAME = 'AdoreMp3Server';
|
|
24
|
+
const DEFAULT_PORT = 6665;
|
|
25
|
+
|
|
26
|
+
function readSettings(workdir) {
|
|
27
|
+
const cfg = require('./config');
|
|
28
|
+
const obj = cfg.readConfig(workdir) || {};
|
|
29
|
+
const s = obj.MP3Server || {};
|
|
30
|
+
return {
|
|
31
|
+
port: parseInt(s.port, 10) || DEFAULT_PORT,
|
|
32
|
+
docroot: s.docroot && String(s.docroot).trim()
|
|
33
|
+
? String(s.docroot).trim()
|
|
34
|
+
: path.join(workdir, 'etc', 'docroot')
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function portOpen(port, host) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
const sock = net.connect({ port, host: host || '127.0.0.1' });
|
|
41
|
+
const done = (ok) => { try { sock.destroy(); } catch (e) {} resolve(ok); };
|
|
42
|
+
sock.setTimeout(2000);
|
|
43
|
+
sock.once('connect', () => done(true));
|
|
44
|
+
sock.once('timeout', () => done(false));
|
|
45
|
+
sock.once('error', () => done(false));
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 前台运行(systemd / Windows 服务 / 手动调试都走这个入口)
|
|
50
|
+
function serve(opts) {
|
|
51
|
+
opts = opts || {};
|
|
52
|
+
const workdir = opts.workdir || paths.defaultWorkdir();
|
|
53
|
+
const { port, docroot } = readSettings(workdir);
|
|
54
|
+
if (!fs.existsSync(docroot)) {
|
|
55
|
+
try { fs.mkdirSync(docroot, { recursive: true }); } catch (e) {}
|
|
56
|
+
}
|
|
57
|
+
const { startServer } = require('./mp3server-server');
|
|
58
|
+
startServer({
|
|
59
|
+
port,
|
|
60
|
+
host: opts.host || '0.0.0.0',
|
|
61
|
+
docroot,
|
|
62
|
+
log: (m) => logger.log(m)
|
|
63
|
+
});
|
|
64
|
+
return null; // 常驻,不返回
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function buildSystemdUnit(workdir, port) {
|
|
68
|
+
const user = process.getuid && process.getuid() === 0 ? 'root' : os.userInfo().username;
|
|
69
|
+
return `[Unit]
|
|
70
|
+
Description=AdoreMix MP3Server (TCP chunked MP3 streaming)
|
|
71
|
+
Documentation=https://github.com/oxiaom/adoremix-npm
|
|
72
|
+
After=network.target
|
|
73
|
+
|
|
74
|
+
[Service]
|
|
75
|
+
Type=simple
|
|
76
|
+
User=${user}
|
|
77
|
+
Group=${user}
|
|
78
|
+
WorkingDirectory=${workdir}
|
|
79
|
+
ExecStart=${paths.nodeExecutable()} ${paths.cliBin()} mp3server serve --workdir ${workdir}
|
|
80
|
+
Restart=on-failure
|
|
81
|
+
RestartSec=5
|
|
82
|
+
StandardOutput=append:${path.join(workdir, 'logs', 'mp3server.log')}
|
|
83
|
+
StandardError=append:${path.join(workdir, 'logs', 'mp3server.log')}
|
|
84
|
+
LimitNOFILE=65536
|
|
85
|
+
|
|
86
|
+
[Install]
|
|
87
|
+
WantedBy=multi-user.target
|
|
88
|
+
`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function installWindowsService(workdir) {
|
|
92
|
+
let hasNodeWindows = false;
|
|
93
|
+
try { require.resolve('node-windows'); hasNodeWindows = true; } catch (e) {}
|
|
94
|
+
if (!hasNodeWindows) {
|
|
95
|
+
logger.warn('node-windows 未安装,尝试在工作目录安装...');
|
|
96
|
+
try {
|
|
97
|
+
execSync('npm install --no-save node-windows', { cwd: workdir, stdio: 'inherit' });
|
|
98
|
+
} catch (e) {
|
|
99
|
+
logger.error(`node-windows 安装失败(需管理员权限):${(e.message || '').split('\n')[0]}`);
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const tpl = fs.readFileSync(path.join(__dirname, '..', 'templates', 'mp3server-winservice.js.tmpl'), 'utf8');
|
|
104
|
+
const wrapper = path.join(workdir, 'mp3server-winservice.js');
|
|
105
|
+
fs.writeFileSync(wrapper, tpl
|
|
106
|
+
.replace(/__NODE__/g, paths.nodeExecutable().replace(/\\/g, '\\\\'))
|
|
107
|
+
.replace(/__CLI__/g, paths.cliBin().replace(/\\/g, '\\\\'))
|
|
108
|
+
.replace(/__WORKDIR__/g, workdir.replace(/\\/g, '\\\\'))
|
|
109
|
+
.replace(/__SVC_NAME__/g, WINSVC_NAME), 'utf8');
|
|
110
|
+
try {
|
|
111
|
+
execSync(`node "${wrapper}" install`, { cwd: workdir, stdio: 'inherit' });
|
|
112
|
+
return true;
|
|
113
|
+
} catch (e) {
|
|
114
|
+
logger.error(`Windows 服务注册失败(需管理员权限):${(e.message || '').split('\n')[0]}`);
|
|
115
|
+
logger.log(`可前台运行:adoremix mp3server serve --workdir "${workdir}"`);
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function install(opts) {
|
|
121
|
+
opts = opts || {};
|
|
122
|
+
const workdir = opts.workdir || paths.defaultWorkdir();
|
|
123
|
+
const { port, docroot } = readSettings(workdir);
|
|
124
|
+
|
|
125
|
+
fs.mkdirSync(workdir, { recursive: true });
|
|
126
|
+
fs.mkdirSync(path.join(workdir, 'logs'), { recursive: true });
|
|
127
|
+
fs.mkdirSync(docroot, { recursive: true });
|
|
128
|
+
|
|
129
|
+
// 写 config.ini(已有配置保留用户值)
|
|
130
|
+
try {
|
|
131
|
+
const cfg = require('./config');
|
|
132
|
+
const obj = cfg.readConfig(workdir) || {};
|
|
133
|
+
if (!obj.MP3Server) {
|
|
134
|
+
cfg.setConfigValue(workdir, 'MP3Server.port', port);
|
|
135
|
+
cfg.setConfigValue(workdir, 'MP3Server.docroot', docroot);
|
|
136
|
+
}
|
|
137
|
+
logger.ok(`config.ini [MP3Server] port=${port} docroot=${docroot}`);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
logger.warn(`config.ini 写入失败:${e.message}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
let ok = false;
|
|
143
|
+
if (process.platform === 'linux') {
|
|
144
|
+
try {
|
|
145
|
+
fs.writeFileSync(SYSTEM_UNIT_PATH, buildSystemdUnit(workdir, port), 'utf8');
|
|
146
|
+
execSync('systemctl daemon-reload', { stdio: 'pipe' });
|
|
147
|
+
execSync(`systemctl enable ${UNIT_NAME}`, { stdio: 'pipe' });
|
|
148
|
+
execSync(`systemctl restart ${UNIT_NAME}`, { stdio: 'pipe' });
|
|
149
|
+
logger.ok(`systemd 服务已注册并启动:${UNIT_NAME}`);
|
|
150
|
+
ok = true;
|
|
151
|
+
} catch (e) {
|
|
152
|
+
logger.error(`systemd 配置失败:${(e.message || '').split('\n')[0]}`);
|
|
153
|
+
logger.log(`可前台运行:adoremix mp3server serve --workdir "${workdir}"`);
|
|
154
|
+
}
|
|
155
|
+
} else if (process.platform === 'win32') {
|
|
156
|
+
ok = installWindowsService(workdir);
|
|
157
|
+
} else {
|
|
158
|
+
logger.warn('macOS 不支持注册系统服务,可手动前台运行:adoremix mp3server serve');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (ok) {
|
|
162
|
+
let up = false;
|
|
163
|
+
for (let i = 0; i < 6; i++) {
|
|
164
|
+
if (await portOpen(port)) { up = true; break; }
|
|
165
|
+
await new Promise(r => setTimeout(r, 800));
|
|
166
|
+
}
|
|
167
|
+
if (up) logger.ok(`端口 ${port} 已监听`);
|
|
168
|
+
else logger.warn(`端口 ${port} 暂不可连接(journalctl -u ${UNIT_NAME} -n 30)`);
|
|
169
|
+
}
|
|
170
|
+
logger.ok(`MP3Server 安装完成 → tcp://0.0.0.0:${port}(docroot: ${docroot})`);
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function uninstall(opts) {
|
|
175
|
+
opts = opts || {};
|
|
176
|
+
const workdir = opts.workdir || paths.defaultWorkdir();
|
|
177
|
+
if (process.platform === 'linux') {
|
|
178
|
+
try {
|
|
179
|
+
execSync(`systemctl disable --now ${UNIT_NAME} 2>/dev/null; true`, { stdio: 'pipe', shell: '/bin/bash' });
|
|
180
|
+
execSync(`rm -f ${SYSTEM_UNIT_PATH} && systemctl daemon-reload`, { stdio: 'pipe', shell: '/bin/bash' });
|
|
181
|
+
} catch (e) { logger.warn(`卸载服务部分出错:${e.message}`); }
|
|
182
|
+
} else if (process.platform === 'win32') {
|
|
183
|
+
const wrapper = path.join(workdir, 'mp3server-winservice.js');
|
|
184
|
+
if (fs.existsSync(wrapper)) {
|
|
185
|
+
try { execSync(`node "${wrapper}" uninstall`, { cwd: workdir, stdio: 'inherit' }); } catch (e) {
|
|
186
|
+
logger.warn(`Windows 服务卸载失败(需管理员):${(e.message || '').split('\n')[0]}`);
|
|
187
|
+
}
|
|
188
|
+
try { fs.rmSync(wrapper, { force: true }); } catch (e) {}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
logger.ok('MP3Server 已卸载(config.ini 配置与 docroot 媒体文件保留)');
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function status(opts) {
|
|
196
|
+
opts = opts || {};
|
|
197
|
+
const workdir = opts.workdir || paths.defaultWorkdir();
|
|
198
|
+
const { port, docroot } = readSettings(workdir);
|
|
199
|
+
let problems = 0;
|
|
200
|
+
|
|
201
|
+
logger.log(`配置:port=${port} docroot=${docroot}`);
|
|
202
|
+
if (!fs.existsSync(docroot)) {
|
|
203
|
+
logger.warn(`docroot 不存在:${docroot}`);
|
|
204
|
+
problems++;
|
|
205
|
+
} else {
|
|
206
|
+
let count = 0;
|
|
207
|
+
try {
|
|
208
|
+
count = execSync(`find "${docroot}" -type f 2>/dev/null | wc -l`, { encoding: 'utf8', shell: '/bin/bash' }).trim();
|
|
209
|
+
} catch (e) {}
|
|
210
|
+
logger.ok(`docroot 存在(${count} 个文件)`);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (process.platform === 'linux') {
|
|
214
|
+
const active = (function () {
|
|
215
|
+
try { return execSync(`systemctl is-active ${UNIT_NAME} 2>/dev/null`, { encoding: 'utf8' }).trim(); }
|
|
216
|
+
catch (e) { return 'inactive'; }
|
|
217
|
+
})();
|
|
218
|
+
const enabled = (function () {
|
|
219
|
+
try { return execSync(`systemctl is-enabled ${UNIT_NAME} 2>/dev/null`, { encoding: 'utf8' }).trim(); }
|
|
220
|
+
catch (e) { return 'disabled'; }
|
|
221
|
+
})();
|
|
222
|
+
if (active === 'active') logger.ok(`systemd:active(开机自启:${enabled})`);
|
|
223
|
+
else { logger.warn(`systemd:${active}(journalctl -u ${UNIT_NAME} -n 30)`); problems++; }
|
|
224
|
+
} else if (process.platform === 'win32') {
|
|
225
|
+
try {
|
|
226
|
+
const out = execSync(`sc query ${WINSVC_NAME}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
227
|
+
if (/RUNNING/.test(out)) logger.ok(`Windows 服务:RUNNING(${WINSVC_NAME})`);
|
|
228
|
+
else { logger.warn(`Windows 服务未运行(${WINSVC_NAME})`); problems++; }
|
|
229
|
+
} catch (e) {
|
|
230
|
+
logger.warn(`Windows 服务未注册(${WINSVC_NAME})`);
|
|
231
|
+
problems++;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const open = await portOpen(port);
|
|
236
|
+
if (open) logger.ok(`端口 ${port} 可连接`);
|
|
237
|
+
else { logger.warn(`端口 ${port} 不可连接`); problems++; }
|
|
238
|
+
return problems ? 1 : 0;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
module.exports = { install, uninstall, status, serve, DEFAULT_PORT, UNIT_NAME, WINSVC_NAME };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// 该文件由 `adoremix mp3server install` 在工作目录生成。
|
|
3
|
+
// 通过 node-windows 把 `adoremix mp3server serve` 注册为 Windows 服务。
|
|
4
|
+
// 用法:node mp3server-winservice.js install|uninstall
|
|
5
|
+
|
|
6
|
+
const SVC_NAME = '__SVC_NAME__';
|
|
7
|
+
const NODE = '__NODE__';
|
|
8
|
+
const CLI = '__CLI__';
|
|
9
|
+
const WORKDIR = '__WORKDIR__';
|
|
10
|
+
|
|
11
|
+
const Service = require('node-windows').Service;
|
|
12
|
+
|
|
13
|
+
const svc = new Service({
|
|
14
|
+
name: SVC_NAME,
|
|
15
|
+
description: 'AdoreMix MP3Server (TCP chunked MP3 streaming)',
|
|
16
|
+
script: CLI,
|
|
17
|
+
execPath: NODE,
|
|
18
|
+
args: ['mp3server', 'serve', '--workdir', WORKDIR],
|
|
19
|
+
cwd: WORKDIR,
|
|
20
|
+
env: [{ name: 'NODE_ENV', value: 'production' }]
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
svc.on('install', () => { console.log('[ok] 服务已安装:' + SVC_NAME); svc.start(); });
|
|
24
|
+
svc.on('alreadyinstalled', () => { console.log('[warn] 服务已存在:' + SVC_NAME); });
|
|
25
|
+
svc.on('start', () => console.log('[ok] 服务已启动:' + SVC_NAME));
|
|
26
|
+
svc.on('stop', () => console.log('[ok] 服务已停止:' + SVC_NAME));
|
|
27
|
+
svc.on('uninstall', () => console.log('[ok] 服务已卸载:' + SVC_NAME));
|
|
28
|
+
svc.on('error', (err) => { console.error('[err] ' + err.message); process.exit(1); });
|
|
29
|
+
|
|
30
|
+
const cmd = process.argv[2] || 'install';
|
|
31
|
+
if (cmd === 'install') svc.install();
|
|
32
|
+
else if (cmd === 'uninstall') svc.uninstall();
|
|
33
|
+
else if (cmd === 'start') svc.start();
|
|
34
|
+
else if (cmd === 'stop') svc.stop();
|
|
35
|
+
else { console.error('用法:node mp3server-winservice.js install|uninstall|start|stop'); process.exit(1); }
|