events.js 5.71 KB
var express = require('express');
var router = express.Router();
var gcal = require('google-calendar');
const request = require('request');
const querystring = require('querystring');

var googleToken;
var kakaoToken;
var id;
var events = new Array();


router.get('/', function(req, res, next) {
    console.log(id);
    gcal(googleToken).events.list(id,{maxResult:1},function(err,data){
        if(err) return console.log(err);
        else {
            events = data.items;
            if(events.length>1){
                events.sort(function (a,b){
                var at= a.start.dateTime.split(/[-:+T]/);
                var aDate = new Date(at[0],at[1]-1,at[2],at[3],at[4],at[5]);
                var bt= b.start.dateTime.split(/[-:+T]/);
                var bDate = new Date(bt[0],bt[1]-1,bt[2],bt[3],bt[4],bt[5]);
                return bDate-aDate;
                });
            }
            checkEvents();
            res.render("events",{id:id,calendars:data.items});
            }
      });  
});
router.post('/', function(req, res, next) {
    googleToken = req.body.googleToken;
    kakaoToken = req.body.kakaoToken;
    id = req.body.id;
    gcal(googleToken).events.list(id,{maxResult:1},function(err,data){
        if(err) return console.log(err);
        else {
            events = data.items;
            if(events.length>1){
                events.sort(function (a,b){
                var at= a.start.dateTime.split(/[-:+T]/);
                var aDate = new Date(at[0],at[1]-1,at[2],at[3],at[4],at[5]);
                var bt= b.start.dateTime.split(/[-:+T]/);
                var bDate = new Date(bt[0],bt[1]-1,bt[2],bt[3],bt[4],bt[5]);
                return bDate-aDate;
                });
            }
            checkEvents();
            res.render("events",{id:id,calendars:data.items});
            }
      });  
});
router.post('/add', function(req, res, next) {
    var sday = req.body.startDay.split('-');
    var stime = req.body.startTime.split(':');
    var start= timestamp(new Date(sday[0],sday[1]-1,sday[2],stime[0],stime[1],0));
    var eday = req.body.endDay.split('-');
    var etime = req.body.endTime.split(':');
    var end = timestamp(new Date(eday[0],eday[1]-1,eday[2],etime[0],etime[1],0));
    var event={
        'summary':req.body.summary,
        'location':req.body.location,
        'description':req.body.description,
        'start':{
            'dateTime':start
        },
        'end':{
            'dateTime':end,
        }
    }
    gcal(googleToken).events.insert(id,event,function(err,data){
        if(err) return console.log(err);
        else res.redirect('/events');
      });  
    
});

router.post('/remove', function(req, res, next) {
    var eId = req.body.eId;
    gcal(googleToken).events.delete(id, eId, function(err, data) {
        if(err) return res.send(err);
        return res.redirect('/events');
      });
    
});


var timestamp = function (date) {
    var pad = function (amount, width) {
     var padding = "";
     while (padding.length < width - 1 && amount < Math.pow(10, width - padding.length - 1))
      padding += "0";
     return padding + amount.toString();
    }
    date = date ? date : new Date();
    var offset = date.getTimezoneOffset();
    var Month; var year;
   
  
    return pad(date.getFullYear(), 4)
      + "-" + pad(date.getMonth()+1, 2)
      + "-" + pad(date.getDate(), 2)
      + "T" + pad(date.getHours(), 2)
      + ":" + pad(date.getMinutes(), 2)
      + ":" + pad(date.getSeconds(), 2)
      + (offset > 0 ? "-" : "+")
      + pad(Math.floor(Math.abs(offset) / 60), 2)
      + ":" + pad(Math.abs(offset) % 60, 2);
   }

   function checkEvents(){
       var nDate = new Date();
       for(var i = 0;i<events.length;i++){
           var time = events[i].start.dateTime.split(/[-:+T]/);
           var tDate = new Date(time[0],time[1]-1,time[2],time[3],time[4],time[5]);
           if(nDate.getFullYear()==tDate.getFullYear()&&nDate.getMonth()==tDate.getMonth()&&nDate.getDate()==tDate.getDate()){
               if((tDate.getHours()-nDate.getHours())==1){
                   var minute = 60-nDate.getMinutes();
                   if(minute<=10) 
                        sendMessage(events[i],minute);
               }
               else if((tDate.getHours()-nDate.getHours())==0){
                    var minute = tDate.getMinutes()-nDate.getMinutes();
                    if(minute<=10&&minute>0) 
                        sendMessage(events[i],minute);
               }
           }
       }
   };

   function sendMessage(event,minute){
        let template_objectObj = {
            "object_type" : 'text',
            "text" : " [Reminder Talk]\n"+"일정 : "+event.summary+
            "\n시작 : " + event.start.dateTime+"\n종료 : "+event.end.dateTime+"\n일정시작까지 "+minute+"분 남았습니다!",
            "link":{
                "web_url" :'https://developers.kakao.com',
                "mobile_web_url" : 'https://developers.kakao.com',
            },
            "button_title": "일정 확인하기"
        };
        let template_objectStr = JSON.stringify(template_objectObj);
        let options = {
            url : 'https://kapi.kakao.com/v2/api/talk/memo/default/send',
            method : 'POST',
            headers:{
                'Authorization' :'Bearer '+kakaoToken,
                'Content-Type' :'application/x-www-form-urlencoded',
            },
            form : {
                template_object : template_objectStr,
            }
        }
        request(options, callback);
   };

   

   function callback(error,response,body){
        console.log(response.statusCode);
        if(!error && response.statusCode==200){
            console.log(body);
        }
    }
   

   setInterval(checkEvents,5*60*1000);
   //5분에 한 번 수행

module.exports = router;