Blame view

app/lib/index.js 9.92 KB
f6a4415a   Apichat.Tum   start smart-rms-c...
1
2
3
'use strict';

const google = require('googleapis');
d360cefc   TUM.Apichat   move save google ...
4
const plus = google.plus('v1');
f6a4415a   Apichat.Tum   start smart-rms-c...
5
6
const googleAuth = require('google-auth-library');
const calendar = google.calendar('v3');
f6a4415a   Apichat.Tum   start smart-rms-c...
7
const fs = require('fs');
a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
8
9
10
const path = require('path');
const yamlConfig = require('node-yaml-config');
const config = yamlConfig.load(path.join(__dirname, '/../../config/config.yml'));
77034810   Apichat.Tum   fix REST API
11
const moment = require('moment')
d360cefc   TUM.Apichat   move save google ...
12
13
14
const Promise = require('bluebird')
const Mongoose = Promise.promisifyAll(require('mongoose'));
const Token = Mongoose.model('Token');
fbe7f7a7   Apichat.Tum   add api google
15
16
17
18
19
20
21
22
23

const CALENDAR_ID = config.ggapi.calendarID
const REDIRECTURL = config.ggapi.redirectUrl


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

f3f14fef   TUM.Apichat   add value config ...
24
function hasTimezone(timezone) {
fbe7f7a7   Apichat.Tum   add api google
25
26
27
28
29
30
31
    if (timezone) {
        return timezone
    } else {
        return 'Asia/Bangkok'
    }
}

f6a4415a   Apichat.Tum   start smart-rms-c...
32
function getNewToken(oauth2Client, callback) {
d360cefc   TUM.Apichat   move save google ...
33
    var authUrl = oauth2Client.generateAuthUrl({
f6a4415a   Apichat.Tum   start smart-rms-c...
34
35
36
        access_type: 'offline',
        scope: SCOPES
    });
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
37
38
39
40
41
42
43
44
    // 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);
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
            return;
        }
        oauth2Client.credentials = token;
        storeToken(token);
        callback(oauth2Client);
    })
}

function storeToken(token, emails) {
    var tokendb;
    token.email = emails[0].value
    try {
        // ** new
        tokendb = new Token(token);
        // -- old
        // fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        throw err;
    }
    // ** new
    Promise.try(function () { })
d360cefc   TUM.Apichat   move save google ...
66
67
68
        .then(function () {
            tokendb.save(function (err, result) {
                if (err) {
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
69
                    console.error(err)
d360cefc   TUM.Apichat   move save google ...
70
71
72
73
                } else {
                    console.log(result);
                }
            });
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
74
        });
d360cefc   TUM.Apichat   move save google ...
75

cf86e9a3   Apichat.Tum   - ui with oauth2 ...
76
    // -- old
d360cefc   TUM.Apichat   move save google ...
77
    // fs.writeFile(TOKEN_PATH, JSON.stringify(token));
48a9a246   Apichat.Tum   fix auth
78
    // console.log('Token stored to ' + TOKEN_PATH);
d360cefc   TUM.Apichat   move save google ...
79
80
81
82
83
84
85
86
87
88
89
90
91
}

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();
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
92
93
            var oauth2Client = new auth.OAuth2(clientId, clientSecret, REDIRECTURL);
            var setToken = {} // set token from callback
f6a4415a   Apichat.Tum   start smart-rms-c...
94
            Token.findOne({ email: 'tzbattleboy@gmail.com' }, function (err, token) {
f6a4415a   Apichat.Tum   start smart-rms-c...
95

fbe7f7a7   Apichat.Tum   add api google
96
97
                if (err) {
                    return callback(null, null, getNewToken(oauth2Client, callback));
f3f14fef   TUM.Apichat   add value config ...
98
                } else if (token) {
fbe7f7a7   Apichat.Tum   add api google
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
                    setToken = {
                        access_token: token.access_token,
                        refresh_token: token.refresh_token,
                        token_type: token.token_type,
                        expiry_date: token.expiry_date
                    }
                    // console.log(setToken)
                    oauth2Client.credentials = setToken;
                    return callback(null, oauth2Client);
                } else {
                    return callback(null, null, getNewToken(oauth2Client, callback));
                }
            });
            // fs.readFile(TOKEN_PATH, (err, token) => {

            // });
