<commit_before>/* eslint max-nested-callbacks: 0 */
/* eslint babel/no-await-in-loop: 0 */
import { config } from '../../core-server';
import Logger from '../../lib/logger';
import fs from 'fs';
import handlebars from 'handlebars';
import * as pg from '../../lib/pg';
import promisify from '../../lib/promisify';
import jwt from 'jsonwebtoken';
import send from './sendEmail';
const DIGEST_INTERVAL = 60 * 60 * 1000,
	template = handlebars.compile(
		fs.readFileSync(__dirname + '/../../../templates/' + config.app_id + '.digest.hbs', 'utf-8').toString()
	),
	connStr = config.connStr, conf = config.email;
let lastEmailSent, /*end,*/ log = new Logger(__filename, 'digest');
const readSync = promisify(pg.read.bind(pg, connStr));

export function initMailSending (userThreadRel) {
	return new Promise(async res => {
		const threads = userThreadRel.threadRels,
			user = userThreadRel.user;

		for (let i=0; i<threads.length; i++) {
			if(i === 3) {
				threads[i].indexFourth = true;
			}
			if (i < 3) {
				threads[i].showBody = true;
			}
		}

		if (!user.identities || !Array.isArray(user.identities)) {
			log.info('No identities found for user: ', user);
			res();
		}

		let mailIds = user.identities.filter((el) => {
			return /mailto:/.test(el);
		});
		if(mailIds.length === 0) res();
		const emailAdd = mailIds[0].slice(7),
		emailSub = threads[0].threadtitle;
		const date = new Date().getDate(),
			month = new Date().getMonth()+1,
			year = new Date().getFullYear();
		const formattedDate = date + '-' + month + '-' + year;
		const templateObj = {
			token: jwt.sign({ email: emailAdd }, conf.secret, { expiresIn: '5 days' }),
			domain: config.server.protocol + '//' + config.server.host,
			link : '?utm_source=DailyDigest&utm_medium=Email&utm_term='+ encodeURIComponent(user.id) + '&utm_content=' + encodeURIComponent(emailSub) + '&utm_campaign=' + encodeURIComponent(formattedDate),
			threads,
			email: emailAdd,
			sub: emailSub,
			date
		};
		const	emailHtml = template(templateObj);
		log.info('Digest email to: ', emailAdd);
		const sendMail = promisify(send.bind());
		try{
			await sendMail(conf.from, emailAdd, emailSub, emailHtml);
		} catch(e) {
			log.e(e);
		}
		res();
	});
}

async function sendDigestEmail () {
	const today = new Date().toString().split(" ")[2],
		lastEmailSentDay = new Date(parseInt(lastEmailSent, 10)).toString().split(" ")[2];

	if(new Date().getUTCHours() !== 22) { //Send at 3am IST. Move this to config
		log.info('Not digest email time: ', new Date().getUTCHours());
		return;
	}

	//Do not send digest email multiple times in the same day
	// This to prevent if server restarts multiple times in single hour. (cron job)
	if ( today === lastEmailSentDay	) {
		log.info('Digest email has been sent today. Last email sent time is: ', new Date((parseInt(lastEmailSent, 10))));
		return;
	}
	log.info('Starting digest email');
	let range;

	if (new Date().getDay() % 2 === 0) {
		range = '^[a-o]';
	} else {
		range = '^[p-z]|^[0-9]';
	}
	const users = await readSync({
		$:`SELECT
				id, identities, name FROM users
				WHERE
					presencetime IS NOT NULL
					AND users.id ~ &{range}
					AND (users.params-> 'email'->>'frequency' = 'daily' OR (users.params->'email') IS NULL)`,
		range<commit_msg>Change subject and email time<commit_after>/* eslint max-nested-callbacks: 0 */
/* eslint babel/no-await-in-loop: 0 */
import { config } from '../../core-server';
import Logger from '../../lib/logger';
import fs from 'fs';
import handlebars from 'handlebars';
import * as pg from '../../lib/pg';
import promisify from '../../lib/promisify';
import jwt from 'jsonwebtoken';
import send from './sendEmail';
const DIGEST_INTERVAL = 60 * 60 * 1000,
	template = handlebars.compile(
		fs.readFileSync(__dirname + '/../../../templates/' + config.app_id + '.digest.hbs', 'utf-8').toString()
	),
	connStr = config.connStr, conf = config.email;
let lastEmailSent, /*end,*/ log = new Logger(__filename, 'digest');
const readSync = promisify(pg.read.bind(pg, connStr));

export function initMailSending (userThreadRel) {
	return new Promise(async res => {
		const threads = userThreadRel.threadRels,
			user = userThreadRel.user;

		for (let i=0; i<threads.length; i++) {
			if(i === 3) {
				threads[i].indexFourth = true;
			}
			if (i < 3) {
				threads[i].showBody = true;
			}
		}

		if (!user.identities || !Array.isArray(user.identities)) {
			log.info('No identities found for user: ', user);
			res();
		}

		let mailIds = user.identities.filter((el) => {
			return /mailto:/.test(el);
		});
		if(mailIds.length === 0) res();
		const emailAdd = mailIds[0].slice(7),
		emailSub = threads[0].threadtitle + ' & More from Belong';
		const date = new Date().getDate(),
			month = new Date().getMonth()+1,
			year = new Date().getFullYear();
		const formattedDate = date + '-' + month + '-' + year;
		const templateObj = {
			token: jwt.sign({ email: emailAdd }, conf.secret, { expiresIn: '5 days' }),
			domain: config.server.protocol + '//' + config.server.host,
			link : '?utm_source=DailyDigest&utm_medium=Email&utm_term='+ encodeURIComponent(user.id) + '&utm_content=' + encodeURIComponent(emailSub) + '&utm_campaign=' + encodeURIComponent(formattedDate),
			threads,
			email: emailAdd,
			sub: emailSub,
			date
		};
		const	emailHtml = template(templateObj);
		log.info('Digest email to: ', emailAdd);
		const sendMail = promisify(send.bind());
		try{
			await sendMail(conf.from, emailAdd, emailSub, emailHtml);
		} catch(e) {
			log.e(e);
		}
		res();
	});
}

async function sendDigestEmail () {
	const today = new Date().toString().split(" ")[2],
		lastEmailSentDay = new Date(parseInt(lastEmailSent, 10)).toString().split(" ")[2];

	if(new Date().getUTCHours() !== 2) { //Send at 7am IST. Move this to config
		log.info('Not digest email time: ', new Date().getUTCHours());
		return;
	}

	//Do not send digest email multiple times in the same day
	// This to prevent if server restarts multiple times in single hour. (cron job)
	if ( today === lastEmailSentDay	) {
		log.info('Digest email has been sent today. Last email sent time is: ', new Date((parseInt(lastEmailSent, 10))));
		return;
	}
	log.info('Starting digest email');
	let range;

	if (new Date().getDay() % 2 === 0) {
		range = '^[a-o]';
	} else {
		range = '^[p-z]|^[0-9]';
	}
	const users = await readSync({
		$:`SELECT
				id, identities, name FROM users
				WHERE
					presencetime IS NOT NULL
					AND users.id ~ &{range}
					AND (users.params-> 'email'->>'frequency' = 'daily' OR (users.params->'email') IS NULL)`,
		range
{'fraction_non_alphanumeric': 0.17518693728063484, 'fraction_numerical': 0.009919121013276362, 'mean_word_length': 3.6714183891660728, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '647302', 'n_tokens_mistral': 2475, 'n_tokens_neox': 2235, 'n_words': 590}