const { RRule } = require('rrule') function _fakeUTCToDate (fakeUTC) { if (!fakeUTC) return const isoString = fakeUTC.toISOString() return new Date(isoString.substr(0, isoString.length - 1)) } function _pad (x) { return x < 10 ? '0' + x : x } // #################################################################################### // #################################################################################### const rruleWeekdays = [RRule.MO, RRule.TU, RRule.WE, RRule.TH, RRule.FR, RRule.SA, RRule.SU] class Schedule { constructor (event) { const times = JSON.parse(event.times) const splitStart = times.start.split(' ') const splitStartTime = splitStart[1].split(':') const rule = { dtstart: new Date(times.start + 'Z'), until: new Date(times.end + 'Z'), interval: times.interval, byhour: [splitStartTime[0]], byminute: [splitStartTime[1]], byweekday: times.dayMap.reduce((arr, v, i) => { if (v) arr.push(rruleWeekdays[i]); return arr }, []), bymonth: times.monthMap.reduce((arr, v, i) => { if (v) arr.push(i + 1); return arr }, []) } if (times.intervalType === 'month') rule.freq = RRule.MONTHLY else if (times.intervalType === 'week') rule.freq = RRule.WEEKLY else rule.freq = RRule.DAILY this.rrule = new RRule(rule) this.endTime = times.end.split(' ')[1] } next () { const now = formatDate(new Date()) return _fakeUTCToDate(this.rrule.after(new Date(now + 'Z'))) } isValid (date) { date = formatDate(date) const lastDate = formatDate(this.rrule.before(new Date(date + 'Z'), true)) let lastDateEnd = lastDate.split(' ')[0] + ' ' + this.endTime if (lastDateEnd < lastDate) { let d = new Date(lastDateEnd) d.setDate(d.getDate() + 1) lastDateEnd = formatDate(d) } return lastDate <= date && date <= lastDateEnd } } function isActive (event) { const times = JSON.parse(event.times) const now = formatDate(new Date()) if (now < times.start || times.end < now) return false if (times.repetitive) return (new Schedule(event)).isValid(now) else return true } function formatDate (date) { if (typeof date === 'string') return date let result = '' result += date.getFullYear() + '-' + _pad(date.getMonth() + 1) + '-' + _pad(date.getDate()) result += ' ' + _pad(date.getHours()) + ':' + _pad(date.getMinutes()) return result } module.exports = { Schedule, isActive, formatDate }