f6a4415a   Apichat.Tum   start smart-rms-c...
115
        });
a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
116

f6a4415a   Apichat.Tum   start smart-rms-c...
117
118
    },

cf86e9a3   Apichat.Tum   - ui with oauth2 ...
119
    setNewToken: (code, callback) => {
fbe7f7a7   Apichat.Tum   add api google
120
        fs.readFile('client_secret.json', (err, content) => {
f3f14fef   TUM.Apichat   add value config ...
121
            if (err) return callback(err);
fbe7f7a7   Apichat.Tum   add api google
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

            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;
                            var params = { userId: 'me', fields: 'emails', auth: oauth2Client };

                            plus.people.get(params, function (err, response) {
                                if (err) {
                                    consol.error(err)
                                } else {
                                    storeToken(token, response.emails);
                                }
                            });

                            return callback(null, oauth2Client);
48a9a246   Apichat.Tum   fix auth
149
                        }
fbe7f7a7   Apichat.Tum   add api google
150
151
152
153

                    })
                } else {
                    oauth2Client.credentials = JSON.parse(token);
48a9a246   Apichat.Tum   fix auth
154
                    return callback(null, oauth2Client);
fbe7f7a7   Apichat.Tum   add api google
155
156
157
158
159
160
                }
            });
        });
    },

    listEvents: (auth, callback) => {
48a9a246   Apichat.Tum   fix auth
161
        calendar.events.list({
fbe7f7a7   Apichat.Tum   add api google
162
            auth: auth,
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
163
164
165
            calendarId: CALENDAR_ID || 'primary',
            maxResults: 50,
            singleEvents: true,
f6a4415a   Apichat.Tum   start smart-rms-c...
166
167
168
            orderBy: 'startTime'
        }, (err, response) => {
            if (err) return callback(err);
fbe7f7a7   Apichat.Tum   add api google
169

f6a4415a   Apichat.Tum   start smart-rms-c...
170
171
172
173
            return callback(null, response);
        });
    },

a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
174
175
    createEvent: (options, callback) => {
        calendar.events.insert({
f6a4415a   Apichat.Tum   start smart-rms-c...
176
177
178
179
            auth: options.auth,
            calendarId: CALENDAR_ID || 'primary',
            resource: options
        }, (err, response) => {
a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
180
            if (err) return callback(err);
f6a4415a   Apichat.Tum   start smart-rms-c...
181

a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
            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,
f6a4415a   Apichat.Tum   start smart-rms-c...
201
            calendarId: CALENDAR_ID || 'primary',
a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
202
203
            eventId: options.eventId,
            resource: options
77034810   Apichat.Tum   fix REST API
204
205
206
207
        }, (err, response) => {
            if (err) return callback(err);

            return callback(null, response);
7598c58f   Apichat.Tum   add eventTypeID /...
208
209
        });
    },
