summaryrefslogblamecommitdiffstats
path: root/server/lib/eventhelper.js
blob: 26fe1fccfc49fd1ec76fcca3538b1c5c05a7f365 (plain) (tree)
1
2
3
4
5
6
7




                                                            

 







































                                                                                       
   

 







                                                 

 





                                                                                             
 
 
                                                   
const { RRule } = require('rrule')

function _fakeUTCToDate (fakeUTC) {
  const isoString = fakeUTC.toISOString()
  return new Date(isoString.substr(0, isoString.length - 1))
}

function _pad (x) {
  return x < 10 ? '0' + x : x
}

// ####################################################################################
// ####################################################################################

class Schedule {
  constructor (event) {
    const splitStart = event.start.split(' ')
    const splitStartTime = splitStart.split(':')
    const rule = {
      dtstart: new Date(event.start + 'Z'),
      until: new Date(event.start + 'Z'),
      interval: event.interval,
      byhour: splitStartTime[0],
      byminute: splitStartTime[1]
    }
    if (event.intervalType === 'month') rule.freq = RRule.MONTHLY
    else if (event.intervalType === 'month') rule.freq = RRule.WEEKLY
    else rule.freq = RRule.DAILY
    this.rrule = new RRule(rule)
    this.endTime = event.end.split(' ')[1]
  }

  next () {
    const now = formatDate(new Date())
    return _fakeUTCToDate(this.rrule.after(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) {
  if (event.repetitive) {
    const schedule = new Schedule(event)
    return schedule.isActive(new Date())
  } else {
    const now = formatDate(new Date())
    return event.start <= now && now <= event.end
  }
}

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 }