feat: Imagenes

This commit is contained in:
2023-03-01 04:23:03 -06:00
parent f191fbf1fe
commit e0b1c868cd
4 changed files with 2515 additions and 64 deletions

2448
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -19,6 +19,7 @@
"dotenv": "^16.0.1",
"exceljs": "^4.3.0",
"express": "^4.18.1",
"express-fileupload": "^1.4.0",
"express-validator": "^6.15.0",
"file-type": "^17.1.6",
"google-spreadsheet": "^3.3.0",
@@ -26,9 +27,11 @@
"mime-db": "^1.52.0",
"moment": "^2.29.4",
"mysql": "^2.18.1",
"open": "^8.4.2",
"pb-util": "^1.0.3",
"qr-image": "^3.2.0",
"qrcode-terminal": "^0.12.0",
"react-dev-utils": "^12.0.1",
"socket.io": "^4.5.1",
"stormdb": "^0.6.0",
"util-tiempo": "^1.0.41",

View File

@@ -1,6 +1,8 @@
const { Client, LocalAuth, Buttons, List } = require('whatsapp-web.js');
const { MessageMedia, Client, LocalAuth, Buttons, List } = require('whatsapp-web.js');
const { sendMedia, sendMessage, sendMessageButton, sendMessageList, readChat } = require(`../controllers/send`);
const mime = require('mime-types')
require('dotenv').config()
const fs = require('fs');
const express = require('express');
const bodyParser = require("body-parser");
const cors = require('cors')
@@ -8,11 +10,14 @@ const qrcode = require('qrcode-terminal');
const app = express();
app.use(cors())
app.use(express.json())
// Use the express-fileupload middleware
const server = require('http').Server(app)
const port = process.env.PORT || 3000
const { generateImage, checkEnvFile } = require('../controllers/handle')
const { connectionReady } = require('../controllers/connection')
const { body, validationResult } = require('express-validator');
const fileUpload = require('express-fileupload');
app.use(fileUpload());
app.use('/', require('../routes/web'))
@@ -31,7 +36,7 @@ initBot = async () => {
console.log("Iniciamos WaWebJS")
client = new Client({
authStrategy: new LocalAuth(),
puppeteer: { headless: true, args: ['--no-sandbox','--disable-setuid-sandbox'] }
pup: { headless: true, args: ['--no-sandbox','--disable-setuid-sandbox'] }
});
client.on('ready', (a) => {
connectionReady()
@@ -86,7 +91,7 @@ initBot = async () => {
client.on('ready', async () => {
socketioStatus = "wa_ready"
await socket.emit('ready', 'Whatsapp esta listo!');
await socket.emit('message', 'Whatsapp esta listo!');
await socket.emit('message', 'Whatsapp está listo!');
waReady = true
});
@@ -112,9 +117,9 @@ initBot = async () => {
}
catch (e) {waReady = false }
});
});
server.listen(port, () => {
console.log(`El servidor web esta listo en el puerto ${port} - http://localhost:${port}`);
console.log(`El servidor web esta listo en el puerto ${port} - http://localhost:${port}`);
})
const phoneNumberFormatter = function (number) {
// 1. Eliminar caracteres que no sean números
@@ -217,6 +222,63 @@ initBot = async () => {
});
});
});
// Send image
app.post('/send-image', async (req, res) => {
console.log("REQUEST=", req.body)
socks.emit('incomming', 'Image In')
const number = phoneNumberFormatter(req.body.number);
// const filename = req.body.image || null;
const caption = req.body.caption || null;
const { image } = req.files;
// If no image submitted, exit
if (!image) return res.sendStatus(400);
// Move the uploaded image to our upload folder
image.mv(__dirname + '/../mediaSend/' + image.name);
res.sendStatus(200);
const isRegisteredNumber = await checkRegisteredNumber(number);
if (!isRegisteredNumber) {
return res.status(422).json({
status: false,
message: 'The number is not registered'
});
}
// sendMedia(client, number, image.name, caption)
// `${__dirname}/../mediaSend`;
const file = `${__dirname}/../mediaSend/${image.name}`;
console.log("FILE="+file);
if (fs.existsSync(file)) {
console.log("ARCHIVO EXISTE");
const media = MessageMedia.fromFilePath(file);
}
const base64 = fs.readFileSync(file, { encoding: 'base64' })
const mimeType = mime.lookup(file)
const media = new MessageMedia(mimeType, base64)
client.sendMessage(number, media, { caption }).then(response => {
socks.emit('imgOk', 'image sent')
console.log("Imagen OK")
// res.status(200).json({
// status: true,
// response: response
// });
}).catch(err => {
socks.emit('imgKo', 'image NOT sent')
console.log("Imagen NOT OK")
// res.status(500).json({
// status: false,
// response: err
// });
});
});
// app.post('/upload', async (req, res) => {
// // Get the file that was set to our field named "image"
// const { image } = req.files;
// // If no image submitted, exit
// if (!image) return res.sendStatus(400);
// // Move the uploaded image to our upload folder
// image.mv(__dirname + '/../mediaSend/' + image.name);
// res.sendStatus(200);
// });
checkEnvFile();
return client

