我需要获取谷歌日历中的免费插槽列表。现在我只是获取事件列表。我正在使用google calendar npm。
google_calendar.events.list(calObj.name,{
timeMin: "2018-03-02T08:00:00.000Z",
timeMax: "2018-03-02T16:00:00.000Z",
singleEvents: true,
orderBy: "startTime"
}, function (err, eventList) {
// handle to get output like
// freeSlots -> [{
// "startDate": "2018-03-02T08:00:00.000Z",
// "endDate": "2018-03-02T09:00:00.000Z"
// },{
// "startDate": "2018-03-02T07:00:00.000Z",
// "endDate": "2018-03-02T08:00:00.000Z"
// }]
// if at this day are events between 10:00 and 16:00 (so calendar is busy)
})
答案 0 :(得分:1)
您可以通过两个步骤从Google日历获得免费插槽。使用npm google-calendar
首先,您需要在日历中获得所有空闲/忙碌时间
var startDate = new Date(),
endDate = new Date();
var rootStart = startDate,
rootEnd = endDate;
gcal(<accessToken>).freebusy.query({
"items":[{
"id": calObj.name
}],
"timeMin": startDate.toISOString(),
"timeMax": endDate.toISOString(),
"timeZone": "GMT+0100"
},{
fields: "calendars,groups,kind,timeMax,timeMin",
alt:"json"
}, function(err, data) {
if(err) return console.log(err)
// then calculate free slots
return slotsFromEvents(startDate, data.calendars[<calName>].busy)
})
var interval = 2, // how big single slot should be (in this case 2 hrs)
freeSlots = [];
function slotsFromEvents(date,events) {
events.forEach(function (event, index) { //calculate free from busy times
if (index == 0 && startDate < event.start) {
freeSlots.push({startDate: startDate, endDate: event.start});
}
else if (index == 0) {
startDate = event.end;
}
else if (events[index - 1].end < event.start) {
freeSlots.push({startDate: events[index - 1].end, endDate: event.start});
}
if (events.length == (index + 1) && event.end < endDate) {
freeSlots.push({startDate: event.end, endDate: endDate});
}
});
if (events.length == 0) {
freeSlots.push({startDate: startDate, endDate: endDate});
}
var temp = {}, hourSlots = [];
freeSlots.forEach(function(free, index) {
var freeHours = new Date(free.endDate).getHours() - new Date(free.startDate).getHours(), freeStart = new Date(free.startDate), freeEnd = new Date(free.endDate);
while(freeStart.getHours()+freeHours+interval>=0) { // 11 + 4 + 2 >= 0
if(freeHours>=interval) {
temp.e = new Date(free.startDate);
temp.e.setHours(temp.e.getHours()+freeHours);
temp.s = new Date(free.startDate);
temp.s.setHours(temp.s.getHours()+freeHours-interval);
if(temp.s.getHours() >= rootStart.getHours() && temp.e.getHours() <= rootEnd.getHours()) {
hourSlots.push({calName: calObj.name, startDate:temp.s, endDate:temp.e});
temp = {};
}
}
freeHours--;
}
})
// callBack(freeSlots, hourSlots);
}