Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
33 kB
2
Indexable
Never
var rimraf = require("rimraf");
const https = require('https');
const qrcode = require('qrcode-terminal');
const fetch = require('node-fetch');
var QRCode = require('qrcode');
var Jimp = require('jimp');
const { pad, toCRC16, dataQris } = require('../../src/Qris.js');
var fs = require('fs'),
request = require('request');
const {
    Client,
    LegacySessionAuth,
    Location,
    List,
    Buttons
} = require('./../../index');
let sessions = {};


const sleep = (milliseconds) => {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
  };

  

function formatRupiah(angka, prefix){
    var number_string = angka.replace(/[^,\d]/g, '').toString(),
    split   		= number_string.split(','),
    sisa     		= split[0].length % 3,
    rupiah     		= split[0].substr(0, sisa),
    ribuan     		= split[0].substr(sisa).match(/\d{3}/gi);

    // tambahkan titik jika yang di input sudah menjadi angka ribuan
    if(ribuan){
        separator = sisa ? '.' : '';
        rupiah += separator + ribuan.join('.');
    }

    rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
    return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
function formatNumber(num) {
    return (num.toFixed(0).replace('.', ',').replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.'))
}

function generateQris(mid, merchantName, nominal, fileName){
    let tax = '';
    //isi data qris
    let qris = "00020101021126570011ID.DANA.WWW011893600915305112759002090511275900303UMI51440014ID.CO.QRIS.WWW0215ID"+mid+"0303UMI5204561153033605802ID5913"+merchantName+"6013Kab. Magelang6105564846304C7D1";
    //isi nominal
    // let nominal = "5000";
    //pajak (opsional)
    //jenis pajak
    let taxtype = 'p' // r/p, r = rupiah, p = persen
    //nominal pajak
    let fee = "10" //contoh persen 10%
    
    let qris2 = qris.slice(0, -4);
    let replaceQris = qris2.replace("010211", "010212");
    let pecahQris = replaceQris.split("5802ID");
    let uang = "54" + pad(nominal.length) + nominal;
    tax = (taxtype == 'p') ? "55020357" + pad(fee.length) + fee : "55020256" + pad(fee.length) + fee;
    uang += (tax.length == 0) ? "5802ID" : tax + "5802ID";
    
    let output = pecahQris[0].trim() + uang + pecahQris[1].trim();
    output += toCRC16(output);
    console.log(output) //output
    // let fileName = Math.floor(Date.now()/1000);
    
    //make output file image
    QRCode.toFile('tmp.png', output, { margin: 2, scale: 10 }, async function (err, url) {
        
        let data = dataQris(qris);
        var text = data.merchantName;
        var qr = await Jimp.read('tmp.png');
        Jimp.read('assets/template.png', (err, image) => {
            if (err) console.log(err);
            var w = image.bitmap.width
            var h = image.bitmap.height
            Jimp.loadFont((text.length > 18) ? 'assets/font/BebasNeueSedang/BebasNeue-Regular.ttf.fnt' : 'assets/font/BebasNeue/BebasNeue-Regular.ttf.fnt').then(fonttitle => {
                Jimp.loadFont((text.length > 28) ? 'assets/font/RobotoSedang/Roboto-Regular.ttf.fnt' : 'assets/font/RobotoBesar/Roboto-Regular.ttf.fnt').then(fontnmid => {
                    Jimp.loadFont('assets/font/RobotoKecil/Roboto-Regular.ttf.fnt').then(fontcetak => {
                        image
                            .composite(qr, w / 4 - 30, h / 4 + 68)
                            .print(fonttitle, w / 5 - 30, h / 5 + 68, { text: text, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? -180 : -210)
                            .print(fontnmid, w / 5 - 30, h / 5 + 68, { text: `NMID : ${data.nmid}`, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? +20 : -45)
                            .print(fontnmid, w / 5 - 30, h / 5 + 68, { text: data.id, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? +110 : +90)
                            .print(fontcetak, w / 20, 1205, `Dicetak oleh: Bank Rakyat Indonesia`)
                            .write(`output/qr.jpg`);
                        fs.unlinkSync('tmp.png')
                    })
                })
            });
        });
    });
    
}
var download = function(uri, filename, callback) {
    try {
        var acceptExt = ["png", "jpg", "jpeg", "pdf", "mp3", "mp4", "docx", "mp4"];
        var extension = uri.split('.').pop();
        console.log(extension);
        var extCheck = acceptExt.includes(extension);
        if (extCheck) {
            request.head(uri, function(err, res, body) {
                request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
            });
        } else {
            throw new Error("media not approve");
        }

        // let file = "https://admin.sliovg.com/file/video/Video%20Greeting%20Template/Video-Haji-Umrah-2.mp4";

        // let mimetype;
        // let filename;
        // const attachment = await axios.get(file, {
        // responseType: 'arraybuffer'
        // }).then(response => {
        // mimetype = response.headers['content-type'];
        // filename = file.split("/").pop();
        // return response.data.toString('base64');
        // });

        // if( attachment ){
        // const media = new MessageMedia(mimetype, attachment, filename);
        // }

    } catch (err) {
        res.status(400).json({
            'status': 'ERROR',
            'messages': err.message
        })
    }
    
};

function sendapi(data, path) {
    console.log("sendapi "+data+" path: "+path);
    fetch('http://209.97.173.148' + path, {
        method: 'post',
        body: data,
        headers: {
            'Content-Type': 'application/json'
        },
    }).then(res => res.text()).then(text => console.log(text));
}

function setclient(number) {
    let sessionCfg;
    const SESSION_FILE_PATH = __dirname + '/../../sessions/' + number + '.json';
    if (fs.existsSync(SESSION_FILE_PATH)) {
        sessionCfg = require(SESSION_FILE_PATH);
    }
    sessions[number] = new Client({
        puppeteer: {
            // executablePath: '/usr/bin/google-chrome-stable',
            headless: true,
            qrTimeoutMs: 0,
            userDataDir: __dirname + '/../../sessions/' + number,
            args: [
            '--no-sandbox',
            '--disable-cache',
            '--disable-application-cache',
            '--media-cache-size=0',
            '--disk-cache-size=0',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-accelerated-2d-canvas',
            '--no-first-run',
            '--no-zygote',
            '--disable-gpu'
            ]
        },
        // session: sessionCfg
        authStrategy: new LegacySessionAuth({
            session: sessionCfg
        })
    });
    sessions[number].initialize();
    // console.log("session after initialize "+JSON.stringify(sessions));
    let qr_reload = 1;
    sessions[number].on('qr', qr => {
        console.log("qr_reload "+qr_reload);
        if (qr_reload > 10) {
            const data = JSON.stringify({
                apikey: 'we4567talk',
                client: number
            });
            sendapi(data, '/apiv2/qr_timeout');
            sessions[number].destroy();
            rimraf(__dirname + '/../../sessions/' + number, function () { console.log(number + " removed"); });
            // process.exit();
        }else{
            qrcode.generate(qr, {
                small: true
            });
            const data = JSON.stringify({
                apikey: 'we4567talk',
                qr: qr,
                client: number
            });
            sendapi(data, '/apiv2/get_qr');
        }
        qr_reload++;
    });
    // console.log("session after qr "+JSON.stringify(sessions));



    sessions[number].on('ready', async () => {
        console.log(number + ' is ready!');
        const infoClient = sessions[number].info;
        const infoBusiness = await sessions[number].getContactById(infoClient.me._serialized);
        const data = JSON.stringify({
            apikey: 'we4567talk',
            client: number,
            client_info: infoClient,
            is_business: infoBusiness.isBusiness ? 1 : 0
        });
        // console.log(data)
        sendapi(data, '/apiv2/update_config');
    });
    // console.log("session after ready "+JSON.stringify(sessions));
    sessions[number].on('disconnected', (reason) => {
        console.log(reason);
        fs.unlinkSync(SESSION_FILE_PATH);
        sessions[number].destroy();
        rimraf(__dirname + '/../../sessions/' + number, function () { console.log("dir removed"); });
        const data = JSON.stringify({
            apikey: 'we4567talk',
            scan: 'on',
            client: number
        });
        sendapi(data, '/apiv2/update_config_scan');
    });
    sessions[number].on('authenticated', (session) => {
        console.log('AUTHENTICATED', session);
        sessionCfg = session;
        fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function(err) {
            if (err) {
                console.error(err);
            }
        });

        const data = JSON.stringify({
            apikey: 'we4567talk',
            scan: 'off',
            client: number
        });
        sendapi(data, '/apiv2/update_config_scan');
    });

    // console.log("session after auth "+JSON.stringify(sessions));
    sessions[number].on('message', async msg => {
        console.log("on message");
        var row = null;
        var b64 = null;
        var related_message_id = null;
        // console.log("msg.to "+msg.to);
        console.log("msg "+JSON.stringify(msg));
        const infoBusiness = await sessions[number].getContactById(msg.to).isBusiness;
        if (msg.hasQuotedMsg) {
            const quotedMsg = await msg.getQuotedMessage();
            console.log("quotedMsg "+JSON.stringify(quotedMsg));
            console.log("quotedMsg.id "+JSON.stringify(quotedMsg.id));
            console.log("quotedMsg.id.id "+JSON.stringify(quotedMsg.id.id));
            related_message_id = quotedMsg.id.id
        }
        if (msg.hasMedia) {
            const attachmentData = await msg.downloadMedia();
            b64 = attachmentData.data;
        }
        if (msg.type === 'chat' || msg.type === 'buttons_response' || msg.type === 'list_response') {
            const info = await sessions[number].getContactById(msg.from);
            row = JSON.stringify({
                apikey: 'we4567talk',
                client: number,
                data: {
                    type: 'text',
                    message_id: msg.id.id,
                    related_message_id: related_message_id,
                    from: msg.from.slice(0, -5),
                    to: msg.to.slice(0, -5),
                    author: (msg.author) ? msg.author.slice(0, -5) : null,
                    message: msg.body,
                    customer_name: info.pushname,
                    timestamp: msg.timestamp
                }
            });
        } else if (msg.type === 'image' || msg.type === 'video' || msg.type === 'audio' || msg.type === 'document' || msg.type === 'ptt') {
            row = JSON.stringify({
                apikey: 'we4567talk',
                client: number,
                data: {
                    type: 'media',
                    message_id: msg.id.id,
                    related_message_id: related_message_id,
                    from: msg.from.slice(0, -5),
                    to: msg.to.slice(0, -5),
                    author: (msg.author) ? msg.author.slice(0, -5) : null,
                    b64: b64,
                    message: msg.body,
                    timestamp: msg.timestamp
                }
            });
        } else if (msg.type === 'location') {
            row = JSON.stringify({
                apikey: 'we4567talk',
                client: number,
                data: {
                    type: msg.type,
                    message_id: msg.id.id,
                    related_message_id: related_message_id,
                    from: msg.from.slice(0, -5),
                    to: msg.to.slice(0, -5),
                    author: (msg.author) ? msg.author.slice(0, -5) : null,
                    message: msg.body + ' ' + msg.location.description,
                    timestamp: msg.timestamp,
                    location: {
                        latitude: msg.location.latitude,
                        longitude: msg.location.longitude,
                        description: msg.location.description
                    }
                }
            });
        } else if (msg.type === 'order') {
            let data_order = await msg.getOrder();
            const info = await sessions[number].getContactById(msg.from);
            row = JSON.stringify({
                apikey: 'a4g',
                client: number,
                data: {
                    type: msg.type,
                    message_id: msg.id.id,
                    order_id: msg.orderId,
                    token: msg.token,
                    from: msg.from.slice(0, -5),
                    to: msg.to.slice(0, -5),
                    message: msg.body,
                    customer_name: info.pushname,
                    timestamp: msg.timestamp,
                    data_order: data_order
                }
            });
        }
        if (msg.type == 'order') {
            sendapi(row, '/apiv2/save_order');
        }else{
            sendapi(row, '/apiv2/save_message');
        }
    });

    sessions[number].on('message_ack', (msg, ack) => {
        var row = null;
        var status = "";
        switch (ack) {
            case -1:
                status = "Error";
                break;
            case 0:
                status = "Pending";
                break;
            case 1:
                status = "Sent";
                break;
            case 2:
                status = "Delivered";
                break;
            case 3:
                status = "Read";
                break;
            case 4:
                status = "Played";
                break;
            default:
                status = "Failed";
        }
        row = JSON.stringify({
            apikey: 'we4567talk',
            client: number,
            data: {
                message_id: msg.id.id,
                ack: ack,
                status: status,
                timestamp: msg.timestamp
            }
        });
        // console.log(ack)
        // sendapi(row, '/apiv2/status');
    });

    return sessions[number];
}


exports.kill = (req, res) => {

    // sessions[req.body.client].destroy();
    console.log("sessions "+JSON.stringify(sessions));
    console.log("kill puppeteer");
};

exports.create = async (req, res) => {
    if (!req.body) {
        res.status(400).send({
            message: "Content can not be empty!"
        });
    }
    try {
        var phone_to = false;
        var phone_check = req.body.to.length > 18 ? req.body.to + "@g.us" : req.body.to + "@c.us";
        const status_nomor = await sessions[req.body.client].isRegisteredUser(phone_check);
        console.log(status_nomor, phone_check, req.body.client);
        console.log("req.body untuk send "+JSON.stringify(req.body));
        if (status_nomor) {
            if (req.body.type == 'text') {
                phone_to = true;
                sessions[req.body.client].sendMessage(phone_check, req.body.message);
            } else if (req.body.type == 'media') {
                console.log("MEDIAAAAA");
                phone_to = true;
                let  bodyMessage = req.body.message != ""  ? req.body.message : "";
                if(bodyMessage != ""){
                    let keywordQris = bodyMessage.split(',')[0] == "qr" ? bodyMessage.split(',')[0] : "";
                    let nominal = bodyMessage.split(',')[1] != null || bodyMessage.split(',')[1] != "" || bodyMessage.split(',')[1] != 0 ? bodyMessage.split(',')[1] : 0;
                    
                  
                    
                 
                    if(keywordQris != "" && nominal > 0 ){
                        let merchantName = "";
                        let mid = "839075645763";
                        console.log(">>>>>>>>>>>> nominal "+nominal);
                        console.log(">>>>>>>>>>>> req.body.to "+req.body.to);
                        if(req.body.to == "6285780368656"){
                            merchantName = "Toko Ajib";
                        }else {
                            merchantName = "Boim Cafe";
                        }
    
                        var now = new Date();
                        // Create formatted time
                        var yyyy = now.getFullYear();
                        var mm = now.getMonth() < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1); // getMonth() is zero-based
                        var dd  = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                        var hh = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
                        var mmm  = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
                        var ss  = now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    
                        
                        var fileName = "qr_"+yyyy+mm+dd+"-"+hh+mm+ss;     // file name
                        // generateQris(mid, merchantName, nominal, fileName); 
                        


                        let tax = '';
                        //isi data qris
                        let qris = "00020101021126570011ID.DANA.WWW011893600915305112759002090511275900303UMI51440014ID.CO.QRIS.WWW0215ID"+mid+"0303UMI5204561153033605802ID5913"+merchantName+"6013Kab. Magelang6105564846304C7D1";
                        //isi nominal
                        // let nominal = "5000";
                        //pajak (opsional)
                        //jenis pajak
                        let taxtype = 'p' // r/p, r = rupiah, p = persen
                        //nominal pajak
                        let fee = "10" //contoh persen 10%
                        
                        let qris2 = qris.slice(0, -4);
                        let replaceQris = qris2.replace("010211", "010212");
                        let pecahQris = replaceQris.split("5802ID");
                        let uang = "54" + pad(nominal.length) + nominal;
                        tax = (taxtype == 'p') ? "55020357" + pad(fee.length) + fee : "55020256" + pad(fee.length) + fee;
                        uang += (tax.length == 0) ? "5802ID" : tax + "5802ID";
                        
                        let output = pecahQris[0].trim() + uang + pecahQris[1].trim();
                        output += toCRC16(output);
                        console.log(output) //output
                        // let fileName = Math.floor(Date.now()/1000);
                        
                        //make output file image
                        QRCode.toFile('tmp.png', output, { margin: 2, scale: 10 }, async function (err, url) {
                            
                            let data = dataQris(qris);
                            var text = data.merchantName;
                            var qr = await Jimp.read('tmp.png');
                            Jimp.read('assets/template.png', (err, image) => {
                                if (err) console.log(err);
                                var w = image.bitmap.width
                                var h = image.bitmap.height
                                Jimp.loadFont((text.length > 18) ? 'assets/font/BebasNeueSedang/BebasNeue-Regular.ttf.fnt' : 'assets/font/BebasNeue/BebasNeue-Regular.ttf.fnt').then(fonttitle => {
                                    Jimp.loadFont((text.length > 28) ? 'assets/font/RobotoSedang/Roboto-Regular.ttf.fnt' : 'assets/font/RobotoBesar/Roboto-Regular.ttf.fnt').then(fontnmid => {
                                        Jimp.loadFont('assets/font/RobotoKecil/Roboto-Regular.ttf.fnt').then(fontcetak => {
                                            image
                                                .composite(qr, w / 4 - 30, h / 4 + 68)
                                                .print(fonttitle, w / 5 - 30, h / 5 + 68, { text: text, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? -180 : -210)
                                                .print(fontnmid, w / 5 - 30, h / 5 + 68, { text: `NMID : ${data.nmid}`, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? +20 : -45)
                                                .print(fontnmid, w / 5 - 30, h / 5 + 68, { text: data.id, alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER, alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE, }, w / 1.5, (text.length > 28) ? +110 : +90)
                                                .print(fontcetak, w / 20, 1205, `Dicetak oleh: Bank Rakyat Indonesia`)
                                                .write(`output/qr.jpg`);

                                                sleep(5000);  
                                                const {
                                                    MessageMedia
                                                } = require('./../../index');
                                                
                                                const media = MessageMedia.fromFilePath("output/qr.jpg" );
                                                sessions[req.body.client].sendMessage(phone_check, media, {
                                                    caption: "Nominal Rupiah Qris *"+formatRupiah(nominal, 'Rp. ')+"* "
                                                });
                                            fs.unlinkSync('tmp.png')
                                        })
                                    })
                                });
                            });
                        });


                       
                    }
                }

                console.log("req.body.url "+req.body.url);
                if(req.body.url != "qris_message"){
                    var filename = req.body.url.split("/").pop();
                    download(req.body.url, 'assets/' + filename, function(err, results) {
                        if (err) {
                            res.status(400).json({
                                'status': 'ERROR',
                                'messages': "media not approved"
                            })
                            return;
                        }
                        const {
                            MessageMedia
                        } = require('./../../index');
                        
                        const media = MessageMedia.fromFilePath("assets/" + filename);
                        sessions[req.body.client].sendMessage(phone_check, media, {
                            caption: req.body.message
                        });
                    });
                }

            } else if (req.body.type == 'sticker') {
                phone_to = true;
                var filename = req.body.url.split("/").pop();
                download(req.body.url, 'assets/' + filename, function(err, results) {
                    if (err) {
                        res.status(400).json({
                            'status': 'ERROR',
                            'messages': "media not approved"
                        })
                        return;
                    }
                    const {
                        MessageMedia
                    } = require('whatsapp-web.js');
                    const sticker = MessageMedia.fromFilePath("assets/" + filename);
                    sessions[req.body.client].sendMessage(phone_check, sticker, {
                        sendMediaAsSticker: true
                    });
                });
            } else if (req.body.type == 'location') {
                phone_to = true;
                const {
                    Location
                } = require('whatsapp-web.js');
                const loc = new Location(req.body.lat, req.body.lng, req.body.description);
                sessions[req.body.client].sendMessage(phone_check, loc);
            } else if (req.body.type == 'button_1') {
                phone_to = true;


                let button1 = new Buttons(req.body.message, [{
                    body: req.body.button_1
                }], req.body.message_header, req.body.message_footer);

                
                sessions[req.body.client].sendMessage(phone_check, button1);
            } else if (req.body.type == 'button_2') {
                phone_to = true;

                let button2 = new Buttons(req.body.message, [{
                    body: req.body.button_1
                }, {
                    body: req.body.button_2
                }], req.body.message_header, req.body.message_footer);
                sessions[req.body.client].sendMessage(phone_check, button2);
            } else if (req.body.type == 'button_3') {
                phone_to = true;

                let button3 = new Buttons(req.body.message, [{
                    body: req.body.button_1
                }, {
                    body: req.body.button_2
                }, {
                    body: req.body.button_3
                }], req.body.message_header, req.body.message_footer);
                sessions[req.body.client].sendMessage(phone_check, button3);
            } else if (req.body.type == 'button_1_media') {
                phone_to = true;
                var filename = req.body.url.split("/").pop();
                download(req.body.url, 'assets/' + filename, function(err, results) {
                    if (err) {
                        res.status(400).json({
                            'status': 'ERROR',
                            'messages': "media not approved"
                        })
                        return;
                    }
                    const {
                        MessageMedia
                    } = require('./../../index');
                    let media = MessageMedia.fromFilePath("assets/" + filename);

                    let button1_media = new Buttons(media, [{
                        body: req.body.button_1
                    }], req.body.message_header, req.body.message_footer);
                    sessions[req.body.client].sendMessage(phone_check, button1_media,{'caption':req.body.message});
                });
            } else if (req.body.type == 'list') {
                phone_to = true;

                let sections2 = [{title: req.body.menu_title,rows:JSON.parse(req.body.button_list)}];
                console.log("sections2 "+JSON.stringify(sections2));
                let listt = new List(
                    req.body.message,req.body.button_name,
                    sections2,
                    req.body.message_header,
                    req.body.message_footer
                    );
                    console.log("listt "+JSON.stringify(listt));
                sessions[req.body.client].sendMessage(phone_check, listt);
            }
            sessions[req.body.client].on('message_create', async msg => {
                if (phone_to) {
                    if (req.body.to == msg.to.slice(0, -5)) {
                        res.status(200).json({
                            'status': 'ok',
                            'message_id': msg.id.id,
                            'from': msg.from.slice(0, -5),
                            'to': msg.to.slice(0, -5)
                        })
                        phone_to = false;
                    }
                }
            });
        }else{
            res.status(400).json({
                'status': 'ERROR',
                'messages': 'phone number is invalid'
            })
        }
    } catch (err) {
        res.status(400).json({
            'status': 'ERROR',
            'messages': err.message
        })
    }
};
exports.chatindex = (req, res) => {
    console.log("chatindex");
    res.writeHead(302, {
        'Location': 'https://apgi4gw.com'
    });
    res.end();
};
exports.endSession = (req, res) => {
    if (!req.body) {
        res.status(400).send({
            message: "Content can not be empty!"
        });
    }
    try {
        if (req.body.apikey == 'we1232123talk') {
            sessions[req.body.client].destroy();
            fs.unlinkSync(__dirname + '/../../sessions/' + req.body.client + '.json');
            rimraf(__dirname + '/../../sessions/' + req.body.client, function() {
                console.log("dir removed");
            });
            res.status(200).json({
                'status': 'OK',
            })
        } else {
            res.status(400).json({
                'status': 'ERROR',
                'messages': 'Invalid apikey'
            })
        }
    } catch (err) {
        res.status(400).json({
            'status': 'ERROR',
            'messages': err.message
        })
    }
};

exports.setClient = async (req, res) => {
    if (!req.body) {
        res.status(400).send({
            message: "Content can not be empty!"
        });
    }
    try {
        if (req.body.apikey == 'we1232123talk') {
            setclient(req.body.client);
            console.log('request set client: ' + req.body.client);
            res.status(200).json({
                'status': "OK",
            })
        } else {
            res.status(400).json({
                'status': 'ERROR',
                'messages': 'Invalid apikey'
            })
        }
    } catch (err) {
        res.status(400).json({
            'status': 'ERROR',
            'messages': err.message
        })
    }
};
exports.removeClient = (req, res) => {
    if (!req.body) {
        res.status(400).send({
            message: "Content can not be empty!"
        });
    }
    try {
        
        if (req.body.apikey == 'we1232123talk') {
            const SESSION_FILE_PATH = __dirname + '/../../sessions/' + req.body.client + '.json';
            if(sessions[req.body.client] != null ){
                sessions[req.body.client].destroy();
            }else { 
                console.log("test");
            } 
            fs.unlinkSync(SESSION_FILE_PATH);
            rimraf(__dirname + '/../../sessions/' + req.body.client, function () { console.log("dir removed"); });
            const data = JSON.stringify({
                apikey: 'we4567talk',
                scan: 'on',
                client: req.body.client
            });
            sendapi(data, '/apiv2/update_config_scan');
            res.status(200).json({
                'status': 'OK',
            })
        } else {
            res.status(400).json({
                'status': 'ERROR',
                'messages': 'Invalid apikey'
            })
        }
    } catch (err) {
        res.status(400).json({
            'status': 'ERROR',
            'messages': err.message
        })
    }
};
// setclient('IM3');
setclient('boot_07');
// let number = "arebi";
// let sessionCfg;
//     const SESSION_FILE_PATH = __dirname + '/../../sessions/' + number + '.json';
//     if (fs.existsSync(SESSION_FILE_PATH)) {
//         sessionCfg = require(SESSION_FILE_PATH);
//     }
//     sessions[number] = new Client({
//         puppeteer: {
//             headless: true,
//             qrTimeoutMs: 0,
//             userDataDir: __dirname + '/../../sessions/' + number,
//             args: [
//             '--no-sandbox',
//             '--disable-cache',
//             '--disable-application-cache',
//             '--media-cache-size=0',
//             '--disk-cache-size=0',
//             '--disable-setuid-sandbox',
//             '--disable-dev-shm-usage',
//             '--disable-accelerated-2d-canvas',
//             '--no-first-run',
//             '--no-zygote',
//             '--disable-gpu'
//             ]
//         },
//         session: sessionCfg
//     });
//     sessions[number].initialize();
//     console.log("session after initialize "+JSON.stringify(sessions));