"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var baileys_1 = __importStar(require("@adiwajshing/baileys"));
var http = require("http");
var https = require("https");
var qrcode = require('qrcode');
var fs = require("fs");
var _a = require('express-validator'), body = _a.body, validationResult = _a.validationResult;
var express = require('express');
var axios = require("axios");
var app = express();
var server = http.createServer(app);
var socketIO = require('socket.io');
var phoneNumberFormatter = require('./helper/formatter').phoneNumberFormatter;
var io = socketIO(server, {
    cors: {
        origin: [
            'https://megamurahkasur.com'
            

        ]
    }
});
// koneksi database
//const mysql = require('mysql');
var request = require('request');
var json = require("express").json;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
var cron = require('node-cron');
//konfigurasi koneksi
/*
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'jadisend_wa'
});
 
//connect ke database
db.connect((err) =>{
  if(err) throw err;
  console.log('Mysql Connected...');
});
*/
var configs = {
    port: 3000,
    url_callback: 'https://wa.megamurahkasur.com/helper/callback.php'
};
// cronjob
/*
cron.schedule('* * * * *',  function() {
  console.log('cronjob berjalan')
 // console.log('ada init')
  const savedSessions = getSessionsFile();


      savedSessions.forEach(sess => {
          if(sess.ready == true){
console.log(sess.id)
              createSession(sess.id);
          }
      });
});
*/
// start a connection
var startSock = function () { return __awaiter(void 0, void 0, void 0, function () {
    var version, sessions, SESSIONS_FILE, createSessionsFileIfNotExists, setSessionsFile, getSessionsFile, createSession, setMime;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4 /*yield*/, (0, baileys_1.fetchLatestBaileysVersion)()];
            case 1:
                version = (_a.sent()).version;
                sessions = [];
                SESSIONS_FILE = './whatsapp-sessions.json';
                createSessionsFileIfNotExists = function () {
                    if (!fs.existsSync(SESSIONS_FILE)) {
                        try {
                            fs.writeFileSync(SESSIONS_FILE, JSON.stringify([{ "id": 0, "ready": false }]));
                            console.log('Sessions file created successfully.');
                        }
                        catch (err) {
                            console.log('Failed to create sessions file: ', err);
                        }
                    }
                };
                createSessionsFileIfNotExists();
                setSessionsFile = function (sessions) {
                    if (sessions === void 0) { sessions = [{ "id": 0, "ready": false }]; }
                    fs.writeFile(SESSIONS_FILE, JSON.stringify(sessions), function (err) {
                        if (err) {
                            console.log(err);
                        }
                    });
                };
                getSessionsFile = function () {
                    createSessionsFileIfNotExists();
                    var jsdata = fs.readFileSync(SESSIONS_FILE, 'utf8');
                    console.log(jsdata);
                    if (jsdata != "") {
                        return JSON.parse(jsdata);
                    }
                    else {
                        setSessionsFile();
                    }
                };
                createSession = function (numberid) {
                    console.log('Creating session: ' + numberid);
                    var SESSION_FILE_PATH = "./wasap-".concat(numberid, ".json");
                    /*
                    fs.stat(SESSION_FILE_PATH, (err:boolean=true, stat:any) => {
                        if(err == null){
                            fs.unlinkSync(SESSION_FILE_PATH);
                        }
                    })
                    */
                    //if (fs.existsSync(SESSION_FILE_PATH)) {
                    var _a = (0, baileys_1.useSingleFileAuthState)(SESSION_FILE_PATH), state = _a.state, saveState = _a.saveState;
                    var conn = (0, baileys_1.default)({
                        version: version,
                        auth: state,
                        printQRInTerminal: true,
                        connectTimeoutMs: 60000
                    });
                    conn.ev.on('creds.update', saveState);
                    conn.ev.on('connection.update', function (update) {
                        var _a, _b;
                        var connection = update.connection, lastDisconnect = update.lastDisconnect, qr = update.qr;
                        if (qr !== undefined) {
                            console.log('QR RECEIVED', qr);
                            qrcode.toDataURL(qr, function (err, url) {
                                io.emit('qr', { id: numberid, src: url });
                                io.emit('message', { id: numberid, text: 'QR Code received, scan please!' });
                            });
                            //conn.removeAllListeners('qr');
                        }
                        ;
                        //conn.connect(); 
                        // conn.on('initial-data-received',function(){
                        //     console.log('aaaaaaaaaaa')
                        // })
                        if (connection == 'open') {
                            io.emit('ready', { id: numberid });
                            io.emit('message', { id: numberid, text: 'Whatsapp is ready!' });
                            io.emit('authenticated', { id: numberid, data: conn.user });
                            /*
                            const savedSessions = getSessionsFile();
                            const sessionIndex = savedSessions.findIndex((sess:any) => sess.id == id);
                            savedSessions[sessionIndex].ready = true;
                            setSessionsFile(savedSessions);
                            const session = conn.base64EncodedAuthInfo()
                            fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
                                if (err) {
                                    console.error(err);
                                }
                            });
                            */
                        }
                        else {
                            if (qr !== undefined) {
                                console.log('QR RECEIVED', qr);
                                qrcode.toDataURL(qr, function (err, url) {
                                    io.emit('qr', { id: numberid, src: url });
                                    io.emit('message', { id: numberid, text: 'QR Code received, scan please!' });
                                });
                                //conn.removeAllListeners('qr');
                            }
                            ;
                        }
                        ;
                        // conn.on('initial-data-received',function(){
                        //     console.log('sfdsf');
                        // })
                        if (connection == 'close') {
                            // reconnect if not logged out
                            if (lastDisconnect !== undefined) {
                                if (!([baileys_1.DisconnectReason.loggedOut, baileys_1.DisconnectReason.connectionClosed].includes((_b = (_a = lastDisconnect.error) === null || _a === void 0 ? void 0 : _a.output) === null || _b === void 0 ? void 0 : _b.statusCode))) {
                                    createSession(numberid);
                                }
                                else {
                                    console.log('connection closed');
                                    var nomor = numberid;
                                    console.log(nomor);
                                    if (fs.existsSync("./wasap-".concat(nomor, ".json"))) {
                                        fs.unlinkSync("./wasap-".concat(nomor, ".json"));
                                        io.emit('close', { id: nomor, text: 'Connection Lost..' });
                                        /*
                                                const savedSessions = getSessionsFile();
                                                const sessionIndex = savedSessions.findIndex((sess:any) => sess.id == nomor);
                                                savedSessions[sessionIndex].ready = false;
                                                setSessionsFile(savedSessions);
                                        */
                                    }
                                }
                            }
                            //const nomors =  phoneNumberFormatter(id);
                        }
                        // Menambahkan session ke file
                        // Tambahkan client ke sessions
                        /*
                        sessions.push({
                            id: id,
                        });
                        // Menambahkan session ke file
                        const savedSessions = getSessionsFile();
                        const sessionIndex = savedSessions.findIndex((sess:any) => sess.id == id);
        
                        if (sessionIndex == -1) {
                            savedSessions.push({
                                id: id,
                                ready: false,
                            });
                            setSessionsFile(savedSessions);
                        }
                        */
                        /*
                        conn.ev.on('creds.update', async () => {
                            request({ url: configs.url_callback, method: "POST", json: {"id" : conn.user.jid ,"data" : conn.contacts} })
                        })
        
                        // chat masuk
                        conn.on('chat-update', async chat => {
                            if (chat.presences) { // receive presence updates -- composing, available, etc.
                                Object.values(chat.presences).forEach(presence => console.log(`${presence.name}'s presence is ${presence.lastKnownPresence} in ${chat.jid}`))
                            }
                            if (chat.imgUrl) {
                                console.log('imgUrl of chat changed ', chat.imgUrl)
                                return
                            }
                            // only do something when a new message is received
                            if (!chat.hasNewMessage) {
                                if (chat.messages) {
                                    console.log('updated message: ', chat.messages.first)
                                }
                                return
                            }
        
                            const m = chat.messages.all()[0] // pull the new message from the update
                            const messageStubType = WA_MESSAGE_STUB_TYPES[m.messageStubType] || 'MESSAGE'
                            console.log('got notification of type: ' + messageStubType)
        
                            const messageContent = m.message
                            // if it is not a regular text or media message
                            if (!messageContent) return
        
                            if (m.key.fromMe) {
                                console.log('relayed my own message')
                                return
                            }
                            let sender = m.key.remoteJid
                            
                            const messageType = Object.keys(messageContent)[0] // message will always contain one key signifying what kind of message
                            if (messageType === MessageType.text) {
                                const text = m.message.conversation
                                ///////////untuk auto reply via web
                            const nomor =  phoneNumberFormatter(conn.user.jid);
                            const nomorsaya = nomor.replace(/\D/g, '');
                            let sql = `SELECT * FROM autoreply WHERE keyword = "${text}" `;
                            db.query(sql, function (err, result) {
                                if (err) throw err;
                                // jika di database ada keyword dan nomor sesuai pesan, maka buat auto replyy
                                result.forEach(data => {
                                    if(data.nomor == nomorsaya){
                                        // ini untuk auto chat , jika tidak ada gambar
                                        console.log(data.media);
                                            if(data.media == ''){
                                                conn.sendMessage(sender, data.response, MessageType.text);
                                            } else {
                                                // fungsi mengambil buffer dari url
                                                const getBuffer = async (url, options) => {
                                                    try {
                                                        options ? options : {}
                                                        const res = await axios({
                                                            method: "get",
                                                            url,
                                                            ...options,
                                                            responseType: 'arraybuffer'
                                                        })
                                                        return res.data
                                                    } catch (e) {
                                                        console.log(`Error : ${e}`)
                                                    }
                                                }
                                                //////
        
                                                var media = `${data.media}`;
                                            
                                            const array = media.split(".");
                                            const ext = array[array.length - 1];
                                            console.log(ext);
                                                if(ext == 'jpg'){
                                                    // kirim media
                                                    async function sendmedia(){
                                                        var messageOptions = {
                                                            caption: data.response
                                                        };
                                                        const buffer =  await getBuffer(media)
                                                    
                                                        conn.sendMessage(sender, buffer, MessageType.image, messageOptions)
                                                    }
                                                    sendmedia();
                                                
                                                }
                                            }
                                    
                                    }  else {
                                        console.log('bukan nomormu')
                                    }
                            });
                            /////////////////////////////
                                //////////////////////////////////////////////////////////
                                // untuk webhook
        
                                let sql = `SELECT link_webhook FROM device WHERE nomor = ${nomorsaya} `;
                                db.query(sql, function (err, result) {
                                    if (err) throw err;
                                    console.log(result)
                                    const webhookurl = result[0].link_webhook;
                                    const pesan = {
                                        sender: phoneNumberFormatter(sender),
                                        msg: text
                                    }
                                    var senddd = kirimwebhook(sender, text, m,conn,webhookurl);
                                });
                            });
                            ///////////////////////////////////////////////////////////
                            } else if (messageType === MessageType.extendedText) {
                                const text = m.message.extendedTextMessage.text
                                console.log(sender + ' sent: ' + text + ' and quoted message: ' + JSON.stringify(m.message))
                                var senddd = kirimwebhook(sender, text, m);
                            } else if (messageType === MessageType.contact) {
                                const contact = m.message.contactMessage
                                console.log(sender + ' sent contact (' + contact.displayName + '): ' + contact.vcard)
                            } else if (messageType === MessageType.location || messageType === MessageType.liveLocation) {
        
                                console.log(`${sender} sent location (lat: ${locMessage.degreesLatitude}, long: ${locMessage.degreesLongitude})`)
        
                                await conn.downloadAndSaveMediaMessage(m, './Media/media_loc_thumb_in_' + m.key.id) // save location thumbnail
        
                                if (messageType === MessageType.liveLocation) {
                                    console.log(`${sender} sent live location for duration: ${m.duration / 60}`)
                                }
                            } else {
                                // if it is a media (audio, image, video, sticker) message
                                // decode, decrypt & save the media.
                                // The extension to the is applied automatically based on the media type
                                try {
                                    const savedFile = await conn.downloadAndSaveMediaMessage(m, './Media/media_in_' + m.key.id)
                                    console.log(sender + ' sent media, saved at: ' + savedFile)
                                } catch (err) {
                                    console.log('error in decoding message: ' + err)
                                }
                            }
                            })
                        */
                    });
                    //}
                };
                //init
                /*
                const init = function () {
                    console.log('ada init')
                    const savedSessions = getSessionsFile();
                
                    savedSessions.forEach((sess:any) => {
                        if(sess.ready == true){
                            console.log(sess.id)
                            createSession(sess.id);
                        }
                    });
                }
                
                init();
                */
                // koneksi socket
                io.on('connection', function (socket) {
                    //init();
                    // membuat session
                    socket.on('create-session', function (data) {
                        console.log(data);
                        console.log('Create session: ' + data.id);
                        createSession(data.id);
                    });
                    //
                    // ini baris untuk logout
                    socket.on('logout', function (data) {
                        return __awaiter(this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                if (fs.existsSync("./wasap-".concat(data.id, ".json"))) {
                                    socket.emit('isdelete', { id: data.id, text: '<h2 class="text-center text-info mt-4">Logout Success, Lets Scan Again<h2>' });
                                    fs.unlinkSync("./wasap-".concat(data.id, ".json"));
                                    //const client = await mkZap(data.id);
                                    //client.logout()
                                    //client.clearAuthInfo()
                                    //const savedSessions = getSessionsFile();
                                    //const sessionIndex = savedSessions.findIndex((sess:any) => sess.id == data.id);
                                    //savedSessions[sessionIndex].ready = false;
                                    //setSessionsFile(savedSessions);
                                    //setSessionsFile(savedSessions);
                                }
                                else {
                                    socket.emit('isdelete', { id: data.id, text: '<h2 class="text-center text-danger mt-4">You are have not Login yet!<h2>' });
                                }
                                return [2 /*return*/];
                            });
                        });
                    });
                    // 
                });
                setMime = function (type) {
                    var messageType = 'document', mimeType;
                    switch (type) {
                        case 'mp3':
                            messageType = 'audio';
                            mimeType = 'audio/mp4';
                            break;
                        case 'mp4':
                            messageType = 'video';
                            mimeType = 'audio/mp4';
                            break;
                        case 'gif':
                            messageType = 'video';
                            mimeType = 'audio/mp4';
                            break;
                        case 'png':
                            messageType = 'image';
                            mimeType = 'image/png';
                            break;
                        case 'jpg':
                        case 'jpeg':
                            messageType = 'image';
                            mimeType = 'image/jpeg';
                            break;
                        case 'webp':
                            messageType = 'sticker';
                            mimeType = 'image/webp';
                            break;
                        case 'pdf':
                            mimeType = 'application/pdf';
                            break;
                        case 'xls':
                            mimeType = 'application/excel';
                            break;
                        case 'xlsx':
                            mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                            break;
                        case 'docx':
                            mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                            break;
                        case 'zip':
                            mimeType = 'application/zip';
                            break;
                        case 'doc':
                            mimeType = 'application/msword';
                            break;
                        default:
                            messageType = 'document';
                    }
                    return {
                        messageType: messageType,
                        mimeType: mimeType
                    };
                };
                // Send message
                app.post('/send-message', function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
                    var sender, _a, state, saveState, client_1, message_1, number, number, error_1;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                sender = req.body.sender;
                                if (!fs.existsSync("./wasap-".concat(sender, ".json"))) return [3 /*break*/, 5];
                                _a = (0, baileys_1.useSingleFileAuthState)("./wasap-".concat(sender, ".json")), state = _a.state, saveState = _a.saveState;
                                client_1 = (0, baileys_1.default)({
                                    version: version,
                                    auth: state,
                                    printQRInTerminal: false,
                                    connectTimeoutMs: 60000
                                });
                                //conn.browserDescription = ['Windows', 'Chrome', '60.0.3112.113'];
                                client_1.ev.on('creds.update', saveState);
                                message_1 = req.body.message;
                                if (req.body.number.length > 15) {
                                    number = req.body.number;
                                }
                                else {
                                    number = phoneNumberFormatter(req.body.number);
                                    /*const [numberExists] = await client.onWhatsApp(req.body.number);
                                    if (!numberExists.exists){
                                        return res.status(422).json({
                                            status: false,
                                            message: 'The number is not registered'
                                        });
                                    }*/
                                }
                                _b.label = 1;
                            case 1:
                                _b.trys.push([1, 3, , 4]);
                                return [4 /*yield*/, client_1.ev.on('connection.update', function (update) { return __awaiter(void 0, void 0, void 0, function () {
                                        var connection, lastDisconnect, sent, error_2;
                                        return __generator(this, function (_a) {
                                            switch (_a.label) {
                                                case 0:
                                                    connection = update.connection, lastDisconnect = update.lastDisconnect;
                                                    if (!(connection == 'open')) return [3 /*break*/, 5];
                                                    _a.label = 1;
                                                case 1:
                                                    _a.trys.push([1, 3, , 4]);
                                                    return [4 /*yield*/, client_1.sendMessage(number, { text: message_1 })];
                                                case 2:
                                                    sent = _a.sent();
                                                    res.status(200).json({
                                                        status: true,
                                                        response: sent
                                                    });
                                                    return [2 /*return*/];
                                                case 3:
                                                    error_2 = _a.sent();
                                                    res.status(500).json({
                                                        status: false,
                                                        response: "Gagal mengirim"
                                                    });
                                                    return [2 /*return*/];
                                                case 4:
                                                    ;
                                                    return [3 /*break*/, 6];
                                                case 5:
                                                    console.log('connection closed');
                                                    _a.label = 6;
                                                case 6: return [2 /*return*/];
                                            }
                                        });
                                    }); })];
                            case 2:
                                _b.sent();
                                return [3 /*break*/, 4];
                            case 3:
                                error_1 = _b.sent();
                                console.log(error_1);
                                res.status(401).json({
                                    status: false,
                                    response: 'Please scan the QR before use the API 2'
                                });
                                return [2 /*return*/];
                            case 4: return [3 /*break*/, 6];
                            case 5:
                                res.status(401).json({
                                    status: false,
                                    response: 'Please scan the QR before use the API 2'
                                });
                                return [2 /*return*/];
                            case 6: return [2 /*return*/];
                        }
                    });
                }); });
                // send media
                app.post('/send-media', function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
                    var sender, _a, state, saveState, client_2, url_1, _b, messageType_1, mimeType_1, filename_1, caption_1, number, number;
                    return __generator(this, function (_c) {
                        sender = req.body.sender;
                        if (fs.existsSync("./wasap-".concat(sender, ".json"))) {
                            _a = (0, baileys_1.useSingleFileAuthState)("./wasap-".concat(sender, ".json")), state = _a.state, saveState = _a.saveState;
                            client_2 = (0, baileys_1.default)({
                                version: version,
                                auth: state,
                                printQRInTerminal: false,
                                connectTimeoutMs: 60000,
                                //browser: ['Windows', 'Chrome', '60.0.3112.113']
                            });
                            //conn.browserDescription = ['Windows', 'Chrome', '60.0.3112.113'];
                            client_2.ev.on('creds.update', saveState);
                            url_1 = req.body.url;
                            _b = setMime(req.body.filetype), messageType_1 = _b.messageType, mimeType_1 = _b.mimeType;
                            filename_1 = req.body.filename;
                            caption_1 = req.body.caption;
                            console.log("source: " + req.body.filetype + " => mestype: " + messageType_1 + " | mime:" + mimeType_1);
                            console.log(req.body);
                            //  var number = phoneNumberFormatter(req.body.number);
                            //  const message = req.body.message;
                            if (req.body.number.length > 15) {
                                number = req.body.number;
                            }
                            else {
                                number = phoneNumberFormatter(req.body.number);
                                /*const [numberExists] = await client.onWhatsApp(req.body.number);
                                if (!numberExists.exists){
                                    return res.status(422).json({
                                        status: false,
                                        message: 'The number is not registered'
                                    });
                                }*/
                            }
                            try {
                                client_2.ev.on('connection.update', function (update) { return __awaiter(void 0, void 0, void 0, function () {
                                    var connection, lastDisconnect, buffer, sendMedia, sent, sendMedia, sent, sendMedia, sent;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                connection = update.connection, lastDisconnect = update.lastDisconnect;
                                                buffer = url_1;
                                                if (!(connection == 'open')) return [3 /*break*/, 8];
                                                if (!(messageType_1 == 'video')) return [3 /*break*/, 2];
                                                sendMedia = {
                                                    video: { url: buffer },
                                                    caption: caption_1,
                                                    mimetype: mimeType_1,
                                                    fileName: filename_1
                                                };
                                                return [4 /*yield*/, client_2.sendMessage(number, sendMedia)];
                                            case 1:
                                                sent = _a.sent();
                                                return [2 /*return*/, res.status(200).json({
                                                        status: true,
                                                        response: sent
                                                    })];
                                            case 2:
                                                if (!(messageType_1 == 'image')) return [3 /*break*/, 4];
                                                sendMedia = {
                                                    image: { url: buffer },
                                                    caption: caption_1,
                                                    mimetype: mimeType_1,
                                                    fileName: filename_1
                                                };
                                                return [4 /*yield*/, client_2.sendMessage(number, sendMedia)];
                                            case 3:
                                                sent = _a.sent();
                                                return [2 /*return*/, res.status(200).json({
                                                        status: true,
                                                        response: sent
                                                    })];
                                            case 4:
                                                if (!(messageType_1 == 'sticker')) return [3 /*break*/, 6];
                                                sendMedia = {
                                                    sticker: { url: buffer },
                                                    caption: caption_1,
                                                    mimetype: mimeType_1,
                                                    fileName: filename_1
                                                };
                                                return [4 /*yield*/, client_2.sendMessage(number, sendMedia)];
                                            case 5:
                                                sent = _a.sent();
                                                return [2 /*return*/, res.status(200).json({
                                                        status: true,
                                                        response: sent
                                                    })];
                                            case 6: return [2 /*return*/, res.status(500).json({
                                                    status: false,
                                                    response: 'Filetype tidak dikenal'
                                                })];
                                            case 7: return [3 /*break*/, 9];
                                            case 8:
                                                console.log('connection closed');
                                                _a.label = 9;
                                            case 9: return [2 /*return*/];
                                        }
                                    });
                                }); });
                            }
                            catch (error) {
                                console.log(error);
                                return [2 /*return*/, res.status(401).json({
                                        status: false,
                                        response: 'Please scan the QR before use the API 2'
                                    })];
                            }
                        }
                        else {
                            return [2 /*return*/, res.status(401).json({
                                    status: false,
                                    response: 'Please scan the QR before use the API 2'
                                })];
                        }
                        return [2 /*return*/];
                    });
                }); });
                // server running
                app.get('/', function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        res.writeHead(200, {
                            'Content-Type': 'application/json'
                        });
                        res.end(JSON.stringify({
                            status: true,
                            service_code: 200,
                            message: 'Server is Running...'
                        }));
                        return [2 /*return*/];
                    });
                }); });
                //function kebutuhan webhook
                /*
                function kirimwebhook(sender, message, m ,conn,link) {
                
                    var webhook_response = {
                        from: phoneNumberFormatter(sender),
                        message: message
                    }
                    const getBuffer = async (url, options) => {
                        try {
                            options ? options : {}
                            const res = await axios({
                                method: "get",
                                url,
                                ...options,
                                responseType: 'arraybuffer'
                            })
                            return res.data
                        } catch (e) {
                            console.log(`Error : ${e}`)
                        }
                    }
            
                    request({ url: link, method: "POST", json: webhook_response },
                        async function (error, response) {
                            if (!error && response.statusCode == 200) {
                                // process hook
                                if (response.body == null) {
                                    return 'gagal send webhook';
                                }
                                const res = response.body;
                                console.log(res);
                                if (res.mode == 'chat') {
                                    conn.sendMessage(sender, res.pesan, MessageType.text)
                                } else if (res.mode == 'reply') {
                                    conn.sendMessage(sender, res.pesan, MessageType.extendedText, { quoted: m })
                                } else if (res.mode == 'picture') {
                                    const url = res.data.url;
                                    const caption = res.data.caption;
                                    var messageOptions = {};
                                    const buffer = await getBuffer(url);
                                    if (caption != '') messageOptions.caption = caption;
                                    conn.sendMessage(sender, buffer, MessageType.image, messageOptions);
                                }
                            } else { console.log('error'); }
                        }
                    );
                }
                */
                server.listen(configs.port, function () {
                    console.log('App running on *: ' + configs.port);
                });
                return [2 /*return*/];
        }
    });
}); };
startSock();
