Untitled

 avatar
unknown
plain_text
a year ago
11 kB
7
Indexable

const tls = require('tls');
const crypto = require('crypto');
const EventEmitter = require('events');
const { SendApi, setup_network, send_message, send_button_message, SendAfmApi } = require("./sendHttpRequest");
const express = require('express');
const app = express();
var http = require("http").Server(app);
const fs = require('fs');
const path = require('path');


class Server extends EventEmitter {

    constructor(server, port, password) {
        super();
        this.server_name = "azerforum.smartbee.az";
        this.server = server;
        this.sUID = "";
        this.port = port;
        this.password = password;
        this.connect();
        this.startPing();
        this.aUsers = [];
        this.UserList = [];
        this.channels = [];
    }
    connect() {
        const options = {
            rejectUnauthorized: false,
            ciphers: 'ECDHE-ECDSA-AES256-GCM-SHA384'
        };
        this.socket = tls.connect(this.port, this.server, options, () => {
            this.initializeConnection();
            this.Security();
            this.SVSLog("Services is now online and synced. Starting... ");
            this.emit('connected');
        });

        this.socket.on('data', (data) => {
            var rawData = data.toString();
            var lines = rawData.split('\n');
            lines.forEach((line) => {
				
				console.log(line);
                if (line.indexOf('Z :') !== -1) {
                    line = line.split('Z :')[1];
                }               
				if (line.indexOf('UID') !== -1) {
					this.UserParse(line);
                }				
				if (line.indexOf('SJOIN') !== -1) {
					this.SJOIN(line);
					this.emit('SJOIN', line );
                }				
				if (line.indexOf('PRIVMSG') !== -1) {
					this.PRIVMSG(line);
					this.emit('PRIVMSG', line );
                }				
				if (line.indexOf('NICK') !== -1) {
					this.NICK(line);
					this.emit('NICK', line );
                }				
				if (line.indexOf('VERSION') !== -1) {
					this.VERSION(line);
					this.emit('VERSION', line );
                }				
				if (line.indexOf('MOTD') !== -1) {
					this.MOTD(line);
					this.emit('MOTD', line );
                } 
            });
        });
		
        this.socket.on('error', (error) => {
            console.error('Error:', error);
            this.SVSLog("Error"); 
        });
        this.socket.on('end', () => {
            this.SVSLog('Disconnected from server');
        });
    }
    initializeConnection() {
        this.sendRaw("PASS " + this.password);
        this.sendRaw("PROTOCTL EAUTH="+this.server_name+",6000,,Smartbee-v1 SID=69L");
        this.sendRaw("PROTOCTL NOQUIT NICKv2 SJOIN SJOIN2 SJ3 CLK TKLEXT2 NICKIP ESVID MLOCK NEXTBANS EXTSWHOIS SJSBY MTAGS");
        this.sendRaw("SERVER "+this.server_name+" 1 :SmartBEE IRC Server");
        this.sendRaw("EOS");
    }
    sendRaw(string) {
        if (this.socket && this.socket.writable) {
            this.socket.write(string + '\n');
        }
    }
    clean(line) {
		return line;	
		
		if (line.startsWith(':')) {
			return line.slice(1);
		}
		return line;		
    }
    startPing() {
        setInterval(() => {
            this.sendRaw("PING :web.smartbee.az");
        }, 30000);
    }
    AddServ(nickname) {
        const uid = this.generateUid(nickname);
        this.sendRaw("UID " + nickname + " 0 " + this.ServerTime() + " services smartbee.az " + uid + " 0 +io * * * :" + nickname);
        
		this.sendRaw("SJOIN " + this.ServerTime() + " " + "#services  :" + uid);
        this.sendRaw("MODE #services +o " + nickname);
		
        this.sendRaw("SJOIN " + this.ServerTime() + " " + "#chat  :" + uid);
        this.sendRaw("MODE #chat +o " + nickname);

        this.sUID = uid;
        this.aUsers[uid] = { "user_name": nickname };
    }
    UserParse(line) {
		
		var uline = line.split(':')[1];
		const parts = line.split(' ');
		const SID = parts[1];
		const UID = parts[8];
		const nick = parts[3]; 
		const time = parts[5];
		const ident = parts[6];
		const ip = parts[7];
		const ip_prefix = parts[12];
		const mode = parts[10];
		const id = parts[13];
		this.aUsers[UID] = { 
			"UID": UID, 
			"nick": nick, 
			"ident": ident, 
			"ip": ip, 
			"ip_prefix": ip_prefix, 
			"time": time, 
			"mode":mode,
			"id":id 
			};				
		this.emit('user', this.aUsers[UID] );
    }
	TKL(line)
	{
		const tline = line.split('TKL ')[1];
		const parts = tline.split(' ');
		const message = parts.slice(7).join(' '); // Corrected to avoid additional spaces

		const isAddition = parts[0] === "+";
		const type = parts[1];
		const userThing = parts[2]; // "user-thing", often "*"
		const mask = parts[3];
		const setBy = parts[4];
		const expiry = parts[5];
		const timestamp = parts[6];
		
		this.SVSLog(`TKL ${isAddition ? '+' : '-'} ${type} ${userThing} ${mask} ${setBy} ${expiry} ${timestamp} ${message}`);

	}	
	MOTD(line)
	{
		const parts = line.split(' ');
		const UID = this.clean(parts[0]);
		this.S2S("422 "+this.clean(UID)+" :No MOTD found. (E-mail: info@smartbee.az)");
		this.SVSLog(this.aUsers[UID]['nick']+" /motd "+this.server_name);
		console.log(parts);
	}	
	VERSION(line)
	{
		if (line.startsWith(':')) {
			line = line.slice(1);
		}
		const parts = line.split(' ');
		const UID = this.clean(parts[0]);
		this.S2S("351 "+this.clean(UID)+" :Smartbee.az(IRCD services) 1.0.0. "+this.server_name);
		this.SVSLog(this.aUsers[UID]['nick']+" /VERSION "+this.server_name);
		console.log(line);
	}		
	NICK(line)
	{
		console.log(line);
	}	
	SJOIN(line)
	{
		const parts = line.split(' ');
		const channel = parts[3];
		const uid = this.clean(parts[4]);
		
		
		
		if (!this.channels || !this.channels[channel]) {
			//this.sendRaw("SJOIN " + this.ServerTime() + " " + channel + " :" + this.sUID);
			
			//this.sendRaw("SVS2MODE "+channel+" +o Security");
			//this.sendRaw(":"+this.sUID+" MODE "+channel+" +o Security");
			this.channels[channel] = 1;
		}
	}	
	PRIVMSG(line) {
		const parts = line.split(' ');
		const uid = parts[2];
		const uid0 = parts[0];
		const message = parts.slice(3).join(' '); // Corrected to avoid additional spaces
		if (this.aUsers[uid]) { 
			this.SVSLog("Private " + uid0 + " " + uid + " " + message);
			this.S2S(":" + uid + " PRIVMSG "+uid0+" " + message);
		} else {
			//this.SVSLog("Channel " + uid0 + " " + uid + " " + message);
		}
	}
	
	
    ServerTime() {
        return Math.floor(Date.now() / 1000);
    }

