2022-07-08 19:17:56 +01:00
|
|
|
import NodeCache from "node-cache";
|
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
import { sha256 } from "../sub/crypto.js";
|
2022-07-08 19:17:56 +01:00
|
|
|
import { streamLifespan } from "../config.js";
|
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
const streamCache = new NodeCache({ stdTTL: streamLifespan/1000, checkperiod: 10, deleteOnExpire: true });
|
2022-11-12 16:40:11 +00:00
|
|
|
const salt = process.env.streamSalt;
|
2022-07-08 19:17:56 +01:00
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
streamCache.on("expired", (key) => {
|
|
|
|
streamCache.del(key);
|
|
|
|
});
|
|
|
|
|
2022-07-08 19:17:56 +01:00
|
|
|
export function createStream(obj) {
|
2023-01-13 18:34:48 +00:00
|
|
|
let streamID = sha256(`${obj.ip},${obj.service},${obj.filename},${obj.audioFormat},${obj.mute}`, salt),
|
2022-07-08 19:17:56 +01:00
|
|
|
exp = Math.floor(new Date().getTime()) + streamLifespan,
|
2023-01-13 18:34:48 +00:00
|
|
|
ghmac = sha256(`${streamID},${obj.service},${obj.ip},${exp}`, salt);
|
2022-11-12 16:40:11 +00:00
|
|
|
|
2023-01-13 18:34:48 +00:00
|
|
|
if (!streamCache.has(streamID)) {
|
|
|
|
streamCache.set(streamID, {
|
|
|
|
id: streamID,
|
|
|
|
service: obj.service,
|
|
|
|
type: obj.type,
|
|
|
|
urls: obj.u,
|
|
|
|
filename: obj.filename,
|
|
|
|
hmac: ghmac,
|
|
|
|
ip: obj.ip,
|
|
|
|
exp: exp,
|
|
|
|
isAudioOnly: !!obj.isAudioOnly,
|
|
|
|
audioFormat: obj.audioFormat,
|
|
|
|
time: obj.time ? obj.time : false,
|
|
|
|
copy: !!obj.copy,
|
|
|
|
mute: !!obj.mute,
|
|
|
|
metadata: obj.fileMetadata ? obj.fileMetadata : false
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
let streamInfo = streamCache.get(streamID);
|
|
|
|
exp = streamInfo.exp;
|
|
|
|
ghmac = streamInfo.hmac;
|
|
|
|
}
|
|
|
|
return `${process.env.selfURL}api/stream?t=${streamID}&e=${exp}&h=${ghmac}`;
|
2022-07-08 19:17:56 +01:00
|
|
|
}
|
|
|
|
|
2022-11-12 16:40:11 +00:00
|
|
|
export function verifyStream(ip, id, hmac, exp) {
|
2022-07-08 19:17:56 +01:00
|
|
|
try {
|
|
|
|
let streamInfo = streamCache.get(id);
|
|
|
|
if (streamInfo) {
|
2023-01-13 18:34:48 +00:00
|
|
|
let ghmac = sha256(`${id},${streamInfo.service},${ip},${exp}`, salt);
|
2023-01-29 18:17:33 +00:00
|
|
|
if (hmac == ghmac && exp.toString() == streamInfo.exp && ghmac == streamInfo.hmac && ip == streamInfo.ip && exp > Math.floor(new Date().getTime())) {
|
2022-07-08 19:17:56 +01:00
|
|
|
return streamInfo;
|
|
|
|
} else {
|
|
|
|
return { error: 'Unauthorized', status: 401 };
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return { error: 'this stream token does not exist', status: 400 };
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
return { status: 500, body: { status: "error", text: "Internal Server Error" } };
|
|
|
|
}
|
2022-08-01 16:48:37 +01:00
|
|
|
}
|