const nodemailer = require("nodemailer"); const fetch = require('cross-fetch'); const { Pool } = require('pg'); var parse = require('pg-connection-string').parse; var config = parse(process.env.DATABASE_URL); const pool = new Pool(config); // ***** update daily top 3 news // const updateEmailNews = async (req, res) => { // try { // const catList = ["science", "india", 'business', // "sports", "entertainment", "technology", "world"]; // catList.forEach(async (cat) => { // const data = await getTopNews(cat); // data.forEach(async (d) => { // const summary = await getSummary(d.article_url); // //set news in database // try { // const query = ` // update top_news set // title = $1, article_url = $2, source = $3, summary = $4, published_date = $5 where category = '${cat}_${data.indexOf(d) + 1}' ; // `; // const values = [ // d.title, // d.article_url, // d.source_name, // summary, // d.published_date // ]; // await pool.query(query, values); // } catch (er) { // console.log(er); // } // }); // }); // res.send({ "status": "running" }); // } catch (e) { // console.log(e); // } // } const updateEmailNews = async (req, res) => { try { const catList = ["science", "india", 'business', "sports", "entertainment", "technology", "world"]; const promises = catList.map(async (cat) => { const data = await getTopNews(cat); const articlePromises = data.map(async (d) => { try { const summary = await getSummary(d.article_url); const query = ` UPDATE top_news SET title = $1, article_url = $2, source = $3, summary = $4, published_date = $5 WHERE category = '${cat}_${data.indexOf(d) + 1}'; `; const values = [ d.title, d.article_url, d.source_name, summary, d.published_date ]; await pool.query(query, values); } catch (er) { console.log(er); } }); await Promise.all(articlePromises); }); await Promise.all(promises); res.send({ "status": "completed" }); } catch (e) { console.log(e); res.status(500).send({ "error": "An error occurred" }); } } async function getTopNews(category) { const query = ` select title, article_url, category, source_name, published_date from news where category like '%${category}%' order by published_date desc limit 3; `; const data = await pool.query(query); return data.rows; } async function getSummary(url) { //console.log(url) const apiUrl = 'https://yashxx07-summarize-articles.hf.space/summarize-v1'; const options = { method: 'POST', headers: { 'content-type': 'application/json', }, body: JSON.stringify({ "url": url, "max_tokens": 500 }) }; try { const response = await fetch(apiUrl, options); const result = await response.text(); //console.log(result); return result; } catch (error) { console.error(error); } } // const transporter = nodemailer.createTransport({ // host: 'smtp.mailchimp.com', // port: 587, // Mailchimp SMTP port // secure: false, // true for 465, false for other ports // auth: { // user: 'your_mailchimp_username', // pass: 'your_mailchimp_password' // } // }); const transporter = nodemailer.createTransport({ host: "smtp.elasticemail.com", port: 2525, auth: { user: process.env.ID, pass: process.env.PASS, }, }); async function sendToUser(email, mailContent) { try { await transporter.sendMail({ from: { name: "RapidRecap", address: process.env.EMAIL }, to: email, subject: "Today's Top News", html: mailContent }); return "Email sent successfully!"; } catch (error) { console.error(error); } } async function getEmailsList(time) { try { const query = ` select * from subs where time = '${time}';`; const data = await pool.query(query); return data.rows; } catch (e) { console.log(e); } } async function getAllNews() { try { const query = ` select * from top_news; `; const data = await pool.query(query); return data.rows; } catch (e) { console.log(e); } } function craftEmailTemplate(user, newsList) { const filteredNews = newsList.filter(item => user.category.includes(item.category.slice(0, -2)) && item.summary != `""`); shuffleArray(filteredNews); // Construct the mail content const mailContent = filteredNews.slice(0, 3).map(doc => `

${doc.title}

Source: ${doc.source}

Published On: ${convertToDateString(doc.published_date)}

${doc.summary.slice(2, -1)}

` ).join(''); return mailContent; } function convertToDateString(publishedDate) { const date = new Date(publishedDate); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`; return formattedDate; } function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } } async function sendEmail(req, res) { try { const time = req.query.time; const emailsList = await getEmailsList(time); const newsList = await getAllNews(); emailsList.forEach(async (user) => { const mailTemplate = craftEmailTemplate(user, newsList); //res.send(mailTemplate); await sendToUser(user.email, mailTemplate); }); //const result = await sendEmail(); res.send({ "news": newsList, "emails": emailsList }); } catch (error) { console.log(error); res.status(500).send("Error sending email."); } } module.exports = { updateEmailNews, sendEmail }