summaryrefslogtreecommitdiffstats
path: root/server/lib/eventhelper.js
blob: e051620d611394b6226fe6e8157ae35f677d4acb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
}

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

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 }