2020-01-20 01:48:25 +01:00
const os = require ( "os" ) ;
2018-12-24 20:31:02 +01:00
2019-12-27 12:41:39 +01:00
const fs = require ( 'fs' ) ;
2019-10-05 20:01:56 +02:00
require ( '../config/config' ) ;
2019-02-14 19:01:41 +01:00
require ( '../models/subscribers' ) ;
2019-12-04 02:03:44 +01:00
const CryptoJS = require ( 'crypto-js' ) ;
2020-01-20 01:48:25 +01:00
const Url = require ( 'url-parse' ) ;
2019-02-14 19:01:41 +01:00
2019-10-21 20:38:10 +02:00
const { ObjectID } = require ( 'mongodb' ) ;
2020-02-02 04:06:32 +01:00
const shared _consts = require ( '../tools/shared_nodejs' ) ;
2019-02-14 19:01:41 +01:00
const mongoose = require ( 'mongoose' ) ;
const Subscription = mongoose . model ( 'subscribers' ) ;
2019-11-21 00:18:40 +01:00
const server _constants = require ( './server_constants' ) ;
2019-02-27 02:59:02 +01:00
2019-02-12 12:06:25 +01:00
// SETTINGS WebPush Configuration
const webpush = require ( 'web-push' ) ;
2020-01-03 01:52:49 +01:00
const subject = process . env . URLBASE _APP1 ;
2019-02-12 12:06:25 +01:00
const publicVapidKey = process . env . PUBLIC _VAPI _KEY ;
const privateVapidKey = process . env . PRIVATE _VAPI _KEY ;
2019-02-14 19:01:41 +01:00
2020-01-03 01:52:49 +01:00
// Code goes here
const keySize = 256 ;
const ivSize = 128 ;
const iterations = 100 ;
2019-02-14 19:01:41 +01:00
if ( process . env . GCM _API _KEY !== "" )
webpush . setGCMAPIKey ( process . env . GCM _API _KEY ) ;
webpush . setVapidDetails ( subject , publicVapidKey , privateVapidKey ) ;
2019-04-06 21:02:39 +02:00
// console.log('setVapidDetails... config...');
2019-02-14 19:01:41 +01:00
2019-02-12 12:06:25 +01:00
2020-01-20 01:48:25 +01:00
// To Translate!
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" ,
2020-02-02 04:06:32 +01:00
'TESTO_ASSISTENZA' : "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI-BiblioBacheca: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI Help & Support'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\nPotrete rientrare tutte le volte che ce ne sia necessità." ,
2020-01-20 01:48:25 +01:00
'BENVENUTO' : "Benvenuto" ,
'EMAIL_VERIF' : "Email Verificata" ,
'EMAIL_NON_VERIF' : "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e 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)' ,
'SCRITTO_SOGNO' : 'Hai scritto il tuo Sogno' ,
'INVITATI' : 'persone registrate che hai invitato' ,
2020-02-02 04:06:32 +01:00
'NONREG' : 'Invitati non Registrati' ,
2020-01-20 01:48:25 +01:00
} ,
es : {
"L'Email è già stata Verificata" : "L'Email è già stata Verificata" ,
"Nuova Registrazione" : "Nuevo Registro" ,
"Effettuata una Nuova Registrazione" : "Se ha realizado un nuevo registro" ,
"partecipanti" : "participantes" ,
2020-02-02 04:06:32 +01:00
'TESTO_ASSISTENZA' : "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI-BiblioBacheca: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI Help & Support'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\nPotrete rientrare tutte le volte che ce ne sia necessità." ,
2020-01-20 01:48:25 +01:00
'BENVENUTO' : "Benvenuto" ,
'EMAIL_VERIF' : "Email Verificata" ,
'EMAIL_NON_VERIF' : "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e 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)' ,
'SCRITTO_SOGNO' : 'Hai scritto il tuo Sogno' ,
'INVITATI' : 'persone registrate che hai invitato' ,
2020-02-02 04:06:32 +01:00
'NONREG' : 'Invitati non Registrati' ,
2020-01-20 01:48:25 +01:00
} ,
us : {
"partecipanti" : "participants" ,
2020-02-02 04:06:32 +01:00
'TESTO_ASSISTENZA' : "Per entrare nel Sito AYNI:\nhttps://ayni.gifteconomy.app\n\nHai dimenticato la Password per accedere al sito?\nhttps://ayni.gifteconomy.app/requestresetpwd\n\nChat AYNI BOT (questa):\nhttps://t.me/notevoleaynibot\n\nChat AYNI-BiblioBacheca: https://t.me/joinchat/AL2qKExZKvenLgpVhOyefQ \n\nChat di Aiuto e Supporto: 'AYNI Help & Support'\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\nPotrete rientrare tutte le volte che ce ne sia necessità." ,
2020-01-20 01:48:25 +01:00
'BENVENUTO' : "Benvenuto" ,
'EMAIL_VERIF' : "Email Verificata" ,
'EMAIL_NON_VERIF' : "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e 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)' ,
'SCRITTO_SOGNO' : 'Hai scritto il tuo Sogno' ,
'INVITATI' : 'persone registrate che hai invitato' ,
2020-02-02 04:06:32 +01:00
'NONREG' : 'Invitati non Registrati' ,
2020-01-20 01:48:25 +01:00
}
} ;
2018-12-24 20:31:02 +01:00
module . exports = {
2019-10-28 16:01:28 +01:00
INITDB _FIRSTIME : true ,
2020-01-03 01:52:49 +01:00
LANGADMIN : 'it' ,
2020-01-13 23:52:51 +01:00
APORTADOR _NONE : '------' ,
2019-04-07 21:24:27 +02:00
TYPE _PROJECT : 1 ,
TYPE _TODO : 2 ,
2019-11-05 23:53:39 +01:00
FieldType : {
boolean : 1 ,
date : 2 ,
string : 4 ,
binary : 8 ,
html : 16 ,
select : 32 ,
number : 64 ,
typeinrec : 128 ,
2019-11-12 21:34:03 +01:00
multiselect : 256 ,
2019-12-04 02:03:44 +01:00
password : 512 ,
2019-12-27 12:41:39 +01:00
listimages : 1024 ,
2019-11-05 23:53:39 +01:00
} ,
2019-04-07 21:24:27 +02:00
MAX _PHASES : 5 ,
2019-04-06 21:02:39 +02:00
FIRST _PROJ : '__PROJECTS' ,
EXECUTE _CALCPROJ : true ,
2019-10-13 20:44:05 +02:00
2020-01-20 01:48:25 +01:00
gettranslate ( text , lang ) {
try {
return textlang [ lang ] [ text ]
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2020-01-20 01:48:25 +01:00
return textlang [ 'it' ] [ text ]
}
} ,
get _ _ ( text , msg ) {
let lang = 'it' ;
if ( msg )
lang = msg . from . language _code ;
try {
return textlang [ lang ] [ text ]
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2020-01-20 01:48:25 +01:00
return textlang [ 'it' ] [ text ]
}
} ,
getres _ _ ( text , res ) {
// ++Todo: res estrarre la lingua
let lang = 'it' ;
try {
return textlang [ lang ] [ text ]
2020-01-21 01:37:15 +01:00
} catch ( e ) {
2020-01-20 01:48:25 +01:00
return textlang [ 'it' ] [ text ]
}
} ,
2018-12-24 20:31:02 +01:00
getHostname : function ( ) {
return os . hostname ( )
2019-02-07 00:52:48 +01:00
} ,
testing : function ( ) {
return ( process . env . TESTING _ON === '1' )
} ,
mylog : function ( ... args ) {
if ( ! this . testing ( ) )
console . log ( args )
} ,
2019-02-11 02:59:05 +01:00
mylogoff : function ( ... args ) {
// doing nothing
} ,
2019-02-12 12:06:25 +01:00
mylogshow : function ( ... args ) {
2019-02-07 00:52:48 +01:00
console . log ( args )
} ,
2019-02-13 18:47:58 +01:00
mylogserr : function ( ... args ) {
console . error ( args )
} ,
2019-10-24 23:30:45 +02:00
allfieldSendMsg : function ( ) {
2019-10-27 00:37:10 +02:00
return [ 'userId' , 'source' , 'dest' , 'message' , 'datemsg' , 'read' , 'deleted' , 'origin' , 'idapp' , 'status' , 'options' ]
2019-10-12 23:34:32 +02:00
} ,
2019-02-07 00:52:48 +01:00
allfieldTodo : function ( ) {
2019-04-06 21:52:34 +02:00
return [ 'userId' , 'pos' , 'category' , 'descr' , 'priority' , 'statustodo' , 'created_at' , 'modify_at' ,
2019-04-29 23:47:48 +02:00
'completed_at' , 'expiring_at' , 'enableExpiring' , 'id_prev' , 'progress' , 'modified' , 'phase' , 'assigned_to_userId' , 'hoursplanned' , 'hoursworked' , 'start_date' , 'themecolor' , 'themebgcolor' ]
2019-02-07 00:52:48 +01:00
} ,
2019-10-20 01:21:54 +02:00
allfieldMyEvent : function ( ) {
return [ 'userId' , ]
} ,
2019-02-07 00:52:48 +01:00
allfieldTodoWithId : function ( ) {
return [ '_id' , ... this . allfieldTodo ( ) ]
2019-02-12 12:06:25 +01:00
} ,
2019-03-28 12:58:58 +01:00
// #TODO Projects++ Add fields ...
allfieldProject : function ( ) {
2019-04-29 23:47:48 +02:00
return [ 'userId' , 'pos' , 'typeproj' , 'id_main_project' , 'id_parent' , 'descr' , 'longdescr' , 'hoursplanned' , 'hoursleft' , 'themecolor' , 'themebgcolor' , 'hoursworked' , 'priority' , 'statusproj' , 'created_at' , 'modify_at' ,
2019-04-09 21:07:30 +02:00
'completed_at' , 'expiring_at' , 'enableExpiring' , 'id_prev' , 'progressCalc' , 'modified' , 'live_url' , 'test_url' , 'begin_development' , 'begin_test' , 'totalphases' , 'actualphase' , 'hoursweeky_plannedtowork' , 'endwork_estimate'
2019-10-05 20:01:56 +02:00
, 'privacyread' , 'privacywrite' ]
} ,
allfieldBooking : function ( ) {
2019-10-10 21:08:12 +02:00
return [ 'idapp' , 'userId' , 'id_bookedevent' , 'numpeople' , 'msgbooking' , 'modified' , 'infoevent' , 'datebooked' , 'booked' ]
2019-10-05 20:01:56 +02:00
} ,
allfieldBookingChange : function ( ) {
2019-10-10 21:08:12 +02:00
return [ 'numpeople' , 'msgbooking' , 'modified' , 'infoevent' , 'datebooked' , 'booked' ]
2019-03-28 12:58:58 +01:00
} ,
allfieldProjectWithId : function ( ) {
return [ '_id' , ... this . allfieldProject ( ) ]
} ,
jsonCopy ( src ) {
return JSON . parse ( JSON . stringify ( src ) )
} ,
2019-10-21 20:38:10 +02:00
CloneRecordToNew ( src ) {
const myrec = Object . assign ( { } , src ) ;
delete myrec . _doc [ '_id' ] ;
myrec . _id = new ObjectID ( ) ;
return myrec . _doc
} ,
2019-02-12 12:06:25 +01:00
sendBackNotif : function ( subscription , payload ) {
2019-02-13 18:47:58 +01:00
console . log ( 'sendBackNotif:' , subscription , payload ) ;
2019-02-12 12:06:25 +01:00
// Pass object into sendNotification
2019-02-14 19:01:41 +01:00
webpush . sendNotification ( subscription , JSON . stringify ( payload ) ) . catch ( err => console . error ( err ) )
2019-02-27 02:59:02 +01:00
. catch ( err => {
2019-02-14 19:01:41 +01:00
if ( err . statusCode === 410 ) {
// Gone: is not valid anymore (Expired probably!), so I have to delete from my db
2019-02-27 02:59:02 +01:00
return Subscription . findOneAndRemove ( { _id : subscription . _id } )
2019-02-14 19:01:41 +01:00
} else {
console . log ( 'Subscription is no longer valid: ' , err ) ;
}
} )
} ,
sendNotificationToUser : function ( userId , title , content , openUrl , tag ) {
let payload = {
title : title ,
message : content ,
url : openUrl ,
tag ,
// ttl: req.body.ttl,
// icon: req.body.icon,
// image: req.body.image,
// badge: req.body.badge,
// tag: req.body.tag
} ;
return Subscription . find ( { userId } , ( err , subscriptions ) => {
if ( err ) {
console . error ( ` Error occurred while getting subscriptions ` ) ;
res . status ( 500 ) . json ( {
error : 'Technical error occurred'
} ) ;
return false ;
} else {
2020-01-20 01:48:25 +01:00
let conta = 0 ;
2019-02-14 19:01:41 +01:00
let parallelSubscriptionCalls = subscriptions . map ( ( subscription ) => {
2020-01-20 01:48:25 +01:00
const trovati = subscriptions . length ;
2019-02-14 19:01:41 +01:00
return new Promise ( ( resolve , reject ) => {
const pushSubscription = {
endpoint : subscription . endpoint ,
keys : {
p256dh : subscription . keys . p256dh ,
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 . URLBASE _APP1 ,
process . env . PUBLIC _VAPI _KEY ,
process . env . PRIVATE _VAPI _KEY ,
'aes128gcm'
) ;
const pushOptions = {
vapidDetails : {
subject : process . env . URLBASE _APP1 ,
privateKey : process . env . PRIVATE _VAPI _KEY ,
publicKey : process . env . PUBLIC _VAPI _KEY ,
} ,
TTL : payload . ttl ,
headers : vapidHeaders
} ;
console . log ( '************ INVIO WEBPUSH.SENDNOTIFICATION N° ' , conta , '/' , trovati , 'A' , subscription . browser ) ;
2019-04-06 21:02:39 +02:00
// console.log('vapidDetails', pushOptions.vapidDetails);
2019-02-14 19:01:41 +01:00
2019-02-27 02:59:02 +01:00
payload . title = process . env . URLBASE _APP1 + ' Msg n° ' + conta + '/' + trovati ;
2019-02-14 19:01:41 +01:00
// payload.message += subscription.browser ;
const pushPayload = JSON . stringify ( payload ) ;
2019-04-06 21:02:39 +02:00
// console.log('A1) SUBS: pushSubscription', pushSubscription);
// console.log('A2) OPZIONI: pushOptions', pushOptions);
// console.log('A3) MSG_TO_SEND: pushPayload', pushPayload);
2019-02-14 19:01:41 +01:00
webpush . sendNotification (
pushSubscription ,
pushPayload ,
// pushOptions
) . then ( ( value ) => {
resolve ( {
status : true ,
endpoint : subscription . endpoint ,
data : value
} ) ;
} ) . catch ( ( err ) => {
reject ( {
status : false ,
endpoint : subscription . endpoint ,
data : err
} ) ;
} ) ;
} ) . catch ( error => {
2019-03-04 17:28:41 +01:00
console . log ( 'ERROR: sendNotificationToUser' , error . data . body )
2019-02-14 19:01:41 +01:00
} ) ;
} ) ;
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
// console.info(pushResults);
// });
// res.json({
// data: 'Push triggered'
// });
return true ;
}
} ) ;
2019-02-12 12:06:25 +01:00
2019-02-27 02:59:02 +01:00
} ,
// **********************
// SORT WITH PREV_ID
// **********************
mapSort : function ( linkedList ) {
2019-04-20 13:59:07 +02:00
let sortedList = [ ] ;
let remainingList = [ ] ;
2019-02-27 02:59:02 +01:00
var map = new Map ( ) ;
var currentId = null ;
// console.log('linkedList', linkedList);
// index the linked list by previous_item_id
for ( var i = 0 ; i < linkedList . length ; i ++ ) {
var item = linkedList [ i ] ;
if ( item . id _prev === server _constants . LIST _START ) {
// first item
currentId = String ( item . _id ) ;
// console.log('currentId', currentId);
sortedList . push ( item ) ;
} else {
2019-04-13 03:04:49 +02:00
map . set ( String ( item . id _prev ) , i ) ;
2019-02-27 02:59:02 +01:00
}
}
2019-04-20 13:59:07 +02:00
let conta = 0 ;
while ( conta < linkedList . length ) {
2019-02-27 02:59:02 +01:00
// get the item with a previous item ID referencing the current item
var nextItem = linkedList [ map . get ( currentId ) ] ;
2019-04-13 03:04:49 +02:00
if ( nextItem === undefined ) {
2019-04-20 13:59:07 +02:00
} else {
sortedList . push ( nextItem ) ;
currentId = String ( nextItem . _id ) ;
2019-04-13 03:04:49 +02:00
}
2019-04-20 13:59:07 +02:00
conta ++ ;
2019-02-27 02:59:02 +01:00
}
2019-04-20 13:59:07 +02:00
if ( linkedList . length > sortedList . length ) {
// If are not in the list, I'll put at the bottom of the list
2019-04-22 01:43:58 +02:00
// console.log('ATTENZIONE !!! ', sortedList.length, linkedList.length);
2019-04-20 13:59:07 +02:00
for ( const itemlinked of linkedList ) {
const elemtrov = sortedList . find ( ( item ) => item . _id === itemlinked . _id ) ;
if ( elemtrov === undefined ) {
sortedList . push ( itemlinked ) ;
}
}
2019-04-13 03:04:49 +02:00
}
2019-02-27 02:59:02 +01:00
// console.log('DOPO sortedList', sortedList);
return sortedList ;
2019-10-05 20:01:56 +02:00
} ,
2019-11-05 23:53:39 +01:00
checkUserOk ( userpassed , userauth , res ) {
2019-10-05 20:01:56 +02:00
this . mylog ( 'checkUserOk' , userpassed , userauth ) ;
if ( String ( userpassed ) !== String ( userauth ) ) {
// I'm trying to write something not mine!
2019-11-05 23:53:39 +01:00
this . mylog ( 'userId = ' , userpassed , 'req.user._id' , userauth ) ;
2019-10-05 20:01:56 +02:00
return { exit : true , ret : res . status ( 404 ) . send ( { code : server _constants . RIS _CODE _TODO _CREATING _NOTMYUSER } ) }
} else {
return { exit : false , ret : false }
}
} ,
convertHTMLtoText ( myhtml ) {
let msg = myhtml ;
msg = msg . replace ( '"' , '"' ) ;
msg = msg . replace ( '>' , '>' ) ;
msg = msg . replace ( '<' , '<' ) ;
msg = msg . replace ( '&' , '&' ) ;
msg = msg . replace ( '<br>' , '\n' ) ;
return msg
} ,
2019-11-06 22:29:29 +01:00
convertTexttoHtml ( myhtml ) {
// let msg = myhtml;
// msg = msg.replace('\n', '<br>');
// return msg
return myhtml ;
} ,
2019-10-05 20:01:56 +02:00
removeSpecialCharForEmail ( myhtml ) {
let msg = myhtml ;
msg = msg . replace ( /"/g , '\'' ) ;
return msg
} ,
getNomeAppByIdApp : function ( idapp ) {
2019-10-16 15:28:49 +02:00
const myapp =
MYAPPS . find ( item => item . idapp === idapp ) ;
2019-10-05 20:01:56 +02:00
if ( myapp )
return myapp . name ;
else
return '' ;
} ,
2019-10-16 15:28:49 +02:00
getHostByIdApp : function ( idapp ) {
const myapp =
MYAPPS . find ( item => item . idapp === idapp ) ;
if ( myapp ) {
let siteport = ( myapp . portapp !== "0" ) ? ( ':' + myapp . portapp ) : "" ;
return myapp . host + siteport ;
} else
return '' ;
} ,
2019-12-27 12:41:39 +01:00
getdirByIdApp : function ( idapp ) {
const myapp =
MYAPPS . find ( item => item . idapp === idapp ) ;
if ( myapp ) {
return myapp . dir ;
} else
return '' ;
} ,
2019-10-05 20:01:56 +02:00
getAdminEmailByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
if ( myapp )
return myapp . adminemail ;
else
return '' ;
} ,
2019-10-16 15:28:49 +02:00
getreplyToEmailByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
if ( myapp )
return myapp . replyTo ;
else
return '' ;
} ,
isManagAndAdminDifferent ( idapp ) {
2019-10-20 01:21:54 +02:00
const manag = this . getManagerEmailByIdApp ( idapp ) ;
return ( manag !== this . getAdminEmailByIdApp ( idapp ) ) && ( manag !== '' ) ;
2019-10-16 15:28:49 +02:00
} ,
getManagerEmailByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
if ( myapp )
return myapp . manageremail ;
else
return '' ;
} ,
2020-01-03 01:52:49 +01:00
getEmailByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
return ( myapp ) ? myapp . email _from : ''
} ,
getPwdByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
return ( myapp ) ? this . decryptdata ( myapp . email _pwd ) : ''
} ,
getTelegramBotNameByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
return ( myapp ) ? myapp . telegram _bot _name : ''
} ,
getTelegramKeyByIdApp : function ( idapp ) {
const myapp = MYAPPS . find ( ( item ) => item . idapp === idapp ) ;
return ( myapp ) ? myapp . telegram _key : ''
} ,
2019-10-20 01:21:54 +02:00
getQueryTable ( idapp , params ) {
// console.log('idapp', idapp);
// console.table(params);
2019-02-07 00:52:48 +01:00
2019-10-20 01:21:54 +02:00
if ( typeof params . startRow !== 'number' ) {
throw new Error ( 'startRow must be number' )
} else if ( typeof params . endRow !== 'number' ) {
throw new Error ( 'endRow must be number' )
}
2019-10-28 16:01:28 +01:00
let query = [ ] ;
if ( params . filter && params . fieldsearch ) {
let myregexp = { } ;
2020-02-02 04:06:32 +01:00
myregexp = new RegExp ( params . filter . trim ( ) . replace ( ' ' , '|' ) , "ig" ) ;
2019-10-28 16:01:28 +01:00
const myfilters = [ ] ;
params . fieldsearch . forEach ( ( field ) => {
const data = { } ;
data [ field ] = myregexp ;
myfilters . push ( data ) ;
} ) ;
query = [
{ $match : { $or : myfilters } } ,
]
}
2020-02-02 04:06:32 +01:00
let filtriadded = [ ] ;
// if (params.table === 'extralist') {
// if (params.filterand.includes(shared_consts.FILTER_EXTRALIST_DELETED))
// filtriadded.push({ deleted: true });
// else
// filtriadded.push({ deleted: { $exists: false } });
// }
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 _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 ] }
} ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _ZOOM ) )
filtriadded . push ( { 'profile.saw_zoom_presentation' : false } ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _INVITANTE ) )
filtriadded . push ( {
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 } ) ;
if ( params . filterand . includes ( shared _consts . FILTER _USER _NO _DREAM ) )
filtriadded . push ( {
'profile.my_dream' : {
$exists : false
}
} ) ;
}
if ( filtriadded . length > 0 )
query . push ( { $match : { $and : filtriadded } } ) ;
2019-10-28 16:01:28 +01:00
if ( idapp > 0 ) {
2019-11-05 23:53:39 +01:00
query . push ( { $match : { idapp } } ) ;
2019-10-28 16:01:28 +01:00
}
// console.log('QUERYMATCH', query[0].$match.or);
// console.log('filter', params.filter);
2019-02-15 01:38:01 +01:00
2019-10-20 01:21:54 +02:00
if ( params . sortBy ) {
// maybe we want to sort by blog title or something
const mysort = { $sort : params . sortBy } ;
// console.log('sortBy', params.sortBy);
// console.table(mysort);
query . push ( mysort )
}
2020-01-30 01:19:25 +01:00
let numrowend = params . endRow - params . startRow ;
if ( numrowend < 0 )
numrowend = 1 ;
2019-10-20 01:21:54 +02:00
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 ,
2020-01-30 01:19:25 +01:00
rows : { $slice : [ '$results' , params . startRow , numrowend ] }
2019-10-20 01:21:54 +02:00
}
}
) ;
2019-10-28 16:01:28 +01:00
2019-12-31 00:44:53 +01:00
// console.log('query', query);
2019-10-28 16:01:28 +01:00
return query ;
2019-10-20 01:21:54 +02:00
} ,
executeQueryTable ( mythistable , idapp , params ) {
let query = this . getQueryTable ( idapp , params ) ;
return mythistable
. aggregate ( query )
2019-10-28 16:01:28 +01:00
. then ( ( [ ris ] ) => {
if ( ris ) {
2019-11-04 20:30:09 +01:00
// console.table(ris.rows);
// console.log('ROW ', ris.count);
2019-10-28 16:01:28 +01:00
return ( { count : ris . count , rows : ris . rows } )
} else {
return ( { count : 0 , rows : [ ] } )
}
2019-10-20 01:21:54 +02:00
} )
. catch ( err => {
2019-10-28 16:01:28 +01:00
console . error ( err ) ;
2019-10-20 01:21:54 +02:00
return {
count : 0 , rows : [ ]
}
} ) ;
2019-10-27 00:37:10 +02:00
} ,
2020-01-13 23:52:51 +01:00
async DuplicateAllRecords ( mythistable , idapporig , idappdest ) {
console . log ( mythistable . name ) ;
const numrec = await mythistable . findAllIdApp ( idappdest ) . then ( ( arrrec ) => {
if ( arrrec && arrrec . length > 1 ) {
return arrrec . length ; // Has Already set
} else {
return 0 ;
}
} ) ;
// Before check if exist more than 1 record in the destination,
// if Yes don't copy
if ( numrec <= 0 ) {
return await mythistable . findAllIdApp ( idapporig ) . then ( async ( arrrec ) => {
let num = 0 ;
for ( let ind = 0 ; ind < arrrec . length ; ind ++ ) {
let newrec = new mythistable ( arrrec [ ind ] . _doc ) ;
newrec . _id = new ObjectID ( ) ;
newrec . idapp = idappdest ;
await newrec . save ( ( err , rec ) => {
if ( rec ) {
num ++ ;
}
} ) ;
}
return num ;
} ) ;
}
} ,
2019-10-27 00:37:10 +02:00
isBitActive ( bit , whattofind ) {
return ( ( bit & whattofind ) === whattofind )
} ,
SetBit ( myval , bit ) {
myval = myval & bit ;
return myval
2019-11-05 23:53:39 +01:00
} ,
2019-10-27 00:37:10 +02:00
2019-11-21 00:18:40 +01:00
snooze ( ms ) {
return new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
} ,
IncDateNow ( secs ) {
let mydate = new Date ( new Date ( ) . getTime ( ) + secs ) ;
// console.log('mydate', mydate);
return mydate
2019-12-04 02:03:44 +01:00
} ,
2020-01-21 01:37:15 +01:00
appendLeadingZeroes ( n ) {
if ( n <= 9 ) {
return "0" + n ;
}
return n
} ,
getWeekDay ( date ) {
//Create an array containing each day, starting with Sunday.
const weekdays = [
"Domenica" , "Lunedì" , "Martedì" , "Mercoledì" , "Giovedí" , "Venerdì" , "Sabato"
] ;
//Use the getDay() method to get the day.
const day = date . getDay ( ) ;
//Return the element that corresponds to that index.
return weekdays [ day ] ;
} ,
getstrDateTimeShort ( mydate ) {
// console.log('getstrDate', mytimestamp)
return this . getWeekDay ( mydate ) + ' ' + this . appendLeadingZeroes ( mydate . getDate ( ) ) + '/' + this . appendLeadingZeroes ( mydate . getMonth ( ) + 1 ) + ' ORE ' + this . appendLeadingZeroes ( mydate . getHours ( ) ) + ':' + this . appendLeadingZeroes ( mydate . getMinutes ( ) ) ;
} ,
getlinkzoom ( idconf ) {
return 'https://zoom.us/j/' + idconf
} ,
2019-12-04 02:03:44 +01:00
getmd5 ( mystr ) {
return CryptoJS . MD5 ( mystr . toLowerCase ( ) ) . toString ( ) ;
} ,
getHash ( mystr ) {
return CryptoJS . SHA512 ( mystr , { outputLength : 256 } ) . toString ( ) ;
} ,
2020-01-03 01:52:49 +01:00
encrypt ( msg , pass ) {
var salt = CryptoJS . lib . WordArray . random ( 128 / 8 ) ;
var key = CryptoJS . PBKDF2 ( pass , salt , {
keySize : keySize / 32 ,
iterations : iterations
} ) ;
var iv = CryptoJS . lib . WordArray . random ( 128 / 8 ) ;
var encrypted = CryptoJS . AES . encrypt ( msg , key , {
iv : iv ,
padding : CryptoJS . pad . Pkcs7 ,
mode : CryptoJS . mode . CBC
} ) ;
// salt, iv will be hex 32 in length
// append them to the ciphertext for use in decryption
var transitmessage = salt . toString ( ) + iv . toString ( ) + encrypted . toString ( ) ;
return transitmessage ;
} ,
decrypt ( transitmessage , pass ) {
var salt = CryptoJS . enc . Hex . parse ( transitmessage . substr ( 0 , 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
} ) ;
var decrypted = CryptoJS . AES . decrypt ( encrypted , key , {
iv : iv ,
padding : CryptoJS . pad . Pkcs7 ,
mode : CryptoJS . mode . CBC
} ) ;
return decrypted ;
} ,
2019-12-04 02:03:44 +01:00
cryptdata ( mydata ) {
// Encrypt
2020-01-03 01:52:49 +01:00
//return CryptoJS.AES.encrypt(JSON.stringify(mydata), process.env.SECRK);
return this . encrypt ( mydata , process . env . SECRK ) ;
2019-12-04 02:03:44 +01:00
} ,
2020-01-03 01:52:49 +01:00
2019-12-04 02:03:44 +01:00
decryptdata ( mydatacrypted ) {
// Decrypt
2020-01-03 01:52:49 +01:00
// 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 ) ;
2019-12-04 02:03:44 +01:00
} ,
BoolToInt ( mybool ) {
return ( mybool ) ? - 1 : 0
} ,
StrToBool ( mystr ) {
return ( mystr === '-1' ) ? true : false
2019-12-27 12:41:39 +01:00
} ,
move ( oldPath , newPath , callback ) {
fs . rename ( oldPath , newPath , function ( err ) {
if ( err ) {
if ( err . code === 'EXDEV' ) {
copy ( ) ;
} else {
callback ( err ) ;
}
return ;
}
callback ( ) ;
} ) ;
function copy ( ) {
const readStream = fs . createReadStream ( oldPath ) ;
const writeStream = fs . createWriteStream ( newPath ) ;
readStream . on ( 'error' , callback ) ;
writeStream . on ( 'error' , callback ) ;
readStream . on ( 'close' , function ( ) {
fs . unlink ( oldPath , callback ) ;
} ) ;
readStream . pipe ( writeStream ) ;
}
} ,
2019-11-21 00:18:40 +01:00
2019-12-28 02:16:29 +01:00
delete ( path , callback ) {
fs . unlink ( path , function ( err ) {
if ( err ) {
console . error ( err ) ;
callback ( err ) ;
return
}
callback ( ) ;
} ) ;
2019-12-28 14:30:30 +01:00
} ,
mkdirpath ( dirPath ) {
// if (!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK)) {
2020-01-03 01:52:49 +01:00
if ( ! fs . existsSync ( dirPath ) ) {
2019-12-28 14:30:30 +01:00
try {
fs . mkdirSync ( dirPath , { recursive : true } ) ;
}
catch ( e ) {
mkdirpath ( path . dirname ( dirPath ) ) ;
mkdirpath ( dirPath ) ;
}
}
} ,
2019-12-28 02:16:29 +01:00
2020-01-13 23:52:51 +01:00
extractNameAndSurnameByComplete ( name _complete ) {
const suffissoCognome = [ 'Del' , 'La' , 'De' , 'Lo' ] ;
let campi = name _complete . split ( " " ) ;
let namesurname = {
name : '' ,
surname : '' ,
} ;
if ( campi . length === 2 ) {
namesurname . name = campi [ 0 ] ;
namesurname . surname = campi [ 1 ] ;
2020-01-21 01:37:15 +01:00
} else if ( campi . length === 3 ) {
2020-01-13 23:52:51 +01:00
if ( suffissoCognome . includes ( campi [ 1 ] ) ) {
namesurname . name = campi [ 0 ] ;
namesurname . surname = campi [ 1 ] + " " + campi [ 2 ] ;
} else {
namesurname . name = campi [ 0 ] + " " + campi [ 1 ] ;
namesurname . surname = campi [ 2 ] ;
}
2020-01-21 01:37:15 +01:00
} else if ( campi . length === 4 ) {
2020-01-13 23:52:51 +01:00
namesurname . name = campi [ 0 ] + " " + campi [ 1 ] ;
namesurname . surname = campi [ 2 ] + " " + campi [ 3 ] ;
2020-01-21 01:37:15 +01:00
} else if ( campi . length > 4 ) {
2020-01-13 23:52:51 +01:00
namesurname . name = campi [ 0 ] + " " + campi [ 1 ] ;
namesurname . surname = " " + campi [ 2 ] ;
2020-01-20 01:48:25 +01:00
for ( let ind = 3 ; ind < campi . length ; ind ++ ) {
2020-01-13 23:52:51 +01:00
namesurname . surname += " " + campi [ ind ] ;
}
}
return namesurname
} ,
2020-02-02 04:06:32 +01:00
getiPAddressUser ( req ) {
2020-01-27 15:07:53 +01:00
try {
const striniziale = '::ffff:' ;
2020-02-02 04:06:32 +01:00
if ( req . ip . indexOf ( striniziale ) >= 0 ) {
2020-01-27 15:07:53 +01:00
return req . ip . substring ( striniziale . length )
} else {
return req . ip ; // Express
}
} catch ( e ) {
return ''
}
2020-01-30 01:19:25 +01:00
} ,
removespaces ( mystr ) {
return mystr . replace ( /\s+/g , '' )
} ,
2020-01-27 15:07:53 +01:00
2019-12-28 14:30:30 +01:00
} ;