index.js 7.98 KB
'use strict';

const google = require('googleapis');
const googleAuth = require('google-auth-library');
const calendar = google.calendar('v3');
const fs = require('fs');
const path = require('path');
const yamlConfig = require('node-yaml-config');
const config = yamlConfig.load(path.join(__dirname, '/../../config/config.yml'));
const moment = require('moment')
const CALENDAR_ID = config.ggapi.calendarID
const REDIRECTURL = config.ggapi.redirectUrl


const SCOPES = ['https://www.googleapis.com/auth/calendar'];
const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
const TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';

function hasTimezone(timezone) {
    if (timezone) {
        return timezone
    } else {
        return 'Asia/Bangkok'
    }
}

function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    // console.log('Authorize this app by visiting this url: ', authUrl);
    return authUrl;
}

function setNewToken(code) {
    oauth2Client.getToken(code, function (err, token) {
        if (err) {
            console.log('Error while trying to retrieve access token', err);
            return;
        }
        oauth2Client.credentials = token;
        storeToken(token);
        callback(oauth2Client);
    })
}

function storeToken(token) {
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log('Token stored to ' + TOKEN_PATH);
}

module.exports = {
    authorize: (callback) => {

        fs.readFile('client_secret.json', (err, content) => {
            if (err) return callback(err);

            let credentials = JSON.parse(content);
            var clientSecret = credentials.installed.client_secret;
            var clientId = credentials.installed.client_id;
            var redirectUrl = credentials.installed.redirect_uris[1];
            var auth = new googleAuth();
            var oauth2Client = new auth.OAuth2(clientId, clientSecret, REDIRECTURL);

            fs.readFile(TOKEN_PATH, (err, token) => {
                if (err) {
                    return callback(null, null, getNewToken(oauth2Client, callback));
                } else {
                    oauth2Client.credentials = JSON.parse(token);
                    return callback(null, oauth2Client);
                }
            });
        });

    },

    setNewToken: (code, callback) => {
        fs.readFile('client_secret.json', (err, content) => {
            if (err) return callback(err);

            let credentials = JSON.parse(content);
            var clientSecret = credentials.installed.client_secret;
            var clientId = credentials.installed.client_id;
            var redirectUrl = credentials.installed.redirect_uris[1];
            var auth = new googleAuth();
            var oauth2Client = new auth.OAuth2(clientId, clientSecret, REDIRECTURL);

            fs.readFile(TOKEN_PATH, (err, token) => {
                if (err) {
                    oauth2Client.getToken(code, function (err, token) {
                        if (err) {
                            console.log('Error while trying to retrieve access token', err);
                            return;
                        } else {
                            oauth2Client.credentials = token;
                            storeToken(token);
                            return callback(null, oauth2Client);
                        }

                    })
                } else {
                    oauth2Client.credentials = JSON.parse(token);
                    return callback(null, oauth2Client);
                }
            });
        });
    },

    listEvents: (auth, callback) => {
        calendar.events.list({
            auth: auth,
            calendarId: CALENDAR_ID || 'primary',
            maxResults: 50,
            singleEvents: true,
            orderBy: 'startTime'
        }, (err, response) => {
            if (err) return callback(err);

            return callback(null, response);
        });
    },

    createEvent: (options, callback) => {
        calendar.events.insert({
            auth: options.auth,
            calendarId: CALENDAR_ID || 'primary',
            resource: options
        }, (err, response) => {
            if (err) return callback(err);

            return callback(null, response);
        });
    },

    deleteEvent: (options, callback) => {
        calendar.events.delete({
            auth: options.auth,
            calendarId: CALENDAR_ID || 'primary',
            eventId: options.eventId
        }, (err, response) => {
            if (err) return callback(err);

            return callback(null, response);
        });
    },

    updateEvent: (options, callback) => {
        calendar.events.update({
            auth: options.auth,
            calendarId: CALENDAR_ID || 'primary',
            eventId: options.eventId
        }, (err, response) => {
            if (err) return callback(err);

            return callback(null, response);
        });
    },

    eventBuilder: (payload) => {
        var buildPayload = {}
        try {
            buildPayload.summary = payload.Title
            buildPayload.description = payload.Description
            buildPayload.start = {
                dateTime: payload.Start,
                timezone: hasTimezone(payload.StartTimezone)

            }
            buildPayload.end = {
                dateTime: payload.End,
                timeZone: hasTimezone(payload.EndTimezone)
            }
            if (payload.email) {
                buildPayload.attendees = [{ email: payload.email }]
            }
            if (payload.reminders) {
                buildPayload.reminders = {
                    useDefault: false,
                    overrides: [
                        {
                            method: 'email',
                            minutes: 24 * 60
                        }
                    ]
                }
            }
            if (payload.extendedProperties) {
                buildPayload.extendedProperties = payload.extendedProperties
            }
        } catch (error) {
            console.error(error.message)
        } finally {
            return buildPayload
        }
    },

    deleteBuilder: (payload) => {
        var buildPayload = {}
        try {
            buildPayload.calendarId = CALENDAR_ID
            buildPayload.eventId = payload.TaskID
        } catch (error) {
            console.error(error.message)
        } finally {
            return buildPayload
        }
    },

    updateBuilder: (payload) => {
        var buildPayload = {}
        try {
            buildPayload.calendarId = CALENDAR_ID
            buildPayload.eventId = payload.TaskID
            buildPayload.summary = payload.Title
            buildPayload.description = payload.Description
            buildPayload.start = {
                dateTime: moment(payload.Start).format("YYYY-MM-DDTHH:mm:ssZ"),
                timeZone: hasTimezone(payload.StartTimezone)
            }
            buildPayload.end = {
                dateTime: moment(payload.End).format("YYYY-MM-DDTHH:mm:ssZ"),
                timeZone: hasTimezone(payload.EndTimezone)
            }
            if (payload.email) {
                buildPayload.attendees = [{ email: payload.email }]
            }
            if (payload.reminders) {
                buildPayload.reminders = {
                    useDefault: false,
                    overrides: [
                        {
                            method: 'email',
                            minutes: 24 * 60
                        }
                    ]
                }
            }
            if (payload.extendedProperties) {
                buildPayload.extendedProperties = payload.extendedProperties
            }
        } catch (error) {
            console.error(error.message)
        } finally {
            return buildPayload
        }
    }
}