-
const pubClient = new Redis({
- host: REDIS,
- port: REDIS_PORT,
-});
-
- // ------------------------------
- // read from redis
- // ------------------------------
-async function getkey(id) {
- return new Promise((resolve) => {
- pubClient.get(id, function (err, reply) {
- if (err) {
- resolve(null);
- } else {
- if (reply) {
- //console.log("---------fount----------");
- resolve(1);
- } else {
- console.log("----------not fount------------");
- resolve(2);
- }
- }
- });
- });
-}
-
- // ------------------------------
- // check if stream exists
- // ------------------------------
-async function checkstream(data) {
- var res = await getkey(data.id);
- if (res == "1") {
- console.log("Stream is on!");
- } else {
- console.log("Creating Stream....");
-
- var url = URL;
- MongoClient.connect(
- url,
- { useNewUrlParser: true, useUnifiedTopology: true },
- function (err, db) {
- if (err) throw err;
- var dbo = db.db(DATABASE);
- dbo.collection(COLLECTION, onCollectionNew.bind(data));
- }
- );
- }
-}
-
- // ------------------------------
- // --- open socket -------------
- // ------------------------------
-io.on("connection", (s) => {
- console.error("socket connection");
- var usersession = new Object();
- usersession.SOCKET = {};
- usersession.SOCKET.error = {};
- console.error("socket ...");
- s.auth = false;
-
- // ------------------------------
- // --- authenticate
- // ------------------------------
- s.on("authenticate", function (data) {
- const token = data;
- (async () => {
- var isvalid = await checkToken(token);
- if (isvalid.action == "ok") {
- usersession.SOCKET.user = isvalid.user;
- usersession.SOCKET.scope = isvalid.scope; // space delimeter
- usersession.SOCKET.token = isvalid.token;
- usersession.SOCKET.id = s.id;
- s.auth = true;
- } else {
- s.auth = false;
- }
- })();
- });
-
- // ------------------------------
- // --- event ----------------
- // ------------------------------
- s.on("onevent", function (data) {
- var binddata = {
- user: data,
- id: s.id,
- };
- checkstream(binddata);
- });
-
-}
-