From 87739a5847b4c4f35871be864233c2e6083117ca Mon Sep 17 00:00:00 2001 From: Paolo Arena Date: Tue, 5 Oct 2021 15:39:44 +0200 Subject: [PATCH] Fixed WebPush Notification error subscription --- src/server/router/subscribe_router.js | 88 +-- src/server/router/users_router.js | 2 +- src/server/tools/general.js | 1048 +++++++++++++++---------- 3 files changed, 669 insertions(+), 469 deletions(-) diff --git a/src/server/router/subscribe_router.js b/src/server/router/subscribe_router.js index 405747a..81749a6 100755 --- a/src/server/router/subscribe_router.js +++ b/src/server/router/subscribe_router.js @@ -1,11 +1,11 @@ const express = require('express'); const router = express.Router(); -const mongoose = require('mongoose').set('debug', false) +const mongoose = require('mongoose').set('debug', false); const Subscription = mongoose.model('subscribers'); const tools = require('../tools/general'); -var { authenticate } = require('../middleware/authenticate'); +var {authenticate} = require('../middleware/authenticate'); const isValidSaveRequest = (req, res) => { try { @@ -15,14 +15,14 @@ const isValidSaveRequest = (req, res) => { res.send(JSON.stringify({ error: { id: 'no-endpoint', - message: 'Subscription must have an endpoint' - } + message: 'Subscription must have an endpoint', + }, })); - return false + return false; } - return true + return true; } catch (e) { - return false + return false; } }; @@ -39,65 +39,63 @@ router.post('/', authenticate, (req, res) => { subscriptionModel.browser = req.get('User-Agent'); // Find if already exist - Subscription.findOne( {userId: subscriptionModel.userId, access: subscriptionModel.access, browser: subscriptionModel.browser}) - .then(itemsub => { - return itemsub - }) - .catch(err => { - // Not found - return null - }) - .then(myitem => { + Subscription.findOne({ + userId: subscriptionModel.userId, + access: subscriptionModel.access, + browser: subscriptionModel.browser, + }).then(itemsub => { + return itemsub; + }).catch(err => { + // Not found + return null; + }).then(myitem => { - if (myitem === null) { - myitem = subscriptionModel; - tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!', myitem) - } + if (myitem === null) { + myitem = subscriptionModel; + tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!', myitem) + } else { + myitem.endpoint = subscriptionModel.endpoint; + myitem.keys = subscriptionModel.keys; + } - // else - // tools.mylogshow('Subscription already Existed!'); + return myitem.save((err, subscription) => { + if (err) { + console.error(`Error occurred while saving subscription. Err: ${err}`); + return res.status(500).json({ + error: 'Technical error occurred', + }); + } else { + // Send 201 - resource created + // res.status(201).json({ data: 'Subscription saved.' }); + console.log('New Subscription id=', subscriptionModel.userId); - myitem.save((err, subscription) => { - if (err) { - console.error(`Error occurred while saving subscription. Err: ${err}`); - res.status(500).json({ - error: 'Technical error occurred' - }); - } else { - // Send 201 - resource created - // res.status(201).json({ data: 'Subscription saved.' }); - res.send({ data: 'Subscription saved.' }); + // console.log('req.body', req.body) - console.log('New Subscription id=', subscriptionModel.userId); - - // console.log('req.body', req.body) - - if (req.body.options !== null) { - tools.sendBackNotif(subscription, req.body.options) - } + if (req.body.options !== null) { + tools.sendBackNotif(subscription, req.body.options); } - }); + return res.send({data: 'Subscription saved.'}); + } }); + }); }); - router.delete('/del', authenticate, (req, res) => { // tools.mylog("TOKENREM = " + req.token); const browser = req.get('User-Agent'); - Subscription.findOneAndRemove( { userId: req.user._id, access: req.access, browser } ).then(() => { + Subscription.findOneAndRemove( + {userId: req.user._id, access: req.access, browser}).then(() => { res.status(200).send(); }, () => { res.status(400).send(); }); }); - - router.get('/', (req, res) => { res.json({ - data: 'Invalid Request Bad' + data: 'Invalid Request Bad', }); }); diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js index a6e3f37..e1d1640 100755 --- a/src/server/router/users_router.js +++ b/src/server/router/users_router.js @@ -352,7 +352,7 @@ router.post('/login', (req, res) => { .then(user => { if (user) { return user.generateAuthToken(req).then((token) => { - var usertosend = User(); + var usertosend = new User(); shared_consts.fieldsUserToChange().forEach((field) => { usertosend[field] = user[field] diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 582a0a6..e011034 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1,26 +1,24 @@ -const os = require("os"); +const os = require('os'); const fs = require('fs'); const path = require('path'); - require('../config/config'); require('../models/subscribers'); - const Site = require('../models/site'); const CryptoJS = require('crypto-js'); const Url = require('url-parse'); -const { ObjectID } = require('mongodb'); +const {ObjectID} = require('mongodb'); const shared_consts = require('./shared_nodejs'); -const mongoose = require('mongoose').set('debug', false) +const mongoose = require('mongoose').set('debug', false); const Subscription = mongoose.model('subscribers'); const server_constants = require('./server_constants'); @@ -45,34 +43,32 @@ const keySize = 256; const ivSize = 128; const iterations = 100; - -if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== "") { +if (!!process.env.GCM_API_KEY && process.env.GCM_API_KEY !== '') { webpush.setGCMAPIKey(process.env.GCM_API_KEY); webpush.setVapidDetails(subject, publicVapidKey, privateVapidKey); } // console.log('setVapidDetails... config...'); - // To Translate! const textlang = { it: { - "L'Email è già stata Verificata": "L'Email è già stata Verificata", - "Nuova Registrazione": "Nuova Registrazione", - "Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione", - "partecipanti": "partecipanti all'Evento", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - "partecipanti a Cena Condivisa": "partecipanti a Cena Condivisa", - 'TESTO_ASSISTENZA': "👉 Per entrare nel Sito AYNI\n\n" + - "👉 Hai dimenticato la password?\n\n" + - "👉 Entra nel Canale d'Informazione per Importanti Avvisi!\nCanale AYNI-BIBLIO\n\n" + - "👉 Chat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat\n%s\n\n" + - "👉 PER AIUTO: Leggi le Domande più Frequenti:\n%s\nOppure chiedi prima al tuo Invitante!\n\n" + - "SOLO se non trovi la risposta che ti serve puoi accedere alla Chat di Supporto 'AYNI - HELP'\nDa Lunedì al Venerdí (9:00 - 19:00)\n%s\n" + - "1 - Fai la tua domanda e chiedi assistenza.\n2 - Dopo aver ricevuto aiuto Esci dalla chat.\nPotrai rientrare ogni qualvolta ne avrai la necessità.", - 'BENVENUTO': "Benvenuto", - 'TUE_NAVI': "Ecco le tue Navi programmate", + 'L\'Email è già stata Verificata': 'L\'Email è già stata Verificata', + 'Nuova Registrazione': 'Nuova Registrazione', + 'Effettuata una Nuova Registrazione': 'Effettuata una Nuova Registrazione', + 'partecipanti': 'partecipanti all\'Evento', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'partecipanti a Cena Condivisa': 'partecipanti a Cena Condivisa', + 'TESTO_ASSISTENZA': '👉 Per entrare nel Sito AYNI\n\n' + + '👉 Hai dimenticato la password?\n\n' + + '👉 Entra nel Canale d\'Informazione per Importanti Avvisi!\nCanale AYNI-BIBLIO\n\n' + + '👉 Chat AYNI - EMPOWER: Entra ⛩ nella nostra Community chat\n%s\n\n' + + '👉 PER AIUTO: Leggi le Domande più Frequenti:\n%s\nOppure chiedi prima al tuo Invitante!\n\n' + + 'SOLO se non trovi la risposta che ti serve puoi accedere alla Chat di Supporto \'AYNI - HELP\'\nDa Lunedì al Venerdí (9:00 - 19:00)\n%s\n' + + '1 - Fai la tua domanda e chiedi assistenza.\n2 - Dopo aver ricevuto aiuto Esci dalla chat.\nPotrai rientrare ogni qualvolta ne avrai la necessità.', + 'BENVENUTO': 'Benvenuto', + 'TUE_NAVI': 'Ecco le tue Navi programmate', 'HAI_I_7_REQUISITI': 'PRIMI PASSI OK!\nHai i Primi 7 Requisiti per Entrare nella Lista d\'Imbarco!', 'NON_HAI_I_7_REQUISITI': 'Attenzione!\nAncora non hai i 7 Requisiti per Entrare nella Lista d\'Imbarco!', 'HAI_I_9_REQUISITI': 'COMPLIMENTI!\nHai Completato TUTTI i 9 Passi della Guida! Grazie per Aiutare AYNI ad Espandersi!', @@ -83,12 +79,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Link da condividere ai tuoi invitati per farli registrare al sito di Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Link da condividere per partecipare allo Zoom (Conferenza OnLine):\n%s', 'ZOOM_CONFERENCE': 'Ecco il programma delle Conferenze (Zoom) aperti a TUTTI:', - "NON_VERIF": "Non Verificata", - "VERIF": "Verificata", - 'EMAIL': "Email", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**\ne clicca sul bottone **\"Verifica Registrazione\"**", - 'TELEGRAM_NOT_CONNECTED': "Telegram non associato al tuo account!", + 'NON_VERIF': 'Non Verificata', + 'VERIF': 'Verificata', + 'EMAIL': 'Email', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Email Non Verificata\nleggi la tua casella email e trova **"Confermare la Registrazione a Ayni"**\ne clicca sul bottone **"Verifica Registrazione"**', + 'TELEGRAM_NOT_CONNECTED': 'Telegram non associato al tuo account!', 'NESSUN_INVITATO': 'Non hai invitato nessuno', 'ZOOM_PARTECIPATO': 'Partecipazione ad almeno 1 Conferenza (Zoom)', 'LINEE_GUIDA': 'Accettato le Linee Guida', @@ -131,22 +127,22 @@ const textlang = { 'ZOOM_CONFERMATO': 'Sei stato confermato ad aver visto la Video Conferenza di Benvenuto!', }, si: { - "Email je že bila preverjena": "Email je že bila preverjenaL'Email è già stata Verificata", - "Nuova Registrazione": "Nova Registracija", - "Effettuata una Nuova Registrazione": "Izpelji novo Registracijo", - "partecipanti": "Udeleženci", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - 'TESTO_ASSISTENZA': "Za vstop na spletno stran:\n%s\n\n" + - "Si pozabil geslo za vstop na stran?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + - "Klepet AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\n" + - "Klepet AYNI - EMPOWER: Vstopi ⛩ v našo Skupnost klepet:\n%s\n\n" + - "Canal News AYNI-BIBLIO:\n%s\n\n" + - "Klepet za Pomoč in Suport: 'AYNI - HELP'\n%s\n" + - "1 - Postavi svoje vprašanje in prosi za asistenco.\n2 - KO si sprejel pomoč, izstopi iz klepeta.\n " + - "Vstopil boš lahko vedno, ko boš potreboval pomoč.", - 'BENVENUTO': "Dobrodošel", - 'TUE_NAVI': "Tvoje programirane Ladje", + 'Email je že bila preverjena': 'Email je že bila preverjenaL\'Email è già stata Verificata', + 'Nuova Registrazione': 'Nova Registracija', + 'Effettuata una Nuova Registrazione': 'Izpelji novo Registracijo', + 'partecipanti': 'Udeleženci', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'TESTO_ASSISTENZA': 'Za vstop na spletno stran:\n%s\n\n' + + 'Si pozabil geslo za vstop na stran?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n' + + 'Klepet AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\n' + + 'Klepet AYNI - EMPOWER: Vstopi ⛩ v našo Skupnost klepet:\n%s\n\n' + + 'Canal News AYNI-BIBLIO:\n%s\n\n' + + 'Klepet za Pomoč in Suport: \'AYNI - HELP\'\n%s\n' + + '1 - Postavi svoje vprašanje in prosi za asistenco.\n2 - KO si sprejel pomoč, izstopi iz klepeta.\n ' + + 'Vstopil boš lahko vedno, ko boš potreboval pomoč.', + 'BENVENUTO': 'Dobrodošel', + 'TUE_NAVI': 'Tvoje programirane Ladje', 'HAI_I_7_REQUISITI': 'PRVI KORAKI OK!\nIzpolnjuješ Prvih 7 Zahtev za vstop na Listo d\'Vkrcanje!', 'NON_HAI_I_7_REQUISITI': 'Pozor!\nŠe vedno nimaš izpolnjenih 7 Zahtev za vstop na listo\'Vkrcanje!', 'HAI_I_9_REQUISITI': 'ČESTITAMO!\nIzpolnil si VSEH 9 korakov v navodilih! Hvala ker pomagaš k širitvi AYNI !', @@ -157,12 +153,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Link, ki ga deliš svojim povabljencem, da se lahko registrirajo na spletni strani Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Link, ki ga deliš za udeležbo na Zoom (Konferenca OnLine):\n%s', 'ZOOM_CONFERENCE': 'Tu najdeš datume prihajajočih Zoom-ov:', - "NON_VERIF": "Ni Preverjena", - "VERIF": "Preverjena", - 'EMAIL': "Email", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Email ni preverjen\npojdi v svoj poštni nabiralnik in najdi**\"Potrditev Registracije na Ayni\"**
e klikni na gumb **\"Potrdi Registracijo\"**", - 'TELEGRAM_NOT_CONNECTED': "Telegram ni povezan s tvojim računom!", + 'NON_VERIF': 'Ni Preverjena', + 'VERIF': 'Preverjena', + 'EMAIL': 'Email', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Email ni preverjen\npojdi v svoj poštni nabiralnik in najdi**"Potrditev Registracije na Ayni"**
e klikni na gumb **"Potrdi Registracijo"**', + 'TELEGRAM_NOT_CONNECTED': 'Telegram ni povezan s tvojim računom!', 'NESSUN_INVITATO': 'Nisi povabil nikogar', 'ZOOM_PARTECIPATO': 'Udeležba na vsaj 1 Konferenci (Zoom-u)', 'LINEE_GUIDA': 'Sprejemam pogoje poslovanja', @@ -202,20 +198,20 @@ const textlang = { 'ZOOM_CONFERMATO': 'Potrjeno je bilo, da ste videli dobrodošlico video konference!', }, es: { - "L'Email è già stata Verificata": "El correo electrónico ya ha sido verificado", - "Nuova Registrazione": "Nuevo Registro", - "Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro", - "partecipanti": "participantes", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - 'TESTO_ASSISTENZA': "Para entrar en el sitio de AYNI:\n%s\n\n" + - "¿Olvidó su contraseña para acceder al sitio?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + - "Chat AYNI BOT (este):\nhttps://t.me/notevoleaynibot\n\n" + - "Chat AYNI - EMPOWER: Entra en ⛩ en nuestra comunidad de chat:\n%s\n\n" + - "Chat de ayuda y soporte: 'AYNI - HELP'\nDe lunes a viernes (9:00 - 19:00)\n%s\n" + - "1 - Haga su pregunta y pida ayuda.\n2 - Después de que consigas ayuda, sal de la sala de chat.\nPuedes volver cuando necesites ayuda..", - 'BENVENUTO': "Bienvenido", - 'TUE_NAVI': "Aquí están sus naves programadas", + 'L\'Email è già stata Verificata': 'El correo electrónico ya ha sido verificado', + 'Nuova Registrazione': 'Nuevo Registro', + 'Effettuata una Nuova Registrazione': 'Se ha realizado un nuevo registro', + 'partecipanti': 'participantes', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'TESTO_ASSISTENZA': 'Para entrar en el sitio de AYNI:\n%s\n\n' + + '¿Olvidó su contraseña para acceder al sitio?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n' + + 'Chat AYNI BOT (este):\nhttps://t.me/notevoleaynibot\n\n' + + 'Chat AYNI - EMPOWER: Entra en ⛩ en nuestra comunidad de chat:\n%s\n\n' + + 'Chat de ayuda y soporte: \'AYNI - HELP\'\nDe lunes a viernes (9:00 - 19:00)\n%s\n' + + '1 - Haga su pregunta y pida ayuda.\n2 - Después de que consigas ayuda, sal de la sala de chat.\nPuedes volver cuando necesites ayuda..', + 'BENVENUTO': 'Bienvenido', + 'TUE_NAVI': 'Aquí están sus naves programadas', 'HAI_I_7_REQUISITI': '¡LOS PRIMEROS PASOS ESTÁN BIEN!\nTiene los primeros 7 requisitos para entrar en la lista de embarque!', 'NON_HAI_I_7_REQUISITI': '¡Atención!\nTodavía no tienes los 7 requisitos para entrar en la lista de embarque!', 'HAI_I_9_REQUISITI': '¡FELICITACIONES!\n¡Has completado los 9 pasos de la Guía! Gracias por ayudar a AYNI a expandirse!', @@ -226,12 +222,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Enlaces para compartir con sus invitados para que se registren en el sitio web de Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Enlaces para compartir para participar en el Zoom (Conferencia en línea):\n%s', 'ZOOM_CONFERENCE': 'Aquí puedes encontrar las fechas de programación en el Zoom:', - "NON_VERIF": "No verificado", - "VERIF": "Verificado", - 'EMAIL': "Email", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Correo electrónico no verificado\nlea su buzón y encuentre **\"Confirmar Registro a Ayni \"** y haga clic en el botón **\"Verificar Registro \"**.", - 'TELEGRAM_NOT_CONNECTED': "Telegram no asociado a su cuenta!", + 'NON_VERIF': 'No verificado', + 'VERIF': 'Verificado', + 'EMAIL': 'Email', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Correo electrónico no verificado\nlea su buzón y encuentre **"Confirmar Registro a Ayni "** y haga clic en el botón **"Verificar Registro "**.', + 'TELEGRAM_NOT_CONNECTED': 'Telegram no asociado a su cuenta!', 'NESSUN_INVITATO': 'No invitaste a nadie', 'ZOOM_PARTECIPATO': 'Participación en al menos 1 Conferencia (Zoom)', 'LINEE_GUIDA': 'Directrices aceptadas', @@ -271,17 +267,17 @@ const textlang = { 'ZOOM_CONFERMATO': '¡Se ha confirmado que ha visto la Video Conferencia de Bienvenida!', }, enUs: { - "partecipanti": "participants", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - 'TESTO_ASSISTENZA': "To enter the AYNI Site:\n%s\n\nForgot your password to access the site?\n" + - "https://ayni.gifteconomy.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n" + - "Chat AYNI - EMPOWER: Enter ⛩ into our chat community:\n%s\n\n" + - "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Help and Support Chat: 'AYNI - HELP'.\nMonday to Friday (9:00 - 19:00)\n%s\n" + - "1 - Ask your question and ask for assistance.\n2 - After receiving help, exit the chat.\nYou can come back whenever you need help.", - 'BENVENUTO': "Welcome", - 'TUE_NAVI': "Here are your programmed ships", + 'partecipanti': 'participants', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'TESTO_ASSISTENZA': 'To enter the AYNI Site:\n%s\n\nForgot your password to access the site?\n' + + 'https://ayni.gifteconomy.app/requestresetpwd\nChat AYNI BOT (this one):\nhttps://t.me/notevoleaynibot\n\n' + + 'Chat AYNI - EMPOWER: Enter ⛩ into our chat community:\n%s\n\n' + + 'Canale News AYNI-BIBLIO:\n%s\n\n' + + 'Help and Support Chat: \'AYNI - HELP\'.\nMonday to Friday (9:00 - 19:00)\n%s\n' + + '1 - Ask your question and ask for assistance.\n2 - After receiving help, exit the chat.\nYou can come back whenever you need help.', + 'BENVENUTO': 'Welcome', + 'TUE_NAVI': 'Here are your programmed ships', 'HAI_I_7_REQUISITI': 'FIRST STEPS OK!\nYou have the First 7 Requirements to Enter the Boarding List!', 'NON_HAI_I_7_REQUISITI': 'Attention!\nYou still do not have the 7 requirements to enter the boarding list!', 'HAI_I_9_REQUISITI': 'CONGRATULATIONS!\nYou have completed ALL 9 steps of the Guide! Thank you for Helping AYNI Expand!', @@ -292,12 +288,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Links to share with your guests to have them register on Ayni\'s website:\n\n%s', 'INFO_LINK_ZOOM': 'Links to share to participate in Zoom (Online Conference):\n%s', 'ZOOM_CONFERENCE': 'Here you can find the Zoom Conference Planning:', - "NON_VERIF": "Not Verified", - "VERIF": "Verified", - 'EMAIL': "Email", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Email Not Verified\nread your mailbox and find **\"Confirm Registration to Ayni \"**
and click on the button **\"Verify Registration \"**.", - 'TELEGRAM_NOT_CONNECTED': "Telegram not associated with your account!", + 'NON_VERIF': 'Not Verified', + 'VERIF': 'Verified', + 'EMAIL': 'Email', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Email Not Verified\nread your mailbox and find **"Confirm Registration to Ayni "**
and click on the button **"Verify Registration "**.', + 'TELEGRAM_NOT_CONNECTED': 'Telegram not associated with your account!', 'NESSUN_INVITATO': 'You didn\'t invite anyone', 'ZOOM_PARTECIPATO': 'Participation in at least 1 Conference (Zoom)', 'LINEE_GUIDA': 'Guidelines Accepted', @@ -337,21 +333,21 @@ const textlang = { 'ZOOM_CONFERMATO': 'You have been confirmed to have seen the Welcome Video Conference!', }, fr: { - "L'Email è già stata Verificata": "Le courrier électronique a déjà été vérifié", - "Nuova Registrazione": "Nouvelle inscription", - "Effettuata una Nuova Registrazione": "Un nouvel enregistrement a été effectué", - "partecipanti": "participants", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - 'TESTO_ASSISTENZA': "Pour entrer sur le site AYNI:\n%s\n\n" + - "Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + - "Chat AYNI BOT (ce):\nhttps://t.me/notevoleaynibot\n\n" + - "Chat AYNI - EMPOWER : Entrez ⛩ dans notre Community chat:\n%s\n\n" + - "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Chat d’Aide et de Support: 'AYNI - HELP'\nDu lundi au Vendredi (9:00 - 19:00)\n%s\n" + - "1 - Posez votre question et demandez d’être assisté.\n2 - Après avoir reçu l’aide, quittez le groupe.\nVous pourrez y entrer chaque fois qu’il vous sera nécessaire.", - 'BENVENUTO': "Bienvenue", - 'TUE_NAVI': "Voici vos navires programmés", + 'L\'Email è già stata Verificata': 'Le courrier électronique a déjà été vérifié', + 'Nuova Registrazione': 'Nouvelle inscription', + 'Effettuata una Nuova Registrazione': 'Un nouvel enregistrement a été effectué', + 'partecipanti': 'participants', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'TESTO_ASSISTENZA': 'Pour entrer sur le site AYNI:\n%s\n\n' + + 'Vous avez oublié votre mot de passe pour accéder au site ?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n' + + 'Chat AYNI BOT (ce):\nhttps://t.me/notevoleaynibot\n\n' + + 'Chat AYNI - EMPOWER : Entrez ⛩ dans notre Community chat:\n%s\n\n' + + 'Canale News AYNI-BIBLIO:\n%s\n\n' + + 'Chat d’Aide et de Support: \'AYNI - HELP\'\nDu lundi au Vendredi (9:00 - 19:00)\n%s\n' + + '1 - Posez votre question et demandez d’être assisté.\n2 - Après avoir reçu l’aide, quittez le groupe.\nVous pourrez y entrer chaque fois qu’il vous sera nécessaire.', + 'BENVENUTO': 'Bienvenue', + 'TUE_NAVI': 'Voici vos navires programmés', 'HAI_I_7_REQUISITI': 'PREMIÈRES ÉTAPES OK!\nvous avez les 7 premiers Requis pour Entrer dans la liste d\'embarquement!', 'NON_HAI_I_7_REQUISITI': '\'Attention!\nVous ne remplissez pas encore les 7 conditions pour figurer sur la liste d\'embarquement!', 'HAI_I_9_REQUISITI': 'FÉLICITATIONS!\n!Vous avez franchi les 9 étapes de la conduite ! Merci d\'avoir aidé AYNI à se développer!', @@ -362,12 +358,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Liens à partager avec vos invités pour qu\'ils s\'inscrivent sur le site web d\'Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Liens à partager pour participer à Zoom (Conférence en ligne):\n%s', 'ZOOM_CONFERENCE': 'Vous trouverez ici les dates de programmation sur Zoom:', - "NON_VERIF": "Non vérifié", - "VERIF": "Vérifié", - 'EMAIL': "Courriel", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Courriel non vérifié\nlisez votre boîte aux lettres et trouvez **\"Confirmer l'inscription à Ayni \"**
et cliquez sur le bouton **\"Vérifier l'inscription \"**.", - 'TELEGRAM_NOT_CONNECTED': "Télégramme non associé à votre compte!", + 'NON_VERIF': 'Non vérifié', + 'VERIF': 'Vérifié', + 'EMAIL': 'Courriel', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Courriel non vérifié\nlisez votre boîte aux lettres et trouvez **"Confirmer l\'inscription à Ayni "**
et cliquez sur le bouton **"Vérifier l\'inscription "**.', + 'TELEGRAM_NOT_CONNECTED': 'Télégramme non associé à votre compte!', 'NESSUN_INVITATO': 'Vous n\'avez invité personne', 'ZOOM_PARTECIPATO': 'Participation à au moins 1 conférence (Zoom)', 'LINEE_GUIDA': 'Lignes directrices acceptées', @@ -407,21 +403,21 @@ const textlang = { 'ZOOM_CONFERMATO': 'Vous avez été confirmé comme ayant vu la vidéoconférence de bienvenue !', }, pt: { - "L'Email è già stata Verificata": "", - "Nuova Registrazione": "Novo Registo", - "Effettuata una Nuova Registrazione": "Foi efectuado um novo registo", - "partecipanti": "participantes", - "partecipanti a Pranzo": "partecipanti a Pranzo", - "partecipanti a Cena": "partecipanti a Cena", - 'TESTO_ASSISTENZA': "Para entrar no site do AYNI:\n%s\n\n" + - "Esqueceu sua senha para acessar o site?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n" + - "Chat AYNI BOT (isto):\nhttps://t.me/notevoleaynibot\n\n" + - "Chat AYNI - EMPOWER: Entrar em ⛩ na nossa comunidade de chat:%s\n\n" + - "Canale News AYNI-BIBLIO:\n%s\n\n" + - "Chat de Ajuda e Suporte: 'AYNI - HELP'.\nDe segunda a Sexta (9:00 - 19:00 ITALY)\n%s\n" + - "1 - Faça a sua pergunta e peça ajuda.\n2 - Depois de receber ajuda, saia do chat.\nPode voltar sempre que precisar de o fazer..", - 'BENVENUTO': "Bem-vindo", - 'TUE_NAVI': "Aqui estão os seus navios programados", + 'L\'Email è già stata Verificata': '', + 'Nuova Registrazione': 'Novo Registo', + 'Effettuata una Nuova Registrazione': 'Foi efectuado um novo registo', + 'partecipanti': 'participantes', + 'partecipanti a Pranzo': 'partecipanti a Pranzo', + 'partecipanti a Cena': 'partecipanti a Cena', + 'TESTO_ASSISTENZA': 'Para entrar no site do AYNI:\n%s\n\n' + + 'Esqueceu sua senha para acessar o site?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\n' + + 'Chat AYNI BOT (isto):\nhttps://t.me/notevoleaynibot\n\n' + + 'Chat AYNI - EMPOWER: Entrar em ⛩ na nossa comunidade de chat:%s\n\n' + + 'Canale News AYNI-BIBLIO:\n%s\n\n' + + 'Chat de Ajuda e Suporte: \'AYNI - HELP\'.\nDe segunda a Sexta (9:00 - 19:00 ITALY)\n%s\n' + + '1 - Faça a sua pergunta e peça ajuda.\n2 - Depois de receber ajuda, saia do chat.\nPode voltar sempre que precisar de o fazer..', + 'BENVENUTO': 'Bem-vindo', + 'TUE_NAVI': 'Aqui estão os seus navios programados', 'HAI_I_7_REQUISITI': 'PRIMEIROS PASSOS OK!\nVocê tem os 7 primeiros requisitos para entrar na lista de embarque!', 'NON_HAI_I_7_REQUISITI': 'Atenção!\nVocê ainda não tem os 7 requisitos para entrar na lista de embarque!', 'HAI_I_9_REQUISITI': 'FELICITAÇÕES!\nVocê completou TODAS as 9 etapas da condução! Obrigado por ajudar a AYNI a expandir!', @@ -432,12 +428,12 @@ const textlang = { 'INFO_LINK_DA_CONDIVIDERE': 'Links para partilhar com os seus convidados para que se registem no website da Ayni:\n\n%s', 'INFO_LINK_ZOOM': 'Links para partilhar para participar na Zoom (Conferência Online):\n%s', 'ZOOM_CONFERENCE': 'Aqui está o programa das Conferências (Zoom) aberto a TODOS:', - "NON_VERIF": "Não verificado", - "VERIF": "Verificado", - 'EMAIL': "Email", - 'BOT': "AYNI BOT", - 'EMAIL_NON_VERIF': "Email Não verificado\nleia a sua caixa de correio e encontre **\"Confirmar o registo à Ayni\"**
e clique no botão **\"Verificação do registo\"**", - 'TELEGRAM_NOT_CONNECTED': "Telegrama não associado à sua conta!", + 'NON_VERIF': 'Não verificado', + 'VERIF': 'Verificado', + 'EMAIL': 'Email', + 'BOT': 'AYNI BOT', + 'EMAIL_NON_VERIF': 'Email Não verificado\nleia a sua caixa de correio e encontre **"Confirmar o registo à Ayni"**
e clique no botão **"Verificação do registo"**', + 'TELEGRAM_NOT_CONNECTED': 'Telegrama não associado à sua conta!', 'NESSUN_INVITATO': 'Você não convidou ninguém', 'ZOOM_PARTECIPATO': 'Participação em pelo menos 1 Conferência (Zoom)', 'LINEE_GUIDA': 'Directrizes Aceites', @@ -478,7 +474,6 @@ const textlang = { }, }; - module.exports = { MYAPPS: [], INITDB_FIRSTIME: true, @@ -549,7 +544,7 @@ module.exports = { intcode: 5000, multioption: 6000, onlydate: 7000, - hours: 8000 + hours: 8000, }, MAX_PHASES: 5, @@ -558,9 +553,9 @@ module.exports = { gettranslate(text, lang) { try { - return textlang[lang][text] + return textlang[lang][text]; } catch (e) { - return textlang['it'][text] + return textlang['it'][text]; } }, @@ -568,95 +563,186 @@ module.exports = { // ++Todo: res estrarre la lingua let lang = ''; try { - lang = res.lang + lang = res.lang; } catch (e) { } if (!lang) { lang = 'it'; } - return lang + return lang; }, get__(text, lang) { try { - return textlang[lang][text] + return textlang[lang][text]; } catch (e) { - return textlang['it'][text] + return textlang['it'][text]; } }, getres__(text, res) { let lang = this.getlangbyres(res); try { - return textlang[lang][text] + return textlang[lang][text]; } catch (e) { - return textlang['it'][text] + return textlang['it'][text]; } }, - getHostname: function () { - return os.hostname() + getHostname: function() { + return os.hostname(); }, - testing: function () { - return (process.env.TESTING_ON === '1') + testing: function() { + return (process.env.TESTING_ON === '1'); }, - mylog: function (...args) { + mylog: function(...args) { if (!this.testing()) - console.log(args) + console.log(args); }, - mylogoff: function (...args) { + mylogoff: function(...args) { // doing nothing }, - mylogshow: function (...args) { - console.log(args) + mylogshow: function(...args) { + console.log(args); }, - mylogserr: function (...args) { - console.error(args) + mylogserr: function(...args) { + console.error(args); }, - allfieldSendMsg: function () { - return ['userId', 'source', 'dest', 'message', 'datemsg', 'read', 'deleted', 'origin', 'idapp', 'status', 'options'] + allfieldSendMsg: function() { + return [ + 'userId', + 'source', + 'dest', + 'message', + 'datemsg', + 'read', + 'deleted', + 'origin', + 'idapp', + 'status', + 'options']; }, - allfieldTodo: function () { - return ['userId', 'pos', 'category', 'descr', 'note', 'priority', 'statustodo', 'assignedToUsers', 'created_at', 'groupId', 'modify_at', - 'completed_at', 'expiring_at', 'enableExpiring', 'progress', 'modified', 'phase', 'assigned_to_userId', 'assignedToUsers', 'hoursplanned', 'hoursworked', 'start_date', 'themecolor', 'themebgcolor'] + allfieldTodo: function() { + return [ + 'userId', + 'pos', + 'category', + 'descr', + 'note', + 'priority', + 'statustodo', + 'assignedToUsers', + 'created_at', + 'groupId', + 'modify_at', + 'completed_at', + 'expiring_at', + 'enableExpiring', + 'progress', + 'modified', + 'phase', + 'assigned_to_userId', + 'assignedToUsers', + 'hoursplanned', + 'hoursworked', + 'start_date', + 'themecolor', + 'themebgcolor']; }, - allfieldMyEvent: function () { - return ['userId',] + allfieldMyEvent: function() { + return ['userId']; }, - allfieldTodoWithId: function () { - return ['_id', ...this.allfieldTodo()] + allfieldTodoWithId: function() { + return ['_id', ...this.allfieldTodo()]; }, // #TODO Projects++ Add fields ... - allfieldProject: function () { - return ['idapp', 'userId', 'respUsername', 'viceRespUsername', 'pos', 'typeproj', 'id_main_project', 'id_parent', 'descr', 'longdescr', 'groupId', 'hoursplanned', 'hoursleft', 'themecolor', 'themebgcolor', 'hoursworked', 'priority', 'statusproj', 'created_at', 'modify_at', - 'completed_at', 'expiring_at', 'enableExpiring', 'progressCalc', 'modified', 'live_url', 'test_url', 'begin_development', 'begin_test', 'totalphases', 'actualphase', 'hoursweeky_plannedtowork', 'endwork_estimate' - , 'privacyread', 'privacywrite', 'tipovisu', 'view'] + allfieldProject: function() { + return [ + 'idapp', + 'userId', + 'respUsername', + 'viceRespUsername', + 'pos', + 'typeproj', + 'id_main_project', + 'id_parent', + 'descr', + 'longdescr', + 'groupId', + 'hoursplanned', + 'hoursleft', + 'themecolor', + 'themebgcolor', + 'hoursworked', + 'priority', + 'statusproj', + 'created_at', + 'modify_at', + 'completed_at', + 'expiring_at', + 'enableExpiring', + 'progressCalc', + 'modified', + 'live_url', + 'test_url', + 'begin_development', + 'begin_test', + 'totalphases', + 'actualphase', + 'hoursweeky_plannedtowork', + 'endwork_estimate' + , + 'privacyread', + 'privacywrite', + 'tipovisu', + 'view']; }, - allfieldBooking: function () { - return ['idapp', 'userId', 'id_bookedevent', 'numpeople', 'numpeopleLunch', 'numpeopleDinner', 'numpeopleDinnerShared', 'msgbooking', 'modified', 'infoevent', 'datebooked', 'booked'] + allfieldBooking: function() { + return [ + 'idapp', + 'userId', + 'id_bookedevent', + 'numpeople', + 'numpeopleLunch', + 'numpeopleDinner', + 'numpeopleDinnerShared', + 'msgbooking', + 'modified', + 'infoevent', + 'datebooked', + 'booked']; }, - allfieldBookingChange: function () { - return ['numpeople', 'numpeopleLunch', 'numpeopleDinner', 'numpeopleDinnerShared', 'msgbooking', 'modified', 'infoevent', 'datebooked', 'booked'] + allfieldBookingChange: function() { + return [ + 'numpeople', + 'numpeopleLunch', + 'numpeopleDinner', + 'numpeopleDinnerShared', + 'msgbooking', + 'modified', + 'infoevent', + 'datebooked', + 'booked']; }, - allfieldProjectWithId: function () { - return ['_id', ...this.allfieldProject()] + allfieldProjectWithId: function() { + return ['_id', ...this.allfieldProject()]; }, jsonCopy(src) { - return JSON.parse(JSON.stringify(src)) + return JSON.parse(JSON.stringify(src)); }, CloneRecordToNew(src) { @@ -664,29 +750,43 @@ module.exports = { delete myrec._doc['_id']; myrec._id = new ObjectID(); - return myrec._doc + return myrec._doc; }, - sendBackNotif: function (subscription, payload) { + sendBackNotif: function(subscription, payload) { console.log('sendBackNotif:', subscription, payload); + + const pushOptions = { + vapidDetails: { + subject: process.env.VAPI_KEY_SUBJECT, + privateKey: process.env.PRIVATE_VAPI_KEY, + publicKey: process.env.PUBLIC_VAPI_KEY, + }, + TTL: payload.ttl, + headers: {} + }; + // Pass object into sendNotification - return webpush.sendNotification(subscription, JSON.stringify(payload)) - .catch(err => { - if (err.statusCode === 410) { - // Gone: is not valid anymore (Expired probably!), so I have to delete from my db - return Subscription.findOneAndRemove({ _id: subscription._id }) - } else { - console.log('Subscription is no longer valid: ', err); - } - }) - .then(ris => { - // console.log('ris', ris) - }) - .catch(err => console.error(err)) + return webpush.sendNotification(subscription, JSON.stringify(payload), pushOptions). + catch(err => { + if (err.statusCode === 410) { + // Gone: is not valid anymore (Expired probably!), so I have to delete from my db + return Subscription.findOneAndRemove({_id: subscription._id}); + } else { + console.log('Subscription is no longer valid: ', err); + } + }). + then(ris => { + // console.log('ris', ris) + }). + catch(err => { + console.error(err); + }); }, - sendNotificationToUser: function (userId, title, content, openUrl, openUrl2, tag, actions) { + sendNotificationToUser: function( + userId, title, content, openUrl, openUrl2, tag, actions) { let payload = { actions, @@ -702,7 +802,7 @@ module.exports = { // tag: req.body.tag }; - return Subscription.find({ userId }, (err, subscriptions) => { + return Subscription.find({userId}, (err, subscriptions) => { if (err) { console.error(`Error occurred while getting subscriptions`); // res.status(500).json({ @@ -721,23 +821,22 @@ module.exports = { endpoint: subscription.endpoint, keys: { p256dh: subscription.keys.p256dh, - auth: subscription.keys.auth - } + auth: subscription.keys.auth, + }, }; conta++; - const parse = require('url-parse'); const parsedUrl = parse(subscription.endpoint); const audience = parsedUrl.protocol + '//' + parsedUrl.hostname; const vapidHeaders = webpush.getVapidHeaders( - audience, - process.env.VAPI_KEY_SUBJECT, - process.env.PUBLIC_VAPI_KEY, - process.env.PRIVATE_VAPI_KEY, - 'aes128gcm' + audience, + process.env.VAPI_KEY_SUBJECT, + process.env.PUBLIC_VAPI_KEY, + process.env.PRIVATE_VAPI_KEY, + 'aes128gcm', ); const pushOptions = { @@ -747,35 +846,35 @@ module.exports = { publicKey: process.env.PUBLIC_VAPI_KEY, }, TTL: payload.ttl, - headers: vapidHeaders + headers: vapidHeaders, }; - console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', conta, '/', trovati, 'A', subscription.browser); - + console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', + conta, '/', trovati, 'A', subscription.browser); const pushPayload = JSON.stringify(payload); webpush.sendNotification( - pushSubscription, - pushPayload, - pushOptions + pushSubscription, + pushPayload, + pushOptions, ).then((value) => { // console.log('Invio Push', value); resolve({ status: true, endpoint: subscription.endpoint, - data: value + data: value, }); }).catch((err) => { - console.error('err Push', err.message) + console.error('err Push', err.body); reject({ status: false, endpoint: subscription.endpoint, - data: err + data: err, }); }); }).catch(error => { - console.log('ERROR: sendNotificationToUser', error) + console.log('ERROR: sendNotificationToUser', error); }); }); // q.allSettled(parallelSubscriptionCalls).then((pushResults) => { @@ -844,22 +943,22 @@ module.exports = { */ sendNotifToAdmin(title, msg, tag = '') { - const { User } = require('../models/user'); + const {User} = require('../models/user'); // console.log('nomeapp 1: ' , this.getNomeAppByIdApp(1)); // console.log('nomeapp 2: ' , this.getNomeAppByIdApp(2)); - User.find({ username: 'paoloar77', idapp: '1' }).then((arrusers) => { + User.find({username: 'paoloar77', idapp: '1'}).then((arrusers) => { if (arrusers !== null) { for (const user of arrusers) { - this.sendNotificationToUser(user._id, title, msg, '/', '', tag, []) - .then(ris => { - if (ris) { + this.sendNotificationToUser(user._id, title, msg, '/', '', tag, []). + then(ris => { + if (ris) { - } else { - // already sent the error on calling sendNotificationToUser - } - }) + } else { + // already sent the error on calling sendNotificationToUser + } + }); } } }); @@ -871,9 +970,13 @@ module.exports = { if (String(userpassed) !== String(userauth)) { // I'm trying to write something not mine! this.mylog('userId = ', userpassed, 'req.user._id', userauth); - return { exit: true, ret: res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }) } + return { + exit: true, + ret: res.status(404). + send({code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER}), + }; } else { - return { exit: false, ret: false } + return {exit: false, ret: false}; } }, @@ -886,7 +989,7 @@ module.exports = { msg = msg.replace('&', '&'); msg = msg.replace('
', '\n'); - return msg + return msg; }, convertTexttoHtml(myhtml) { @@ -902,47 +1005,47 @@ module.exports = { let msg = myhtml; msg = msg.replace(/"/g, '\''); - return msg + return msg; }, - getNomeAppByIdApp: function (idapp) { + getNomeAppByIdApp: function(idapp) { const myapp = - this.getApps().find(item => item.idapp === idapp); + this.getApps().find(item => item.idapp === idapp); if (myapp) return myapp.name; else return ''; }, - getHostByIdApp: function (idapp) { + getHostByIdApp: function(idapp) { const myapp = - this.getApps().find(item => item.idapp === idapp); + this.getApps().find(item => item.idapp === idapp); if (myapp) { - let siteport = (myapp.portapp !== "0") ? (':' + myapp.portapp) : ""; + let siteport = (myapp.portapp !== '0') ? (':' + myapp.portapp) : ''; return myapp.host + siteport; } else return ''; }, - isAbilitaNave: function (idapp) { + isAbilitaNave: function(idapp) { const myapp = this.getApps().find(item => item.idapp === idapp); return myapp.abilitanave; }, - getdirByIdApp: function (idapp) { + getdirByIdApp: function(idapp) { const myapp = - this.getApps().find(item => item.idapp === idapp); + this.getApps().find(item => item.idapp === idapp); if (myapp) { return myapp.dir; } else return ''; }, - getAdminEmailByIdApp: function (idapp) { + getAdminEmailByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); if (myapp) return myapp.adminemail; @@ -950,7 +1053,7 @@ module.exports = { return ''; }, - getreplyToEmailByIdApp: function (idapp) { + getreplyToEmailByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); if (myapp) return myapp.replyTo; @@ -958,7 +1061,7 @@ module.exports = { return ''; }, - getpathregByIdApp: function (idapp, lang) { + getpathregByIdApp: function(idapp, lang) { const myapp = this.getApps().find((item) => item.idapp === idapp); if (myapp) { const addstr = myapp.pathreg_add ? myapp.pathreg_add : ''; @@ -974,7 +1077,7 @@ module.exports = { return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== ''); }, - getManagerEmailByIdApp: function (idapp) { + getManagerEmailByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); if (myapp) return !!myapp.manageremail ? myapp.manageremail : ''; @@ -982,25 +1085,25 @@ module.exports = { return ''; }, - getEmailByIdApp: function (idapp) { + getEmailByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); - return (myapp) ? myapp.email_from : '' + return (myapp) ? myapp.email_from : ''; }, - getPwdByIdApp: function (idapp) { + getPwdByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); - return (myapp) ? this.decryptdata(myapp.email_pwd) : '' + return (myapp) ? this.decryptdata(myapp.email_pwd) : ''; }, - getTelegramBotNameByIdApp: function (idapp) { + getTelegramBotNameByIdApp: function(idapp) { const myapp = this.getApps().find((item) => item.idapp === idapp); - return (myapp) ? myapp.telegram_bot_name : '' + return (myapp) ? myapp.telegram_bot_name : ''; }, - getTelegramKeyByIdApp: function (idapp) { + getTelegramKeyByIdApp: function(idapp) { const myarr = this.getApps(); const myapp = myarr.find((item) => item.idapp === idapp); - return (myapp) ? myapp.telegram_key : '' + return (myapp) ? myapp.telegram_key : ''; }, getQueryTable(idapp, params) { @@ -1008,16 +1111,16 @@ module.exports = { // console.table(params); if (typeof params.startRow !== 'number') { - throw new Error('startRow must be number') + throw new Error('startRow must be number'); } else if (typeof params.endRow !== 'number') { - throw new Error('endRow must be number') + throw new Error('endRow must be number'); } let query = []; if (params.filter && params.fieldsearch) { let myregexp = {}; - myregexp = new RegExp(params.filter.trim().replace(' ', '|'), "ig"); + myregexp = new RegExp(params.filter.trim().replace(' ', '|'), 'ig'); const myfilters = []; params.fieldsearch.forEach((rec) => { @@ -1026,15 +1129,16 @@ module.exports = { data[rec.field] = params.filter.trim(); } else if (rec.type === this.FieldType.string) { data[rec.field] = myregexp; - } else if ((rec.type === this.FieldType.number) || (rec.type === this.FieldType.hours)) { + } else if ((rec.type === this.FieldType.number) || + (rec.type === this.FieldType.hours)) { data[rec.field] = parseFloat(params.filter.trim()); } myfilters.push(data); }); query = [ - { $match: { $or: myfilters } }, - ] + {$match: {$or: myfilters}}, + ]; } let filtriadded = []; @@ -1048,101 +1152,116 @@ module.exports = { if (params.filterand) { - if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) - filtriadded.push({ registered: false }); + if (params.filterand.includes( + shared_consts.FILTER_EXTRALIST_NOT_REGISTERED)) + filtriadded.push({registered: false}); - if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { - filtriadded.push({ contacted: { $exists: false } }); + if (params.filterand.includes( + shared_consts.FILTER_EXTRALIST_NOT_CONTACTED)) { + filtriadded.push({contacted: {$exists: false}}); } if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_WITH_NOTE)) filtriadded.push({ - 'note': { $exists: true }, - "$expr": { "$gt": [{ "$strLenCP": "$note" }, 1] } + 'note': {$exists: true}, + '$expr': {'$gt': [{'$strLenCP': '$note'}, 1]}, }); if (params.filterand.includes(shared_consts.FILTER_QUALIFIED)) - filtriadded.push({ 'profile.qualified': true }); + filtriadded.push({'profile.qualified': true}); if (params.filterand.includes(shared_consts.FILTER_USER_NO_ZOOM)) - filtriadded.push({ 'profile.saw_zoom_presentation': false }); + filtriadded.push({'profile.saw_zoom_presentation': false}); if (params.filterand.includes(shared_consts.FILTER_ASK_ZOOM_VISTO)) - filtriadded.push({ 'profile.ask_zoom_partecipato': false }); + filtriadded.push({'profile.ask_zoom_partecipato': false}); if (params.filterand.includes(shared_consts.FILTER_USER_NO_INVITANTE)) filtriadded.push({ - aportador_solidario: { $exists: false } + aportador_solidario: {$exists: false}, }); if (params.filterand.includes(shared_consts.FILTER_USER_NO_TELEGRAM_ID)) - filtriadded.push({ 'profile.teleg_id': { $lt: 1 } }); - if (params.filterand.includes(shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) - filtriadded.push({ 'profile.teleg_checkcode': { $gt: 1 } }); - if (params.filterand.includes(shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) - filtriadded.push({ verified_email: false }); + filtriadded.push({'profile.teleg_id': {$lt: 1}}); + if (params.filterand.includes( + shared_consts.FILTER_USER_CODICE_AUTH_TELEGRAM)) + filtriadded.push({'profile.teleg_checkcode': {$gt: 1}}); + if (params.filterand.includes( + shared_consts.FILTER_USER_NO_EMAIL_VERIFICATA)) + filtriadded.push({verified_email: false}); if (params.filterand.includes(shared_consts.FILTER_USER_NO_DREAM)) filtriadded.push({ 'profile.my_dream': { - $exists: false - } + $exists: false, + }, }); if (params.filterand.includes(shared_consts.FILTER_USER_TELEGRAM_BLOCKED)) - filtriadded.push({ 'profile.teleg_id_old': { $gt: 1 } }); + filtriadded.push({'profile.teleg_id_old': {$gt: 1}}); if (params.filterand.includes(shared_consts.FILTER_ATTIVI)) filtriadded.push({ - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] + $or: [ + {deleted: {$exists: false}}, + {deleted: {$exists: true, $eq: false}}], }); // Hours if (params.filterand.includes(shared_consts.FILTER_HOURS_ALL)) filtriadded.push( - { - idapp, - todoId: params.codeId, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - } + { + idapp, + todoId: params.codeId, + $or: [ + {deleted: {$exists: false}}, + {deleted: {$exists: true, $eq: false}}], + }, ); else if (params.filterand.includes(shared_consts.FILTER_HOURS_MYLIST)) filtriadded.push( - { - idapp, - userId: params.userId, - todoId: params.codeId, - $or: [{ deleted: { $exists: false } }, { deleted: { $exists: true, $eq: false } }] - } + { + idapp, + userId: params.userId, + todoId: params.codeId, + $or: [ + {deleted: {$exists: false}}, + {deleted: {$exists: true, $eq: false}}], + }, ); if (params.filterand.includes(shared_consts.FILTER_NASCOSTI)) filtriadded.push({ - deleted: { $exists: true, $eq: true } + deleted: {$exists: true, $eq: true}, }); if (params.filterand.includes(shared_consts.FILTER_NAVI_NON_PRESENTI)) filtriadded.push({ - navinonpresenti: { $exists: true, $eq: true }, - $or: [{ subaccount: { $exists: false } }, { subaccount: { $exists: true, $eq: false } }] + navinonpresenti: {$exists: true, $eq: true}, + $or: [ + {subaccount: {$exists: false}}, + {subaccount: {$exists: true, $eq: false}}], }); // Iscritti Conacreis if (params.filterand.includes(shared_consts.FILTER_MISSING_PAYMENT)) filtriadded.push({ - $or: [{ ha_pagato: { $exists: false } }, { ha_pagato: { $exists: true, $lt: 1 } }] + $or: [ + {ha_pagato: {$exists: false}}, + {ha_pagato: {$exists: true, $lt: 1}}], }); - if (params.filterand.includes(shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) + if (params.filterand.includes( + shared_consts.FILTER_TO_MAKE_MEMBERSHIP_CARD)) filtriadded.push({ - $or: [{ codiceConacreis: { $exists: false } }, { codiceConacreis: { $exists: true, $eq: '' } }] + $or: [ + {codiceConacreis: {$exists: false}}, + {codiceConacreis: {$exists: true, $eq: ''}}], }); if (params.filterand.includes(shared_consts.FILTER_MEMBERSHIP_CARD_OK)) filtriadded.push({ - codiceConacreis: { $exists: true }, - "$expr": { "$gt": [{ "$strLenCP": "$codiceConacreis" }, 0] } + codiceConacreis: {$exists: true}, + '$expr': {'$gt': [{'$strLenCP': '$codiceConacreis'}, 0]}, }); - } - if (filtriadded.length > 0) - query.push({ $match: { $and: filtriadded } }); + query.push({$match: {$and: filtriadded}}); if (idapp > 0) { - query.push({ $match: { idapp } }); + query.push({$match: {idapp}}); } // console.log('QUERYMATCH', query[0].$match.or); @@ -1150,10 +1269,10 @@ module.exports = { if (params.sortBy) { // maybe we want to sort by blog title or something - const mysort = { $sort: params.sortBy }; + const mysort = {$sort: params.sortBy}; // console.log('sortBy', params.sortBy); // console.table(mysort); - query.push(mysort) + query.push(mysort); } let numrowend = params.endRow - params.startRow; @@ -1163,45 +1282,53 @@ module.exports = { let mylkLF = params.lk_LF; if (params.af_objId_tab) { query.push( - { "$addFields": { "myId": { "$toObjectId": '$' + params.lk_LF } } } + {'$addFields': {'myId': {'$toObjectId': '$' + params.lk_LF}}}, ); mylkLF = 'myId'; } if (params.lk_tab) { query.push( - { - $lookup: { - from: params.lk_tab, - localField: mylkLF, // field in my collection - foreignField: params.lk_FF, // field in the 'from' collection - as: params.lk_as - } - }, - { - $replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ['$' + params.lk_as, 0] }, "$$ROOT"] } } - }, - { $project: params.lk_proj } + { + $lookup: { + from: params.lk_tab, + localField: mylkLF, // field in my collection + foreignField: params.lk_FF, // field in the 'from' collection + as: params.lk_as, + }, + }, + { + $replaceRoot: { + newRoot: { + $mergeObjects: [ + { + $arrayElemAt: [ + '$' + params.lk_as, 0], + }, '$$ROOT'], + }, + }, + }, + {$project: params.lk_proj}, ); } query.push( - { - $group: { - _id: null, - // get a count of every result that matches until now - count: { $sum: 1 }, - // keep our results for the next operation - results: { $push: '$$ROOT' } - } - }, - // and finally trim the results to within the range given by start/endRow - { - $project: { - count: 1, - rows: { $slice: ['$results', params.startRow, numrowend] } - } - } + { + $group: { + _id: null, + // get a count of every result that matches until now + count: {$sum: 1}, + // keep our results for the next operation + results: {$push: '$$ROOT'}, + }, + }, + // and finally trim the results to within the range given by start/endRow + { + $project: { + count: 1, + rows: {$slice: ['$results', params.startRow, numrowend]}, + }, + }, ); // console.log('query', query); @@ -1218,9 +1345,9 @@ module.exports = { if (ris) { // console.table(ris.rows); // console.log('ROW ', ris.count); - return ({ count: ris.count, rows: ris.rows }) + return ({count: ris.count, rows: ris.rows}); } else { - return ({ count: 0, rows: [] }) + return ({count: 0, rows: []}); } }, @@ -1259,14 +1386,13 @@ module.exports = { } }, - isBitActive(bit, whattofind) { - return ((bit & whattofind) === whattofind) + return ((bit & whattofind) === whattofind); }, SetBit(myval, bit) { myval = myval & bit; - return myval + return myval; }, async snooze(ms) { @@ -1276,7 +1402,7 @@ module.exports = { IncDateNow(secs) { let mydate = new Date(new Date().getTime() + secs); // console.log('mydate', mydate); - return mydate + return mydate; }, isdiffSecDateLess(mydatediffstr, secs) { @@ -1295,12 +1421,12 @@ module.exports = { isMonToSat() { const dayOfWeek = new Date(new Date()).getDay(); - return dayOfWeek >= 1 && dayOfWeek <= 6 + return dayOfWeek >= 1 && dayOfWeek <= 6; }, isMonToFri() { const dayOfWeek = new Date(new Date()).getDay(); - return dayOfWeek >= 1 && dayOfWeek <= 5 + return dayOfWeek >= 1 && dayOfWeek <= 5; }, // var startTime = '15:10:10'; @@ -1310,15 +1436,14 @@ module.exports = { currentDate = new Date(); startDate = new Date(currentDate.getTime()); - startDate.setHours(startTime.split(":")[0]); - startDate.setMinutes(startTime.split(":")[1]); - startDate.setSeconds(startTime.split(":")[2]); + startDate.setHours(startTime.split(':')[0]); + startDate.setMinutes(startTime.split(':')[1]); + startDate.setSeconds(startTime.split(':')[2]); endDate = new Date(currentDate.getTime()); - endDate.setHours(endTime.split(":")[0]); - endDate.setMinutes(endTime.split(":")[1]); - endDate.setSeconds(endTime.split(":")[2]); - + endDate.setHours(endTime.split(':')[0]); + endDate.setMinutes(endTime.split(':')[1]); + endDate.setSeconds(endTime.split(':')[2]); valid = startDate < currentDate && endDate > currentDate; @@ -1361,7 +1486,7 @@ module.exports = { idapp, riga, col, - numup + numup, }; if (idapp === this.AYNI) { @@ -1386,9 +1511,9 @@ module.exports = { appendLeadingZeroes(n) { if (n <= 9) { - return "0" + n; + return '0' + n; } - return n + return n; }, getWeekDayByLangByNumCar(date, lang, num) { @@ -1398,54 +1523,109 @@ module.exports = { const dayOfWeek = new Date(date).getDay(); const myday = { - it: ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'], - enUs: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], - fr: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], - es: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'iernes', 'Sábado'], - pt: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'], - de: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], - si: ['Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'četrtek', 'Petek', 'Sobota'], + it: [ + 'Domenica', + 'Lunedì', + 'Martedì', + 'Mercoledì', + 'Giovedì', + 'Venerdì', + 'Sabato'], + enUs: [ + 'Sunday', + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday'], + fr: [ + 'Dimanche', + 'Lundi', + 'Mardi', + 'Mercredi', + 'Jeudi', + 'Vendredi', + 'Samedi'], + es: [ + 'Domingo', + 'Lunes', + 'Martes', + 'Miércoles', + 'Jueves', + 'iernes', + 'Sábado'], + pt: [ + 'Domingo', + 'Segunda', + 'Terça', + 'Quarta', + 'Quinta', + 'Sexta', + 'Sábado'], + de: [ + 'Sonntag', + 'Montag', + 'Dienstag', + 'Mittwoch', + 'Donnerstag', + 'Freitag', + 'Samstag'], + si: [ + 'Nedelja', + 'Ponedeljek', + 'Torek', + 'Sreda', + 'četrtek', + 'Petek', + 'Sobota'], }; if (num > 0) { - return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek].substring(0, num) + return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek].substring(0, num); } else { - return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek] + return isNaN(dayOfWeek) ? '' : myday[lang][dayOfWeek]; } }, isSunday(mydate) { - const dayOfWeek = new Date(mydate).getDay() - return dayOfWeek === 0 + const dayOfWeek = new Date(mydate).getDay(); + return dayOfWeek === 0; }, isMonday(mydate) { - const dayOfWeek = new Date(mydate).getDay() - return dayOfWeek === 1 + const dayOfWeek = new Date(mydate).getDay(); + return dayOfWeek === 1; }, isSundayDate(mydate) { - const dayOfWeek = mydate.getDay() - return dayOfWeek === 0 + const dayOfWeek = mydate.getDay(); + return dayOfWeek === 0; }, isMondayDate(mydate) { - const dayOfWeek = mydate.getDay() - return dayOfWeek === 1 + const dayOfWeek = mydate.getDay(); + return dayOfWeek === 1; }, getWeekDayByLang(date, lang) { - return this.getWeekDayByLangByNumCar(date, lang, 3) + return this.getWeekDayByLangByNumCar(date, lang, 3); }, getWeekDayByLangTot(date, lang) { - return this.getWeekDayByLangByNumCar(date, lang, 0) + return this.getWeekDayByLangByNumCar(date, lang, 0); }, getWeekDay(date) { //Create an array containing each day, starting with Sunday. const weekdays = [ - "Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedí", "Venerdì", "Sabato" + 'Domenica', + 'Lunedì', + 'Martedì', + 'Mercoledì', + 'Giovedí', + 'Venerdì', + 'Sabato', ]; //Use the getDay() method to get the day. const day = date.getDay(); @@ -1456,7 +1636,11 @@ module.exports = { getstrDateTimeShort(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + this.appendLeadingZeroes(mydate.getHours()) + ':' + this.appendLeadingZeroes(mydate.getMinutes()); + return this.getWeekDayByLang(mydate, lang) + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + ' ORE ' + + this.appendLeadingZeroes(mydate.getHours()) + ':' + + this.appendLeadingZeroes(mydate.getMinutes()); } else { return ''; } @@ -1465,7 +1649,9 @@ module.exports = { getstrDateShort(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang).substring(0, 3) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1); + return this.getWeekDayByLang(mydate, lang).substring(0, 3) + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1); } else { return ''; } @@ -1474,7 +1660,9 @@ module.exports = { getstrDate_DD_MM_YYYY(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + this.appendLeadingZeroes(mydate.getFullYear()); + return this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + this.appendLeadingZeroes(mydate.getFullYear()); } else { return ''; } @@ -1483,7 +1671,9 @@ module.exports = { getstrDateYYYY_MM_DD(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getFullYear() + '-' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + this.appendLeadingZeroes(mydate.getDate()) + return mydate.getFullYear() + '-' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getDate()); } else { return ''; } @@ -1492,7 +1682,9 @@ module.exports = { getstrUTCDateYYYY_MM_DD(mydate) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getUTCFullYear() + '-' + this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + '-' + this.appendLeadingZeroes(mydate.getUTCDate()) + return mydate.getUTCFullYear() + '-' + + this.appendLeadingZeroes(mydate.getUTCMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getUTCDate()); } else { return ''; } @@ -1501,7 +1693,10 @@ module.exports = { getstrDateLong(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLang(mydate, lang) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + mydate.getFullYear(); + return this.getWeekDayByLang(mydate, lang) + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + mydate.getFullYear(); } else { return ''; } @@ -1510,7 +1705,10 @@ module.exports = { getstrDateLongTot(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return this.getWeekDayByLangTot(mydate, lang) + ' ' + this.appendLeadingZeroes(mydate.getDate()) + '/' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + mydate.getFullYear(); + return this.getWeekDayByLangTot(mydate, lang) + ' ' + + this.appendLeadingZeroes(mydate.getDate()) + '/' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '/' + + mydate.getFullYear(); } else { return ''; } @@ -1519,7 +1717,10 @@ module.exports = { getstrDateLongFile(mydate, lang) { if (mydate) { // console.log('getstrDate', mytimestamp) - return mydate.getFullYear() + '-' + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + this.appendLeadingZeroes(mydate.getDate()) + ' (' + this.getWeekDayByLang(mydate, lang) + ')' + return mydate.getFullYear() + '-' + + this.appendLeadingZeroes(mydate.getMonth() + 1) + '-' + + this.appendLeadingZeroes(mydate.getDate()) + ' (' + + this.getWeekDayByLang(mydate, lang) + ')'; } else { return ''; } @@ -1530,7 +1731,7 @@ module.exports = { rec = { typeconf: this.TYPECONF_ZOOM, id_conf_zoom: '', - } + }; } let typeconf = rec.typeconf; if (typeconf === '') @@ -1544,7 +1745,7 @@ module.exports = { rec.id_conf_zoom = '6668882000'; } - return mylink + rec.id_conf_zoom + return mylink + rec.id_conf_zoom; }, @@ -1553,7 +1754,7 @@ module.exports = { }, getHash(mystr) { - return CryptoJS.SHA512(mystr, { outputLength: 256 }).toString(); + return CryptoJS.SHA512(mystr, {outputLength: 256}).toString(); }, encrypt(msg, pass) { @@ -1561,7 +1762,7 @@ module.exports = { var key = CryptoJS.PBKDF2(pass, salt, { keySize: keySize / 32, - iterations: iterations + iterations: iterations, }); var iv = CryptoJS.lib.WordArray.random(128 / 8); @@ -1569,7 +1770,7 @@ module.exports = { var encrypted = CryptoJS.AES.encrypt(msg, key, { iv: iv, padding: CryptoJS.pad.Pkcs7, - mode: CryptoJS.mode.CBC + mode: CryptoJS.mode.CBC, }); @@ -1581,18 +1782,18 @@ module.exports = { decrypt(transitmessage, pass) { var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32)); - var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32)) + var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32)); var encrypted = transitmessage.substring(64); var key = CryptoJS.PBKDF2(pass, salt, { keySize: keySize / 32, - iterations: iterations + iterations: iterations, }); var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, padding: CryptoJS.pad.Pkcs7, - mode: CryptoJS.mode.CBC + mode: CryptoJS.mode.CBC, }); return decrypted; @@ -1604,20 +1805,20 @@ module.exports = { return this.encrypt(mydata, process.env.SECRK); }, - decryptdata(mydatacrypted) { // Decrypt // const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK); // return JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); - return this.decrypt(mydatacrypted, process.env.SECRK).toString(CryptoJS.enc.Utf8); + return this.decrypt(mydatacrypted, process.env.SECRK). + toString(CryptoJS.enc.Utf8); }, BoolToInt(mybool) { - return (mybool) ? -1 : 0 + return (mybool) ? -1 : 0; }, StrToBool(mystr) { - return (mystr === '-1') ? true : false + return (mystr === '-1') ? true : false; }, writelogfile(mystr, filename) { @@ -1628,7 +1829,7 @@ module.exports = { mystr = this.getstrDateTimeShort(new Date(), 'it') + ': ' + mystr; - const stream = fs.createWriteStream(filename, { flags: 'a' }); + const stream = fs.createWriteStream(filename, {flags: 'a'}); stream.write('\n' + mystr); stream.end(); }, @@ -1678,7 +1879,7 @@ module.exports = { move(oldPath, newPath, callback) { - fs.rename(oldPath, newPath, function (err) { + fs.rename(oldPath, newPath, function(err) { if (err) { if (err.code === 'EXDEV') { copy(); @@ -1697,7 +1898,7 @@ module.exports = { readStream.on('error', callback); writeStream.on('error', callback); - readStream.on('close', function () { + readStream.on('close', function() { fs.unlink(oldPath, callback); }); @@ -1707,11 +1908,11 @@ module.exports = { delete(path, callback) { - fs.unlink(path, function (err) { + fs.unlink(path, function(err) { if (err) { console.error(err); callback(err); - return + return; } callback(); }); @@ -1721,7 +1922,7 @@ module.exports = { // if (!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK)) { if (!fs.existsSync(dirPath)) { try { - fs.mkdirSync(dirPath, { recursive: true }); + fs.mkdirSync(dirPath, {recursive: true}); } catch (e) { if (dirPath !== path.dirname(dirPath)) { const myname = path.dirname(dirPath); @@ -1735,7 +1936,7 @@ module.exports = { extractNameAndSurnameByComplete(name_complete) { const suffissoCognome = ['Del', 'La', 'De', 'Lo']; - let campi = name_complete.split(" "); + let campi = name_complete.split(' '); let namesurname = { name: '', surname: '', @@ -1747,40 +1948,40 @@ module.exports = { } else if (campi.length === 3) { if (suffissoCognome.includes(campi[1])) { namesurname.name = campi[0]; - namesurname.surname = campi[1] + " " + campi[2]; + namesurname.surname = campi[1] + ' ' + campi[2]; } else { - namesurname.name = campi[0] + " " + campi[1]; + namesurname.name = campi[0] + ' ' + campi[1]; namesurname.surname = campi[2]; } } else if (campi.length === 4) { - namesurname.name = campi[0] + " " + campi[1]; - namesurname.surname = campi[2] + " " + campi[3]; + namesurname.name = campi[0] + ' ' + campi[1]; + namesurname.surname = campi[2] + ' ' + campi[3]; } else if (campi.length > 4) { - namesurname.name = campi[0] + " " + campi[1]; - namesurname.surname = " " + campi[2]; + namesurname.name = campi[0] + ' ' + campi[1]; + namesurname.surname = ' ' + campi[2]; for (let ind = 3; ind < campi.length; ind++) { - namesurname.surname += " " + campi[ind]; + namesurname.surname += ' ' + campi[ind]; } } - return namesurname + return namesurname; }, getiPAddressUser(req) { try { const striniziale = '::ffff:'; if (req.ip.indexOf(striniziale) >= 0) { - return req.ip.substring(striniziale.length) + return req.ip.substring(striniziale.length); } else { return req.ip; // Express } } catch (e) { - return '' + return ''; } }, removespaces(mystr) { - return mystr.replace(/\s+/g, '') + return mystr.replace(/\s+/g, ''); }, ModificheConsentite(table, fieldsvalue, idrec, user) { @@ -1796,7 +1997,7 @@ module.exports = { } if ('ALL' in fieldsvalue) { //++Todo: Cancellalo solo se sono io il creatore dell'utente ... o se posso! - return true + return true; } } @@ -1804,7 +2005,8 @@ module.exports = { }, NotifyIfDelRecord(table) { - if ((table === 'users') || (table === 'extralist') || (table === 'listaingressos') || (table === 'graduatorias')) { + if ((table === 'users') || (table === 'extralist') || + (table === 'listaingressos') || (table === 'graduatorias')) { return true; } @@ -1812,18 +2014,18 @@ module.exports = { }, getFirstWord(mystr) { - const myarr = mystr.split(" "); + const myarr = mystr.split(' '); if (myarr.length > 0) return myarr[0]; else - return mystr + return mystr; }, getFirst2Car(mystr) { if (!!mystr) return mystr.substring(0, 2) + '.'; else - return '' + return ''; }, getmaxcol(riga) { @@ -1835,7 +2037,7 @@ module.exports = { let ris = ((Math.ceil(col / 8) - 1) * 8) + 1; if (ris <= 0) ris = 1; - return ris + return ris; }, getPrimaColFlotta(col) { @@ -1843,7 +2045,7 @@ module.exports = { let ris = ((Math.ceil(col / 64) - 1) * 64) + 1; if (ris <= 0) ris = 1; - return ris + return ris; }, getStrMsgByTipoMsg(tipomsg) { @@ -1898,52 +2100,52 @@ module.exports = { for (i = 0, len = str.length; i < len; i++) { code = str.charCodeAt(i); if (!(code > 47 && code < 58) && // numeric (0-9) - !(code > 64 && code < 91) && // upper alpha (A-Z) - !(code > 96 && code < 123)) { // lower alpha (a-z) + !(code > 64 && code < 91) && // upper alpha (A-Z) + !(code > 96 && code < 123)) { // lower alpha (a-z) return false; } } return true; }, categorizeQueryString(queryObj) { - let query = {} - let order = {} + let query = {}; + let order = {}; //extract query, order, filter value for (const i in queryObj) { if (queryObj[i]) { // extract order if (i === 'order') { - order['sort'] = queryObj[i] - continue + order['sort'] = queryObj[i]; + continue; } // extract range if (i === 'range') { - let range_arr = [] - let query_arr = [] + let range_arr = []; + let query_arr = []; // multi ranges if (queryObj[i].constructor === Array) { for (const r of queryObj[i]) { - range_arr = r.split('-') + range_arr = r.split('-'); query_arr.push({ - price: { $gt: range_arr[0], $lt: range_arr[1] } - }) + price: {$gt: range_arr[0], $lt: range_arr[1]}, + }); } } // one range if (queryObj[i].constructor === String) { - range_arr = queryObj[i].split('-') + range_arr = queryObj[i].split('-'); query_arr.push({ - price: { $gt: range_arr[0], $lt: range_arr[1] } - }) + price: {$gt: range_arr[0], $lt: range_arr[1]}, + }); } - Object.assign(query, { $or: query_arr }) - delete query[i] - continue + Object.assign(query, {$or: query_arr}); + delete query[i]; + continue; } - query[i] = queryObj[i] + query[i] = queryObj[i]; } } - return { query, order } + return {query, order}; }, dateToEpoch(thedate) { @@ -1968,7 +2170,7 @@ module.exports = { }, getPaymentTypesById(idmetodo) { - return shared_consts.PaymentTypes[idmetodo] + return shared_consts.PaymentTypes[idmetodo]; }, getVersionint(versionstr) { @@ -1976,6 +2178,6 @@ module.exports = { version = version.replace('.', ''); return parseInt(version); - } + }, };