77034810   Apichat.Tum   fix REST API
210
211
212
213
214
215
216

    eventBuilder: (payload) => {
        var buildPayload = {}
        try {
            buildPayload.summary = payload.Title
            buildPayload.description = payload.Description
            buildPayload.start = {
a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API
217
                dateTime: new Date(payload.Start),
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
218
219
                timezone: hasTimezone(payload.StartTimezone)
            }
77034810   Apichat.Tum   fix REST API
220
221
            buildPayload.end = {
                dateTime: new Date(payload.End),
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
222
                timeZone: hasTimezone(payload.EndTimezone)
21a1ff19   Apichat.Tum   fix follow smartr...
223
            }
77034810   Apichat.Tum   fix REST API
224
            if (payload.email) {
77034810   Apichat.Tum   fix REST API
225
226
                buildPayload.attendees = [{
                    email: payload.email
21a1ff19   Apichat.Tum   fix follow smartr...
227
                }]
77034810   Apichat.Tum   fix REST API
228
229
230
            }
            if (payload.reminders) {
                buildPayload.reminders = {
21a1ff19   Apichat.Tum   fix follow smartr...
231
232
233
                    useDefault: false,
                    overrides: [{
                        method: 'email',
77034810   Apichat.Tum   fix REST API
234
235
236
237
                        minutes: 24 * 60
                    }]
                }
            }
21a1ff19   Apichat.Tum   fix follow smartr...
238
239
240
241
            if (payload.EventTypeID) {
                buildPayload.extendedProperties = {
                    "private": {
                        "eventTypeID": payload.EventTypeID
77034810   Apichat.Tum   fix REST API
242
243
                    }
                }
7598c58f   Apichat.Tum   add eventTypeID /...
244
245
246
247
248
249
            }
        } catch (error) {
            console.error(error.message)
        } finally {
            return buildPayload
        }
77034810   Apichat.Tum   fix REST API
250
    },
1244ae71   Apichat.Tum   new response
251
252
253

    deleteBuilder: (payload) => {
        var buildPayload = {}
77034810   Apichat.Tum   fix REST API
254
255
256
257
258
259
        try {
            buildPayload.calendarId = CALENDAR_ID
            buildPayload.eventId = payload.TaskID
        } catch (error) {
            console.error(error.message)
        } finally {
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
260
            return buildPayload
77034810   Apichat.Tum   fix REST API
261
262
263
264
265
266
267
268
269
270
271
272
        }
    },

    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"),
fbe7f7a7   Apichat.Tum   add api google
273
274
275
276
277
                timeZone: hasTimezone(payload.StartTimezone)
            }
            buildPayload.end = {
                dateTime: moment(payload.End).format("YYYY-MM-DDTHH:mm:ssZ"),
                timeZone: hasTimezone(payload.EndTimezone)
77034810   Apichat.Tum   fix REST API
278
            }
fbe7f7a7   Apichat.Tum   add api google
279
            if (payload.email) {
77034810   Apichat.Tum   fix REST API
280
                buildPayload.attendees = [{
fbe7f7a7   Apichat.Tum   add api google
281
282
283
284
                    email: payload.email
                }]
            }
            if (payload.reminders) {
77034810   Apichat.Tum   fix REST API
285
286
287
                buildPayload.reminders = {
                    useDefault: false,
                    overrides: [{
fbe7f7a7   Apichat.Tum   add api google
288
                        method: 'email',
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
289
                        minutes: 24 * 60
77034810   Apichat.Tum   fix REST API
290
291
                    }]
                }
fbe7f7a7   Apichat.Tum   add api google
292
            }
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
293
            if (payload.EventTypeID) {
21a1ff19   Apichat.Tum   fix follow smartr...
294
295
296
                buildPayload.extendedProperties = {
                    "private": {
                        "eventTypeID": payload.EventTypeID
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
297
298
299
300
                    }
                }
            }
            if (payload.extendedProperties) {
21a1ff19   Apichat.Tum   fix follow smartr...
301
302
303
304
                buildPayload.extendedProperties = payload.extendedProperties
            }
        } catch (error) {
            console.error(error.message)
cf86e9a3   Apichat.Tum   - ui with oauth2 ...
305
306
        } finally {
            return buildPayload
7598c58f   Apichat.Tum   add eventTypeID /...
307
308
309
        }
    }
}
1244ae71   Apichat.Tum   new response

cf86e9a3   Apichat.Tum   - ui with oauth2 ...

a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API

cf86e9a3   Apichat.Tum   - ui with oauth2 ...

a54f2679   DESKTOP-RBJDHSM\ADMIN   fix API

fbe7f7a7   Apichat.Tum   add api google

f3f14fef   TUM.Apichat   add value config ...

fbe7f7a7   Apichat.Tum   add api google

f6a4415a   Apichat.Tum   start smart-rms-c...

fbe7f7a7   Apichat.Tum   add api google