{"size": 14376, "ext": "js", "max_stars_repo_path": "Mail.js", "max_stars_repo_name": "tukida/pm2-health", "max_stars_repo_stars_event_min_datetime": "2021-12-27T05:56:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T05:56:59.000Z", "max_issues_repo_path": "Mail.js", "max_issues_repo_name": "tukida/pm2-health", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mail.js", "max_forks_repo_name": "tukida/pm2-health", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 43.4320241692, "max_line_length": 268, "alphanum_fraction": 0.4429604897}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Slack = exports.GMail = exports.Mail = void 0;
const Mailer = require("nodemailer");
const Fs = require("fs");
const os_1 = require("os");
const Log_1 = require("./Log");
const { google } = require('googleapis');
const MailComposer = require('nodemailer/lib/mail-composer');
const SlackNotiFy = require('slack-notify');
const moment = require('moment');
function timeConverter(UNIX_timestamp) {
    var a = new Date(UNIX_timestamp * 1000);
    var months = [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec'
    ];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec;
    return time;
}
class Mail {
    constructor(_config) {
        this._config = _config;
        this._template = '<p><!-- body --></p><p>At: <!-- timeStamp --></p>';
        if (!this._config.smtp)
            this._config.smtp = { disabled: true };
        if (this._config.smtp.disabled === true)
            return; // don't analyze config if disabled
        if (!this._config.smtp)
            throw new Error(`[smtp] not set`);
        if (!this._config.smtp.host)
            throw new Error(`[smtp.host] not set`);
        if (!this._config.smtp)
            throw new Error(`[smtp.port] not set`);
        try {
            console.log('read html');
            this._template = Fs.readFileSync('Template.html', 'utf8');
        }
        catch (_a) {
            Log_1.info(`Template.html not found`);
        }
    }
    configChanged() {
        if (!this._config.mailTo)
            throw new Error(`[mailTo] not set`);
    }
    async send(message) {
        if (this._config.smtp.disabled === true) {
            Log_1.debug('mail sending is disbled in config');
            return;
        }
        const temp = {
            host: this._config.smtp.host,
            port: this._config.smtp.port,
            tls: { rejectUnauthorized: false },
            secure: this._config.smtp.secure === true,
            auth: null
        };
        if (this._config.smtp.user)
            temp.auth = {
                user: this._config.smtp.user,
                pass: this._config.smtp.password
            };
        const transport = Mailer.createTransport(temp), headers = {};
        if (message.priority)
            headers['importance'] = message.priority;
        await transport.sendMail({
            to: this._config.mailTo,
            from: this._config.smtp.from || this._config.smtp.user,
            replyTo: this._config.replyTo,
            subject: `pm2-health-custom: ${os_1.hostname()}, ${message.subject}`,
            html: this._template
                .replace(/<!--\s*body\s*-->/, message.body)
                .replace(/<!--\s*timeStamp\s*-->/, new Date().toISOString()),
            attachments: message.attachements,
            headers
        });
    }
}
exports.Mail = Mail;
class GMail extends Mail {
    constructor(_config) {
        super(_config);
        this.TOKEN_PATH = 'token.json';
        try {
            console.log('read html');
            this._template = Fs.readFileSync('Template.html', 'utf8');
        }
        catch (_a) {
            Log_1.info(`Template.html not found`);
        }
        if (!this._config.gmail)
            this._config.gmail = { disabled: true };
        if (this._config.gmail.disabled === true)
            return; // don't analyze config if disabled
        if (!this._config.gmail)
            throw new Error(`[gmail] not set`);
        if (!this._config.gmail.type)
            throw new Error(`[smtp.type] not set`);
        if (!this._config.gmail.clientId)
            throw new Error(`[smtp.clientId] not set`);
        if (!this._config.gmail.clientSecret)
            throw new Error(`[smtp.clientSecret] not set`);
        if (!this._config.gmail.user)
            throw new Error(`[smtp.user] not set`);
        if (!this._config.gmail.refreshToken)
            throw new Error(`[smtp.refreshToken] not set`);
    }
    async send(message) {
        const oAuth2Client = new google.auth.OAuth2(this._config.gmail.clientId, this._config.gmail.clientSecret, this._config.gmail.redirect_uris[0]);
        const token = {
            refresh_token: this._config.gmail.refreshToken
        };
        oAuth2Client.setCredentials(token);
        const accessToken = await oAuth2Client.getAccessToken();
        oAuth2Client.setCredentials(accessToken.res.data);
        const headers = {};
        if (message.priority)
            headers['importance'] = message.priority;
        const mail = new MailComposer({
            to: this._config.mailTo,
            from: this._config.gmail.from,
            replyTo: this._config.replyTo,
            subject: `pm2-health-custom: ${os_1.hostname()}, ${message.subject}`,
            html: this._template
                .replace(/<!--\s*body\s*-->/, message.body)
                .replace(/<!--\s*timeStamp\s*-->/, new Date().toISOString()),
            headers
        });
        mail.compile().build((error, msg) => {
            if (error)
                return console.log('Error compiling email ' + error);
            const encodedMessage = Buffer.from(msg)
                .toString('base64')
                .replace(/\+/g, '-')
                .replace(/\//g, '_')
                .replace(/=+$/, '');
            const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
            gmail.users.messages.send({
                userId: 'me',
                resource: {
                    raw: encodedMessage
                }
            }, (err, result) => {
                if (err)
                    return console.log('NODEMAILER - The API returned an error: ' + err);
                console.log('NODEMAILER - Sending email reply from server:', result.data);
            });
        });
    }
}
exports.GMail = GMail;
class Slack extends Mail {
    constructor(_config) {
        super(_config);
        this.TOKEN_PATH = 'token.json';
        this.slack = null;
        console.log(this._config.slack);
        if (!this._config.slack)
            this._config.slack = { disabled: true };
        if (this._config.slack.disabled === true)
            return; // don't analyze config if disabled
        if (!this._config.slack)
            throw new Error(`[slack] not set`);
        if (!this._config.slack.webhook_url)
            throw new Error(`[slack.webhook_url] not set`);
        console.log('slack valid');
        this.slack = SlackNotiFy(this._config.slack.webhook_url);
    }
    async send(message) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19;
        const serviceInfo = [
            {
                title: 'Service Name',
                value: (_b = (_a = message.rawData) === null || _a === void 0 ? void 0 : _a.process) === null || _b === void 0 ? void 0 : _b.name,
                short: true
            },
            {
                title: 'Service ID',
                value: (_d = (_c = message.rawData) === null || _c === void 0 ? void 0 : _c.process) === null || _d === void 0 ? void 0 : _d.pm_id,
                short: true
            }
        ];
        const versioning = [
            {
                title: 'Update Time',
                value: (_g = (_f = (_e = message.rawData) === null || _e === void 0 ? void 0 : _e.process) === null || _f === void 0 ? void 0 : _f.versioning) === null || _g === void 0 ? void 0 : _g.update_time,
                short: false
            },
            {
                title: 'Revision',
                value: (_k = (_j = (_h = message.rawData) === null || _h === void 0 ? void 0 : _h.process) === null || _j === void 0 ? void 0 : _j.versioning) === null || _k === void 0 ? void 0 : _k.revision,
                short: false
            },
            {
                title: 'Comment',
                value: (_o = (_m = (_l = message.rawData) === null || _l === void 0 ? void 0 : _l.process) === null || _m === void 0 ? void 0 : _m.versioning) === null || _o === void 0 ? void 0 : _o.comment,
                short: false
            }
        ];
        let errorAttachments = {};
        console.log((_q = (_p = message.rawData) === null || _p === void 0 ? void 0 : _p.data) === null || _q === void 0 ? void 0 : _q.name);
        if (((_s = (_r = message.rawData) === null || _r === void 0 ? void 0 : _r.data) === null || _s === void 0 ? void 0 : _s.name) === 'Error') {
            errorAttachments = {
                fallback: 'Service Error',
                pretext: 'Error:',
                fields: [
                    {
                        title: 'Call Site',
                        value: (_u = (_t = message.rawData) === null || _t === void 0 ? void 0 : _t.data) === null || _u === void 0 ? void 0 : _u.callsite,
                        short: false
                    },
                    {
                        title: 'Message',
                        value: (_w = (_v = message.rawData) === null || _v === void 0 ? void 0 : _v.data) === null || _w === void 0 ? void 0 : _w.message,
                        short: false
                    },
                    {
                        title: 'Stack',
                        value: (_y = (_x = message.rawData) === null || _x === void 0 ? void 0 : _x.data) === null || _y === void 0 ? void 0 : _y.stack,
                        short: false
                    }
                ],
                color: '#FF0051'
            };
        }
        const event = (_0 = (_z = message.rawData) === null || _z === void 0 ? void 0 : _z.event) === null || _0 === void 0 ? void 0 : _0.toUpperCase();
        const status = (_2 = (_1 = message.rawData) === null || _1 === void 0 ? void 0 : _1.process) === null || _2 === void 0 ? void 0 : _2.status;
        let statusSymbol = '';
        switch (event) {
            case 'DELETE':
            case 'STOP':
            case 'EXIT':
            case 'EXCEPTION':
                statusSymbol = '❌';
                break;
            default:
                statusSymbol = '✅';
                break;
        }
        if (event !== 'EXIT' || status === 'stopped') {
            this.slack.alert({
                blocks: [
                    {
                        type: 'header',
                        text: {
                            type: 'plain_text',
                            text: `${(_5 = (_4 = (_3 = message.rawData) === null || _3 === void 0 ? void 0 : _3.process) === null || _4 === void 0 ? void 0 : _4.name) === null || _5 === void 0 ? void 0 : _5.replace('_', ' ').toUpperCase()} - ${event} ${statusSymbol}`,
                            emoji: true
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'section',
                        fields: [
                            {
                                type: 'mrkdwn',
                                text: `*Service Name:*\n${(_7 = (_6 = message.rawData) === null || _6 === void 0 ? void 0 : _6.process) === null || _7 === void 0 ? void 0 : _7.name}`
                            },
                            {
                                type: 'mrkdwn',
                                text: `*Service ID:*\n${(_9 = (_8 = message.rawData) === null || _8 === void 0 ? void 0 : _8.process) === null || _9 === void 0 ? void 0 : _9.pm_id}`
                            }
                        ]
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'section',
                        fields: [
                            {
                                type: 'mrkdwn',
                                text: `*Update Time:*\n${(_12 = (_11 = (_10 = message.rawData) === null || _10 === void 0 ? void 0 : _10.process) === null || _11 === void 0 ? void 0 : _11.versioning) === null || _12 === void 0 ? void 0 : _12.update_time}`
                            },
                            {
                                type: 'mrkdwn',
                                text: `*Revision:*\n${(_15 = (_14 = (_13 = message.rawData) === null || _13 === void 0 ? void 0 : _13.process) === null || _14 === void 0 ? void 0 : _14.versioning) === null || _15 === void 0 ? void 0 : _15.revision}`
                            },
                            {
                                type: 'mrkdwn',
                                text: `*Comment:*\n${(_18 = (_17 = (_16 = message.rawData) === null || _16 === void 0 ? void 0 : _16.process) === null || _17 === void 0 ? void 0 : _17.versioning) === null || _18 === void 0 ? void 0 : _18.comment}`
                            }
                        ]
                    },
                    {
                        type: 'context',
                        elements: [
                            {
                                type: 'image',
                                image_url: 'https://yt3.ggpht.com/ytc/AAUvwnjHbdHcG1nweQYFubTIU2JjBslYt_Ko0Iv02bbK=s88-c-k-c0x00ffffff-no-rj',
                                alt_text: 'utrend'
                            },
                            {
                                type: 'plain_text',
                                text: `Utrend | ${moment((_19 = message.rawData) === null || _19 === void 0 ? void 0 : _19.at).format('DD-MM-YYYY h:mm:ss')}`,
                                emoji: true
                            }
                        ]
                    }
                ],
                attachments: [
                    Object.assign({}, errorAttachments)
                ]
            });
        }
        this.slack.onError = function (err) {
            console.log('API error:', err);
        };
    }
}
exports.Slack = Slack;
//# sourceMappingURL=Mail.js.map