Skip to content
Snippets Groups Projects
email.service.ts 4.56 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Injectable, Logger, InternalServerErrorException } from '@nestjs/common';
    
    import * as amqp from 'amqplib';
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
    import { ContactForm, Email, EmailWithoutFrom, FeedbackForm } from './email';
    
    import { ConfigService } from '../configuration/config.service';
    import { buildContactAdminEmail, buildContactUserEmail } from '../email-templates/contact';
    
    import moment = require('moment');
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
    import { buildFeedbackEmail } from '../email-templates/feedback';
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
    import * as useragent from 'useragent';
    
    
    @Injectable()
    export class EmailService {
    
      config: any = {};
    
      constructor(private configService: ConfigService) {
        this.config = this.configService.config;
      }
    
    
      async sendContactEmails(contactForm: ContactForm) {
        Logger.log('[-] sendContactEmails method');
    
        const adminEmailBody = buildContactAdminEmail({
          subject: contactForm.subject,
          message: contactForm.text,
          firstName: contactForm.firstname,
          lastName: contactForm.lastname,
          email: contactForm.email,
    
          datetime: moment().format('DD/MM/YYYY à HH:mm'),
          imageHost: this.config.imageHost,
    
        });
        const userEmailBody = buildContactUserEmail({
          subject: contactForm.subject,
          message: contactForm.text,
    
          firstName: contactForm.firstname,
          datetime: moment().format('DD/MM/YYYY à HH:mm'),
          imageHost: this.config.imageHost,
    
        });
    
        const adminEmail = new EmailWithoutFrom();
        adminEmail.to = [this.config.plateformDataEmail];
    
        adminEmail.replyTo = contactForm.email;
    
        adminEmail.subject = contactForm.subject;
        adminEmail.html = adminEmailBody;
    
        const userEmail = new EmailWithoutFrom();
        userEmail.to = [contactForm.email];
        userEmail.subject = contactForm.subject;
        userEmail.html = userEmailBody;
    
        await this.send(adminEmail);
        await this.send(userEmail);
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
      async sendFeedback(feedbackForm: FeedbackForm, userAgent) {
        Logger.log('[-] sendFeedback method');
    
        const userAgentParsed = useragent.parse(userAgent);
        let userAgentString = '';
    
        if (userAgentParsed) {
          userAgentString = `Family: ${userAgentParsed.family},`;
          userAgentString += `Version:${userAgentParsed.major}.${userAgentParsed.minor}.${userAgentParsed.patch},`;
          userAgentString += `Source: ${userAgentParsed.source}`;
        }
    
        const feedbackEmailBody = buildFeedbackEmail({
          url: feedbackForm.url,
          userAgent: userAgentString,
          version: feedbackForm.version,
          message: feedbackForm.message,
          datetime: moment().format('DD/MM/YYYY à HH:mm'),
          imageHost: this.config.imageHost,
        });
        const feedbackEmail = new EmailWithoutFrom();
        feedbackEmail.to = [this.config.plateformDataEmail];
        feedbackEmail.subject = 'Feedback';
        feedbackEmail.html = feedbackEmailBody;
    
        await this.send(feedbackEmail);
    
        return;
      }
    
    
      async send(emailInfo: EmailWithoutFrom) {
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
        let conn, ch;
        // tslint:disable-next-line:max-line-length
        const rabbitmqUrl = `amqp://${this.config.rabbitMQ.user}:${this.config.rabbitMQ.password}@${this.config.rabbitMQ.host}:${this.config.rabbitMQ.port}`;
        const mailerQueue = this.config.mailerQueue;
    
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
        let email = new Email();
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
        email.from = this.config.plateformDataEmail;
    
        email = Object.assign(email, emailInfo);
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
    
        Logger.log('[-] send method');
    
    FORESTIER Fabien's avatar
    FORESTIER Fabien committed
        Logger.log(email);
    
        // Connect to rabbitmq
        try {
          conn = await amqp.connect(rabbitmqUrl);
        } catch (error) {
          Logger.error('    [x] Error connecting to RabbitMQ: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not connect to rabbitMQ.');
        }
    
        try {
    
          // Create a communication channel
          ch = await conn.createChannel();
        } catch (error) {
          Logger.error('    [x] Error creating channel: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not create channel.');
        }
    
        // Stringify and bufferise message
        const buffer = Buffer.from(JSON.stringify(email));
    
        try {
          await ch.assertQueue(mailerQueue, { durable: true });
        } catch (error) {
          Logger.error('    [x] Error creating channel: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not assert channel.');
        }
    
        try {
          await ch.sendToQueue(mailerQueue, buffer, { persistent: true });
        } catch (error) {
          Logger.error('    [x] Error sending to queue: ', JSON.stringify(error));
          throw new InternalServerErrorException('Could not send to queue.');
        }
    
        Logger.log(`Sent to queue ${mailerQueue}: ${JSON.stringify(email)}`);
    
        setTimeout(() => { conn.close(); }, 500);
    
        return;