-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
333 lines (298 loc) · 11.1 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '1';
process.on('uncaughtException', console.error)
import './config.js';
import path, { join } from 'path'
import { writeFileSync, readdirSync, statSync, unlinkSync, existsSync, readFileSync, copyFileSync, watch, rmSync, readdir, stat } from 'fs';
import yargs from 'yargs';
import { spawn } from 'child_process';
import chalk from 'chalk';
import { tmpdir } from 'os';
import { protoType, serialize } from './lib/simple.js';
import { plugins, filesInit, reload} from './lib/plugins.js'
import Connection from './lib/connection.js'
import Helper from './lib/helper.js'
import db, { loadDatabase } from './lib/database.js'
import { platform } from 'process'
const PORT = process.env.PORT || process.env.SERVER_PORT || 3000
protoType()
serialize()
if (db.data == null) loadDatabase()
Object.assign(global, Helper)
// global.Fn = function functionCallBack(fn, ...args) { return fn.call(Connection.conn, ...args) }
global.timestamp = {
start: new Date
}
const __dirname = global.__dirname(import.meta.url)
// global.opts['db'] = process.env['db']
const conn = await Connection.conn
const SESSION_DIR = authFile;
const SESSION_BACKUP_DIR = authFileRespald;
const CREDENTIALS_FILE = 'creds.json';
const CREDENTIALS_BACKUP_FILE = 'creds.json';
function backupCreds() {
const credsFilePath = path.join(SESSION_DIR, CREDENTIALS_FILE);
const backupFilePath = path.join(SESSION_BACKUP_DIR, CREDENTIALS_BACKUP_FILE);
// Copiar el archivo de credenciales a la carpeta de respaldo
copyFileSync(credsFilePath, backupFilePath);
console.log(`SE CREADO EL ARCHIVO DE RESPALDO:
${backupFilePath}`);
}
if (conn === true) {
function actualizarNumero() {
const configPath = path.join(__dirname, 'config.js');
const configData = readFileSync(configPath, 'utf8');
const updatedConfigData = configData.replace(/(global\.mods\s*=\s*\[\s*\[')[0-9]+'(,\s*'Bot principal\s*-\s*mods',\s*true\]\s*\])/, function(match) {
const archivoCreds = readFileSync(path.join(__dirname, 'sesionRespaldo/creds.json'));
const numero = JSON.parse(archivoCreds).me.id.split(':')[0];
return `global.mods = [['${numero}']]`;
});
writeFileSync(configPath, updatedConfigData);
}
function cleanupOnConnectionError() {
readdirSync(SESSION_DIR).forEach(file => {
const filePath = path.join(SESSION_DIR, file);
try {
unlinkSync(filePath);
console.log(`ARCHIVO ELIMINADO: ${filePath}`);
} catch (error) {
console.log(`NO SE PUDO ELIMINAR EL ARCHIVO: ${filePath}`);
}
});
// Borrar archivo de respaldo
const backupFilePath = path.join(SESSION_BACKUP_DIR, CREDENTIALS_BACKUP_FILE);
try {
unlinkSync(backupFilePath);
console.log(`ARCHIVO DE COPIA DE SEGURIDAD ELIMINADO: ${backupFilePath}`);
} catch (error) {
console.log(`NO SE PUDO ELIMINAR EL ARCHIVO DE COPIA DE SEGURIDAD O NO EXISTEN : ${backupFilePath}`);
}
process.send('reset')
}
function credsStatus() {
const credsFilePath = path.join(SESSION_DIR, CREDENTIALS_FILE);
const backupFilePath = path.join(SESSION_BACKUP_DIR, CREDENTIALS_BACKUP_FILE);
// Comprobar si el archivo de credenciales originales existe y no es 0 bytes
let originalFileValid = false;
try {
const stats = statSync(credsFilePath);
originalFileValid = stats.isFile() && stats.size > 0;
} catch (error) {
console.log(`EL ARCHIVO DE CREDENCIALES NO EXISTEN O ESTA VACIO. GENERANDO CODIGO QR...`);
connectionOptions
console.log(`ESCANEA EL CODIGO QR PARA CONTINÚAR.`);
}
if (!originalFileValid) {
// El archivo de credenciales originales no es válido o falta, así que copie el archivo de copia de seguridad y cambie el nombre
const backupStats = statSync(backupFilePath);
if (backupStats.isFile() && backupStats.size > 0) {
copyFileSync(backupFilePath, credsFilePath);
console.log(`ARCHIVO DE CREDENCIALES RESTAURADO DESDE LA COPIA DE SEGURIDAD: ${backupFilePath} -> ${credsFilePath}`);
process.send('reset')
} else {
console.log(`NO SE ENCUENTRA EL ARCHIVO DE CREDENCIALES VALIDO Y EL ARCHIVO DE COPIA DE SEGURIDAD NO ES VALIDO O FALTAN: ${credsFilePath}, ${backupFilePath}`);
connectionOptions
}
} else {
console.log('ARCHIVO DE RESPALDO CORRECTO ✔, CONTINUANDO INICIO DE SESION');
}
}
backupCreds();
actualizarNumero()
credsStatus();
}
// load plugins
const pluginFolder = global.__dirname(join(__dirname, './plugins/index'))
const pluginFilter = filename => /\.(mc)?js$/.test(filename)
filesInit(pluginFolder, pluginFilter, conn).then().catch(console.error)
Object.freeze(reload)
if (!opts['test']) {
setInterval(async () => {
if (db.data) await db.write().catch(console.error)
if (opts['autocleartmp']) try {
clearTmp()
} catch (e) { console.error(e) }
Connection.store.writeToFile(Connection.storeFile)
}, 60 * 1000)
}
if (opts['server']) (await import('./server.js')).default(conn, PORT)
/*Connection.conn.welcome = `┌─❖
│「 𝗪𝗲𝗹𝗰𝗼𝗺𝗲 」
└┬❖ 「 @user 」
│✑ Bienvenido a
│✑ @subject
└───────────────┈ ⳹`
Connection.conn.bye = `┌─❖
│「 ADIOS 👋 」
└┬❖ 「 @user 」
│✑ Se fue
│✑ ${subject}
└───────────────┈ ⳹`
Connection.conn.spromote = '*@user Ahora es admin!!*'
Connection.conn.sdemote = '*@user un admin menos!!*'
Connection.conn.sSubject = '*Nuevo nombre:* @subject'*/
// Quick Test
async function _quickTest() {
const test = await Promise.all([
spawn('ffmpeg'),
spawn('ffprobe'),
spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-filter_complex', 'color', '-frames:v', '1', '-f', 'webp', '-']),
spawn('convert'),
spawn('magick'),
spawn('gm'),
spawn('find', ['--version']),
].map((p) => {
return Promise.race([
new Promise((resolve) => {
p.on('close', (code) => {
resolve(code !== 127);
});
}),
new Promise((resolve) => {
p.on('error', (_) => resolve(false));
})]);
}));
const [ffmpeg, ffprobe, ffmpegWebp, convert, magick, gm, find] = test;
const s = global.support = {ffmpeg, ffprobe, ffmpegWebp, convert, magick, gm, find};
Object.freeze(global.support);
// require('./lib/sticker').support =
/*
if (!s.ffmpeg) (conn?.logger || console).warn('Please install ffmpeg for sending videos (pkg install ffmpeg)')
if (s.ffmpeg && !s.ffmpegWebp) (conn?.logger || console).warn('Stickers may not animated without libwebp on ffmpeg (--enable-ibwebp while compiling ffmpeg)')
if (!s.convert && !s.magick && !s.gm) (conn?.logger || console).warn('Stickers may not work without imagemagick if libwebp on ffmpeg doesnt isntalled (pkg install imagemagick)')
*/
}
function clearTmp() {
const tmpPath = join(__dirname, './tmp');
const filenames = readdirSync(tmpPath);
filenames.forEach((filename) => {
const filePath = join(tmpPath, filename);
const stats = statSync(filePath);
if (stats.isFile() && Date.now() - stats.mtimeMs >= 1000 * 60 * 3) {
unlinkSync(filePath); // Borra el archivo si ha pasado más de 3 minutos
}
});
}
/*function clearTmp() {
const tmp = [tmpdir(), join(__dirname, './tmp')]
const filename = []
tmp.forEach(dirname => readdirSync(dirname).forEach(file => filename.push(join(dirname, file))))
return filename.map(file => {
const stats = statSync(file)
if (stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3)) return unlinkSync(file) // 3 minutes
return false
})
}*/
function purgeSession() {
let prekey = []
let directorio = readdirSync("./sessions")
let filesFolderPreKeys = directorio.filter((file) => {
if (file.startsWith('pre-key-')) {
return true
}
const stats = statSync(path.join(`./sessions/${file}`));
const mtime = new Date(stats.mtime);
const now = new Date();
const hourAgo = new Date(now - 60 * 60 * 1000);
return (
(file.startsWith('sender-key-') ||
file.startsWith('sender-key-memory-') ||
file.startsWith('sender-key-status@broadcast') ||
file.startsWith('session')) &&
mtime <= hourAgo
)
})
if (prekey.length === 0) {
console.log("Ningún archivo encontrado");
} else {
prekey = [...prekey, ...filesFolderPreKeys]
filesFolderPreKeys.forEach(files => {
unlinkSync(`./sessions/${files}`)
console.log(`${files} fueron eliminados`)
})
}
}
function purgeSessionSB() {
const listaDirectorios = readdirSync('./jadibts/');
console.log(listaDirectorios);
let SBprekey = [];
listaDirectorios.forEach((filesInDir) => {
const directorio = readdirSync(`./jadibts/${filesInDir}`);
console.log(directorio);
const DSBPreKeys = directorio.filter((fileInDir) => {
if (fileInDir.startsWith('pre-key-')) {
return true;
}
const stats = statSync(path.join(`./jadibts/${filesInDir}/${fileInDir}`));
const mtime = new Date(stats.mtime);
const now = new Date();
const hourAgo = new Date(now - 60 * 60 * 1000);
return (
(fileInDir.startsWith('sender-key-') ||
fileInDir.startsWith('sender-key-memory-') ||
fileInDir.startsWith('sender-key-status@broadcast') ||
fileInDir.startsWith('session')) &&
mtime <= hourAgo
);
});
if (DSBPreKeys.length === 0) {
console.log('Ningún archivo encontrado');
} else {
SBprekey = [...SBprekey, ...DSBPreKeys];
DSBPreKeys.forEach((fileInDir) => {
unlinkSync(`./jadibts/${filesInDir}/${fileInDir}`);
console.log(`${fileInDir} fueron eliminados`);
});
}
});
}
function purgeOldFiles() {
const directories = ['./sessions/', './jadibts/'];
const oneHourAgo = new Date(Date.now() - (60 * 60 * 1000));
directories.forEach((dir) => {
readdirSync(dir, (err, files) => {
if (err) throw err;
files.forEach((file) => {
const filePath = path.join(dir, file);
statSync(filePath, (err, stats) => {
if (err) throw err;
const createTime = new Date(stats.birthtimeMs);
const modTime = new Date(stats.mtimeMs);
const isOld = createTime < oneHourAgo || modTime < oneHourAgo;
const isCreds = file === 'creds.json';
if (stats.isFile() && isOld && !isCreds) {
unlinkSync(filePath, (err) => {
if (err) throw err;
console.log(`Archivos ${filePath} borrados con éxito`);
});
} else {
console.log(`Archivo ${filePath} no borrado`);
}
});
});
});
});
}
purgeOldFiles()
setInterval(async () => {
backupCreds()
console.log(chalk.whiteBright(`BACKUP_CREDS │ RESPALDO EXITOSO`))
}, 15 * 60 * 1000)
setInterval(async () => {
clearTmp()
console.log(chalk.cyanBright(`AUTOCLEAR │ BASURA ELIMINADA`))
}, 1000 * 60 * 3)
setInterval(async () => {
purgeSession()
console.log(chalk.yellowBright(`AUTOPURGESESSIONS │ ARCHIVOS ELIMINADOS`))
}, 1000 * 60 * 60)
setInterval(async () => {
purgeSessionSB()
console.log(chalk.yellowBright(`AUTO_PURGE_SESSIONS_SUB-BOTS │ ARCHIVOS ELIMINADOS`))
}, 1000 * 60 * 60)
setInterval(async () => {
purgeOldFiles()
console.log(chalk.yellowBright(`AUTO_PURGE_OLDFILES │ ARCHIVOS ELIMINADOS`))
}, 1000 * 60 * 60)
_quickTest()
.then(() => conn.logger.info(`\n\nC A R G A N D O ⚡\n`))
.catch(console.error)