projeto-hit/backend/src/helpers/InternetConnection.ts

69 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-01-01 23:40:00 +00:00
const fsPromises = require("fs/promises");
const fs = require('fs')
const checkInternetConnected = require('check-internet-connected');
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { Client } from "whatsapp-web.js";
import { splitDateTime } from "../helpers/SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import dir from 'path';
import { getIO } from "../libs/socket";
import { number } from "yup";
const internetConnection = async (whatasappId?: string | number) => {
checkInternetConnected().then((result: any) => {
console.log('Internet successfully connected to a server: ', result);//successfully connected to a server
}).catch((ex: any) => {
console.log('Intenet connection cannot connect to a server or error occurred: ', ex); // cannot connect to a server or error occurred.
});
const config = {
timeout: 5000, //timeout connecting to each server, each try
retries: 5,//number of retries to do before failing
domain: 'https://apple.com',//the domain to check DNS record of
}
let internet_status:any = null
try {
internet_status = await checkInternetConnected(config);
} catch (error) {
console.log('Erron when trying get internet connection info: ', error)
}
console.log('INTERNET STATUS: ', internet_status)
if (whatasappId && !internet_status) {
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let timestamp = Math.floor(Date.now() / 1000)
const sourcePath = dir.join(process.cwd(), '.wwebjs_auth', 'sessions', 'log');
fs.writeFileSync(`${sourcePath}/${timestamp}_internet_connection_lost.txt`, `Date: ${dateToday.fullDate} ${dateToday.fullTime}`, (error: any) => { console.log(error) });
let whats = await ShowWhatsAppService(whatasappId)
await whats.update({ status: "OPENING" });
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whats
});
}
return internet_status
}
export default internetConnection;