    Security() {
        //this.AddServ("AINServ");
        this.AddServ("Security");

    }
    generateUid(str) {
        const hash = crypto.createHash('md5').update(str).digest('hex');
        return "69L" + hash.substring(0, 6).toUpperCase();
    }
	new_msgid() {
		const bytes = crypto.randomBytes(24);
		return bytes.toString('base64');
	}
    S2S(string) {
        this.sendRaw(string);
    }

    SVSLog(string) {
        this.S2S(":" + this.sUID + " PRIVMSG #services :" + string);
    }

    joinChannelWithUser(nickname, user_id, channel, email) {
        const uid = this.generateUid(nickname);
        const timestamp = Math.floor(Date.now() / 1000);
        this.sendRaw("UID " + nickname + " 0 " + timestamp + " " + user_id + " " + nickname + ".smartbee.az " + uid + " 0 +iwxzWr * * * :" + email);
        this.sendRaw("SJOIN " + timestamp + " " + channel + " :" + uid);
        this.S2S("SWHOIS " + uid + " :is logged in as " + email);
        this.S2S("SWHOIS " + uid + " :is connecting from Azerbaijan");
        this.aUsers[uid] = { "nick": nickname, 'uid': uid, 'expiry': 0 };
        this.UserList[nickname] = this.aUsers[uid];
    }

    formatTime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;
         return `${hours} hours, ${minutes} minutes, ${remainingSeconds} seconds`;
    } 
}    
const server = new Server('127.0.0.1', 6697, 'kerimov');
//const server = new Server('irc.azirc.net', 6900, 'kerimov');
server.on('connected', () => {
    setInterval(() => {
        const currentTime = Math.floor(new Date().getTime() / 1000);
        SendApi('user_online', {}, function (api) {
            api.data.forEach(element => {
                const user_name = element.email.split("@")[0].replace(/\./g, '_');
                //const expiryTime = server.UserList[user_name]?.expiry || element.expiry;
                const expiryTime = element.expiry;
                const timeDifference = expiryTime - currentTime;
                if (server.UserList.hasOwnProperty(user_name)) {
                    server.UserList[user_name].expiry = element.expiry;
                } else {
                    if (timeDifference > 3600) {
                        server.joinChannelWithUser(user_name, element.user_id, '#chat', element.email);
                        server.UserList[user_name].expiry = element.expiry;
                    }
                }
            })
        });
        Object.keys(server.UserList).forEach(user_name => {
            const expiryTime = server.UserList[user_name].expiry;
            const timeDifference = expiryTime - currentTime;
            if (timeDifference < 3600) {
                //console.log(server.UserList[user_name].uid + " => " + user_name + " => " + server.formatTime(timeDifference) + " has expired. ");
                server.S2S(":" + server.UserList[user_name].uid + " QUIT :" + server.formatTime(timeDifference) + " has expired. ");
                delete server.UserList[user_name];
            }
        });
    }, 30000);
});
 
function sendApiAsync(action, user) {
    return new Promise((resolve, reject) => {
        SendApi(action, user, function(api) {
            if(api.status === "success") {
                resolve(api);
            } else {
                reject(new Error('API call failed'));
            }
        });
    });
}
server.on('user', async (user) => {
    try {
        //const api = await sendApiAsync('check_irc_user', user);

        // API başarıyla döndüğünde yapılacak işlemler
        // Örnek olarak, aşağıdaki yorum satırını kullanabilirsiniz:
       //server.sendRaw("sajoin " + api.data.nick + " #chat");

        // Diğer yorum satırlarını da benzer şekilde aktifleştirebilirsiniz
        // Örnek:
        // server.S2S(":" + server.sUID + " NOTICE "+api.data.UID+" Welcome to AzIRC, "+api.data.nick+"!");        
        //server.SVSLog("Connected: " + api.data.nick + " ("+api.data.ip+") " + " is connecting from " + api.data.country_name+" / " +api.data.city_name ); 
    } catch (error) {
        // Hata oluştuğunda burası çalışacak
        console.error('Error:', error);
    }
});



app.get("/", function (req, res) {
    console.log(server.aUsers);
    res.json({});
});

http.listen(3001, function () {
    console.log("listening on *:3001");
});
Editor is loading...
Leave a Comment