View File

@@ -65,7 +65,7 @@
<div>
<select id="tipoMensaje">
<option>Mensaje</option>
<!-- <option>Imagen</option> -->
<option>Imagen</option>
<option>Botones</option>
</select>
</div>
@@ -120,26 +120,28 @@
</tr>
</table>
</div>
<!-- <div id="postImg">
<div id="postImg">
<table>
<form action="/send-image" method="POST" id="imgForm" enctype="multipart/form-data">
<tr>
<td>Número:</td>
<td><input type="text" id="number" value="5215554192439"></td>
<td><input type="text" id="imgnumber" value="5215554192439" style="width:160px;"></td>
</tr>
<tr>
<td>Imagen:</td>
<td><input type="text" id="image" value="test1"></td>
<td><input type="file" id="imgimage" name="imgimage" style="width:160px;" /></td>
</tr>
<tr>
<td>Texto:</td>
<td><input type="text" id="caption" placeholder="El texto aquí"></td>
<td><input type="text" id="imgcaption" placeholder="El texto aquí" style="width:160px;"></td>
</tr>
<tr>
<td> </td>
<td align="center"><input type="button" id="btnImg" value="Enviar Mensaje"></td>
</tr>
</form>
</table>
</div> -->
</div>
</div>
</div>
<!-- <input type="button" id="chkConn" value="QR"> -->
@@ -148,6 +150,14 @@
<ul class="logs"></ul>
</div>
<div id="div_wa_msg" style="display: none;"></div>
<!-- <form action="/send-image" method="POST" enctype="multipart/form-data">
<input type="text" name="number" value="5215554192439"><br>
<input type="text" name="caption" placeholder="El texto de la imagen"><br>
<input type="file" name="image" />
<button type="submit">Upload</button>
</form> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js" crossorigin="anonymous"></script>
<script>
@@ -175,13 +185,16 @@
$("#div_wa_msg").fadeOut("slow")
}, 1500);
})
socket.on('imgOk', function (msg) {
alert("¡Imagen mandada con exito!")
})
socket.on('message', function (msg) {
$('.logs').prepend($('<li>').text(msg));
console.log("|" + msg + "|");
console.log("MENSAJES = " + $(".logs li").length)
if($(".logs li").length >= 15){ $('.logs li').last().remove(); }
if (msg == 'Conectando...' && IOSTATUS == "wa_ready") { $('#divQRPage').hide(); $('#postman').show(); waReady = false, $("#btnMessage").attr("disabled", true); $("#btnBtn").attr("disabled", true); }
if (msg == 'Whatsapp esta listo!') { $("#btnMessage").attr("disabled", false); $("#btnBtn").attr("disabled", false); }
// if (msg == 'Whatsapp esta listo!') { $("#btnMessage").attr("disabled", false); $("#btnBtn").attr("disabled", false); }
})
socket.on('qr', function (src) {
var extra = Date.now();
@@ -196,8 +209,10 @@
startImer()
})
socket.on('ready', function (data) {
$("#divQRPage").hide()
$("#divQRPage").hide();
$('#postman').show();
$("#btnMessage").attr("disabled", false);
$("#btnBtn").attr("disabled", false);
clearInterval(IntervaloABorrar);
})
socket.on('authenticated', function (data) {
@@ -302,6 +317,31 @@
}
else{alert("Es necesario llenar por lo menos el número, mensaje y boton1.")}
})
$("#btnImg").click(function () {
var fd = new FormData();
console.log("IMAGEN=" + $('#imgimage')[0]?.files[0])
var files = $('#imgimage')[0].files[0];
fd.append('image', files);
fd.append('number', $("#imgnumber").val())
fd.append('caption', $("#imgcaption").val())
$.ajax({
url: 'http://localhost:3005/send-image/',
type: 'POST',
data: fd,
contentType: false,
processData: false,
success: function (response) {
if (response != 0) {
// alert('file uploaded');
}
else {
alert('file not uploaded');
}
},
});
});
$("#tipoMensaje").change(function () {
let sel = $("select option:selected").val()
console.log(sel)