Commit fbe7f7a735e67c8bbbe019c062c720442fb20b4c

Authored by Apichat.Tum
1 parent e19c0d0b
Exists in master

add api google

app/controllers/home.controller.js
1   -"use strict"
2   -var console = process.console
  1 +"use strict";
  2 +var console = process.console;
3 3 var yamlConfig = require('node-yaml-config')
4 4 var path = require('path')
5 5 var async = require('async')
... ... @@ -90,7 +90,7 @@ function index(req, res) {
90 90 } else {
91 91 rms._20000(authUrl)
92 92 }
93   - })
  93 + });
94 94 }
95 95  
96 96 function setToken(req, res) {
... ... @@ -109,11 +109,18 @@ function setToken(req, res) {
109 109  
110 110 function events(req, res) {
111 111 var rms = new rmsRes(res)
112   -
  112 + console.tag().time().file().log(req.body)
113 113 lib.authorize((err, auth, authUrl) => {
114 114 if (err) {
115 115 rms._50000(err)
116 116 } else {
  117 + lib.listCalendar(auth, (err, response) => {
  118 + if (err) {
  119 + console.error(err);
  120 + } else {
  121 + console.info(response);
  122 + }
  123 + })
117 124 lib.listEvents(auth, (err, response) => {
118 125 if (err) {
119 126 if (authUrl) {
... ... @@ -123,9 +130,8 @@ function events(req, res) {
123 130 rms._50000(err)
124 131 }
125 132 } else {
126   - // console.tag().time().file().info(response)
127   - res.jsonp(ggToKendo(response))
128   - res.end()
  133 + res.json(ggToKendo(response));
  134 + res.end();
129 135 }
130 136 })
131 137 }
... ... @@ -168,7 +174,8 @@ function oauth2callback(req, res) {
168 174 if (err) {
169 175 rms._50000(err)
170 176 } else {
171   - res.redirect('http://localhost:3030/home')
  177 +
  178 + res.redirect('http://localhost:8000/#!/calendar')
172 179 }
173 180 })
174 181 }
... ... @@ -244,11 +251,93 @@ function checkObjEmpty(obj, parm, name) {
244 251  
245 252 }
246 253  
247   -module.exports.index = index
248   -module.exports.events = events
249   -module.exports.eventCreate = eventCreate
250   -module.exports.eventUpdate = eventUpdate
251   -module.exports.eventDelete = eventDelete
252   -module.exports.home = home
253   -module.exports.setToken = setToken
254   -module.exports.oauth2callback = oauth2callback
255 254 \ No newline at end of file
  255 +function createCalendar(req, res) {
  256 + var rms = new rmsRes(res)
  257 + let options = {};
  258 + lib.authorize((err, auth) => {
  259 + if (err) {
  260 + rms._50000(err)
  261 + } else {
  262 + options.auth = auth;
  263 + options.summary = req.body.summary;
  264 + lib.createCalendar(options, (err, result) => {
  265 + if (err) {
  266 + rms._50000(err)
  267 + } else {
  268 + rms._20000(result)
  269 + }
  270 + })
  271 + }
  272 + })
  273 +}
  274 +
  275 +function getCalendar(req, res) {
  276 + var rms = new rmsRes(res);
  277 +
  278 + lib.authorize((err, auth) => {
  279 + if (err) {
  280 + rms._50000(err)
  281 + } else {
  282 + lib.getCalendar(auth, (err, response) => {
  283 + if (err) {
  284 + rms._50000(err)
  285 + } else {
  286 + rms._20000(response)
  287 + }
  288 + })
  289 + }
  290 + })
  291 +}
  292 +
  293 +function deleteCalendar(req, res) {
  294 + var rms = new rmsRes(res);
  295 + var options = {};
  296 + lib.authorize((err, auth) => {
  297 + if (err) {
  298 + rms._50000(err)
  299 + } else {
  300 + options.auth = auth;
  301 + options.calendarId = req.body.id;
  302 + lib.deleteCalendar(options, (err, response) => {
  303 + if (err) {
  304 + rms._50000(err)
  305 + } else {
  306 + rms._20000(response)
  307 + }
  308 + })
  309 + }
  310 + })
  311 +}
  312 +
  313 +function refreshToken(req, res) {
  314 + var rms = new rmsRes(res);
  315 +
  316 + lib.authorize((err, auth) => {
  317 + if (err) {
  318 + rms._50000(err)
  319 + } else {
  320 + options.auth = auth;
  321 + lib.refreshToken(options, (err, response) => {
  322 + if (err) {
  323 + rms._50000(err)
  324 + } else {
  325 + rms._20000(response)
  326 + }
  327 + })
  328 + }
  329 + })
  330 +}
  331 +
  332 +module.exports.index = index;
  333 +module.exports.events = events;
  334 +module.exports.eventCreate = eventCreate;
  335 +module.exports.eventUpdate = eventUpdate;
  336 +module.exports.eventDelete = eventDelete;
  337 +module.exports.home = home;
  338 +module.exports.setToken = setToken;
  339 +module.exports.oauth2callback = oauth2callback;
  340 +module.exports.createCalendar = createCalendar;
  341 +module.exports.getCalendar = getCalendar;
  342 +module.exports.deleteCalendar = deleteCalendar;
  343 +module.exports.refreshToken = refreshToken;
  344 +
... ...
app/lib/index.js
... ... @@ -12,10 +12,22 @@ const moment = require('moment')
12 12 const Promise = require('bluebird')
13 13 const Mongoose = Promise.promisifyAll(require('mongoose'));
14 14 const Token = Mongoose.model('Token');
15   -
16   -const CALENDAR_ID = config.ggapi.calendarID
17   -const REDIRECTURL = config.ggapi.redirectUrl
18   -
  15 +const console = process.console;
  16 +
  17 +/**
  18 + * เธ”เธถเธ‡เธ„เนˆเธฒเธกเธฒเธˆเธฒเธ config.yml
  19 + */
  20 +const CALENDAR_ID = config.google.calendar_id;
  21 +const REDIRECT_URL = config.google.redirect_url;
  22 +const CLIENT_ID = config.google.client_id;
  23 +const CLIENT_SECRET = config.google.client_secret;
  24 +
  25 +/**
  26 + * เน€เธฃเธตเธขเธเนƒเธŠเน‰ oauth2Client
  27 + * @type {GoogleAuth}
  28 + */
  29 +const auth = google.auth.OAuth2;
  30 +const oauth2Client = new auth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
19 31  
20 32 const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/userinfo.email'];
21 33 const TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/';
... ... @@ -80,102 +92,80 @@ function storeToken(token, emails) {
80 92  
81 93 module.exports = {
82 94 authorize: (callback) => {
83   -
84   - fs.readFile('client_secret.json', (err, content) => {
85   - if (err) return callback(err);
86   -
87   - let credentials = JSON.parse(content);
88   - var clientSecret = credentials.installed.client_secret;
89   - var clientId = credentials.installed.client_id;
90   - var redirectUrl = credentials.installed.redirect_uris[1];
91   - var auth = new googleAuth();
92   - var oauth2Client = new auth.OAuth2(clientId, clientSecret, REDIRECTURL);
93   - var setToken = {} // set token from callback
94   - Token.findOne({
95   - email: 'tzbattleboy@gmail.com'
96   - }, function (err, token) {
97   - if (err) {
98   - return callback(null, null, getNewToken(oauth2Client, callback));
99   - } else if (token) {
100   - setToken = {
101   - access_token: token.access_token,
102   - refresh_token: token.refresh_token,
103   - token_type: token.token_type,
104   - expiry_date: token.expiry_date
105   - }
106   - // console.log(setToken)
107   - oauth2Client.credentials = setToken;
108   - return callback(null, oauth2Client);
109   - } else {
110   - return callback(null, null, getNewToken(oauth2Client, callback));
111   - }
112   - });
113   - // fs.readFile(TOKEN_PATH, (err, token) => {
114   -
115   - // });
  95 + var setToken = {} // set token from callback
  96 + Token.findOne({
  97 + email: 'zentoriono@gmail.com'
  98 + }, function (err, token) {
  99 + if (err) {
  100 + return callback(null, null, getNewToken(oauth2Client, callback));
  101 + } else if (token) {
  102 + setToken = {
  103 + access_token: token.access_token,
  104 + refresh_token: token.refresh_token,
  105 + token_type: token.token_type,
  106 + expiry_date: token.expiry_date
  107 + };
  108 + // console.log(setToken)
  109 + oauth2Client.credentials = setToken;
  110 + return callback(null, oauth2Client);
  111 + } else {
  112 + return callback(null, null, getNewToken(oauth2Client, callback));
  113 + }
116 114 });
117 115  
118 116 },
119 117  
120 118 setNewToken: (code, callback) => {
121   - fs.readFile('client_secret.json', (err, content) => {
122   - if (err) return callback(err);
123   -
124   - let credentials = JSON.parse(content);
125   - var clientSecret = credentials.installed.client_secret;
126   - var clientId = credentials.installed.client_id;
127   - var redirectUrl = credentials.installed.redirect_uris[1];
128   - var auth = new googleAuth();
129   - var oauth2Client = new auth.OAuth2(clientId, clientSecret, REDIRECTURL);
130   -
131   - Token.findOne({
132   - email: 'tzbattleboy@gmail.com'
133   - }, function (err, token) {
134   - if (token) {
135   - oauth2Client.credentials = JSON.parse(token);
136   - return callback(null, oauth2Client);
137   - } else {
138   - oauth2Client.getToken(code, function (err, token) {
139   - if (err) {
140   - console.log('Error while trying to retrieve access token', err);
141   - return;
142   - } else {
143   - oauth2Client.credentials = token;
144   - var params = {
145   - userId: 'me',
146   - fields: 'emails',
147   - auth: oauth2Client
148   - };
149   -
150   - plus.people.get(params, function (err, response) {
151   - if (err) {
152   - console.error(err)
153   - } else {
154   - storeToken(token, response.emails);
155   - }
156   - });
157   -
158   - return callback(null, oauth2Client);
159   - }
160   -
161   - })
162   - }
163   - });
  119 + Token.findOne({
  120 + email: 'zentoriono@gmail.com'
  121 + }, function (err, token) {
  122 + if (token) {
  123 + oauth2Client.credentials = JSON.parse(token);
  124 + return callback(null, oauth2Client);
  125 + } else {
  126 + oauth2Client.getToken(code, function (err, token) {
  127 + if (err) {
  128 + console.log('Error while trying to retrieve access token', err);
  129 + return;
  130 + } else {
  131 + oauth2Client.credentials = token;
  132 + var params = {
  133 + userId: 'me',
  134 + fields: 'emails',
  135 + auth: oauth2Client
  136 + };
  137 +
  138 + plus.people.get(params, function (err, response) {
  139 + if (err) {
  140 + console.error(err)
  141 + } else {
  142 + storeToken(token, response.emails);
  143 + }
  144 + });
  145 +
  146 + return callback(null, oauth2Client);
  147 + }
164 148  
165   - // fs.readFile(TOKEN_PATH, (err, token) => {
166   - // if (err) {
  149 + })
  150 + }
  151 + });
  152 + },
167 153  
168   - // } else {
  154 + listCalendar: (auth, callback) => {
  155 + calendar.calendarList.list({
  156 + auth: auth,
  157 + minAccessRole: 'owner'
  158 + }, (err, response) => {
  159 + if (err) return callback(err);
169 160  
170   - // }
171   - // });
  161 + return callback(null, response);
172 162 });
173 163 },
174 164  
175 165 listEvents: (auth, callback) => {
176 166 calendar.events.list({
177 167 auth: auth,
178   - calendarId: CALENDAR_ID || 'primary',
  168 + calendarId: CALENDAR_ID || 'primary', //CALENDAR_ID || 'primary'
179 169 maxResults: 50,
180 170 singleEvents: true,
181 171 orderBy: 'startTime'
... ... @@ -279,21 +269,26 @@ module.exports = {
279 269 }
280 270 },
281 271  
  272 + /**
  273 + * เธชเธฃเน‰เธฒเธ‡ JSON เธชเธณเธซเธฃเธฑเธšเธชเนˆเธ‡เน„เธ›เธญเธฑเธžเน€เธ”เธ•เธ‚เน‰เธญเธกเธนเธฅ event เธ›เธเธดเธ—เธดเธ™
  274 + * @param payload
  275 + * @returns {{}}
  276 + */
282 277 updateBuilder: (payload) => {
283   - var buildPayload = {}
  278 + var buildPayload = {};
284 279 try {
285   - buildPayload.calendarId = CALENDAR_ID
286   - buildPayload.eventId = payload.TaskID
287   - buildPayload.summary = payload.Title
288   - buildPayload.description = payload.Description
  280 + buildPayload.calendarId = CALENDAR_ID;
  281 + buildPayload.eventId = payload.TaskID;
  282 + buildPayload.summary = payload.Title;
  283 + buildPayload.description = payload.Description;
289 284 buildPayload.start = {
290 285 dateTime: moment(payload.Start).format("YYYY-MM-DDTHH:mm:ssZ"),
291 286 timeZone: hasTimezone(payload.StartTimezone)
292   - }
  287 + };
293 288 buildPayload.end = {
294 289 dateTime: moment(payload.End).format("YYYY-MM-DDTHH:mm:ssZ"),
295 290 timeZone: hasTimezone(payload.EndTimezone)
296   - }
  291 + };
297 292 if (payload.email) {
298 293 buildPayload.attendees = [{
299 294 email: payload.email
... ... @@ -326,5 +321,70 @@ module.exports = {
326 321 } finally {
327 322 return buildPayload
328 323 }
  324 + },
  325 +
  326 + /**
  327 + * API เธชเธฃเน‰เธฒเธ‡เธ›เธเธดเธ—เธดเธ™ เธญเธดเธ‡เธ•เธฒเธก summary(เธˆเธฐเธเธฅเธฒเธขเน€เธ›เน‡เธ™เธŠเธทเนˆเธญเธ‚เธญเธ‡เธ›เธเธดเธ—เธดเธ™) เธ—เธตเนˆเธกเธฒเธˆเธฒเธ request
  328 + * @googleAPI https://developers.google.com/apis-explorer/#p/calendar/v3/calendar.calendars.insert
  329 + * @param options
  330 + * @param callback
  331 + */
  332 + createCalendar: (options, callback) => {
  333 + calendar.calendars.insert({
  334 + auth: options.auth,
  335 + resource: options
  336 + }, (err, response) => {
  337 + if (err) return callback(err);
  338 +
  339 + return callback(null, response);
  340 + });
  341 +
  342 + },
  343 +
  344 + /**
  345 + * API เน€เธฃเธตเธขเธเธ‚เน‰เธญเธกเธนเธฅเธ›เธเธดเธ—เธดเธ™ เธญเธดเธ‡เธ•เธฒเธก id เธ—เธตเนˆเธกเธฒเธˆเธฒเธ request
  346 + * @googleAPI https://developers.google.com/apis-explorer/#p/calendar/v3/calendar.calendarList.get
  347 + * @param auth
  348 + * @param callback
  349 + */
  350 + getCalendar: (auth, callback) => {
  351 + calendar.calendars.get({
  352 + auth: auth,
  353 + calendarId: CALENDAR_ID || 'primary'
  354 + }, (err, response) => {
  355 + if (err) return callback(err);
  356 +
  357 + return callback(null, response);
  358 + });
  359 + },
  360 +
  361 + /**
  362 + * API เธฅเธšเธ›เธเธดเธ—เธดเธ™เน‚เธ”เธข เธญเธดเธ‡เธ•เธฒเธก id เธ—เธตเนˆเธกเธฒเธˆเธฒเธ request
  363 + * @googleAPI https://developers.google.com/apis-explorer/#p/calendar/v3/calendar.calendars.delete
  364 + * @param options
  365 + * @param callback
  366 + */
  367 + deleteCalendar: (options, callback) => {
  368 + calendar.calendars.delete({
  369 + auth: options.auth,
  370 + calendarId: options.calendarId
  371 + }, (err, response) => {
  372 + if (err) return callback(err);
  373 +
  374 + return callback(null, response);
  375 + });
  376 + },
  377 +
  378 + refreshToken: (options, callback) => {
  379 + oauth2Client.setCredentials(options.auth);
  380 + oauth2Client.refreshAccessToken(function(err, tokens) {
  381 + // your access_token is now refreshed and stored in oauth2Client
  382 + // store these new tokens in a safe place (e.g. database)
  383 + if (err) return callback(err);
  384 +
  385 + return callback(null, tokens);
  386 + });
329 387 }
330   -}
331 388 \ No newline at end of file
  389 +
  390 +
  391 +};
... ...
app/routes/home.routes.js
1 1 // var console = process.console
2   -var express = require('express')
3   -var router = express.Router()
4   -var home = require('../controllers/home.controller')
  2 +var express = require('express');
  3 +var router = express.Router();
  4 +var home = require('../controllers/home.controller');
5 5  
6   -router.get('/', home.home)
7   -router.get('/home', home.home)
  6 +router.get('/', home.home);
  7 +router.get('/home', home.home);
8 8  
9   -router.get('/events', home.events)
10   -router.post('/events', home.eventCreate)
11   -router.put('/events', home.eventUpdate)
12   -router.delete('/events', home.eventDelete)
13   -router.post('/setToken', home.setToken)
14   -router.get('/oauth2callback', home.oauth2callback)
  9 +router.get('/events', home.events);
  10 +router.post('/events', home.eventCreate);
  11 +router.put('/events', home.eventUpdate);
  12 +router.delete('/events', home.eventDelete);
  13 +router.post('/setToken', home.setToken);
  14 +router.get('/oauth2callback', home.oauth2callback);
15 15  
16   -module.exports = router
17 16 \ No newline at end of file
  17 +router.post('/calendars', home.createCalendar);
  18 +router.get('/calendars', home.getCalendar);
  19 +router.delete('/calendars', home.deleteCalendar);
  20 +
  21 +router.get('/refresh-token', home.refreshToken);
  22 +module.exports = router;
... ...
config/config.yml
... ... @@ -15,6 +15,12 @@ localhost:
15 15 pass:
16 16 timerecheck: '10000' #millisecond
17 17 apitimeout: 3000 #millisecond
18   - ggapi:
19   - calendarID: 'rvmbg3kg7uqninf7n3au1ku4mc@group.calendar.google.com'
20   - redirectUrl: 'http://localhost:3030/oauth2callback'
21 18 \ No newline at end of file
  19 + google:
  20 + calendar_id: 'rvmbg3kg7uqninf7n3au1ku4mc@group.calendar.google.com'
  21 + redirect_url: 'http://localhost:3030/oauth2callback'
  22 + client_id: "16634359544-7crvssfmpmtp0ng3jbipms65ccl9aol1.apps.googleusercontent.com"
  23 + project_id: "psyched-garage-146109"
  24 + auth_uri: "https://accounts.google.com/o/oauth2/auth"
  25 + token_uri: "https://accounts.google.com/o/oauth2/token"
  26 + auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs"
  27 + client_secret: "lpIa_7Wwbang6jTypMfCpOR6"
... ...