summaryrefslogtreecommitdiffstats
path: root/server/bin/scheduler.js
blob: ddb96d85b6f4382a90669ef404f68f5cad2af32f (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
75
76
77
78
/* global __appdir */
const path = require('path')
global.__appdir = path.join(__dirname, '..')
const db = require(path.join(__appdir, 'lib', 'sequelize'))
const groupHelper = require(path.join(__appdir, 'lib', 'grouphelper'))
const wolHelper = require(path.join(__appdir, 'lib', 'wolhelper'))
const zmq = require('zeromq')
const socket = zmq.socket('pull')
socket.bindSync('ipc:///tmp/bas_zeromq_events')
socket.on('message', calcNextWake)

const runningTimeouts = {}

async function calcNextWake (id) {
  id = id.toString()
  var event = await db.event.findOne({ where: { id: id }, include: ['groups', 'clients'] })

  // Event got deleted
  if (event === null || !event.wakeonlan) {
    clearTimeout(runningTimeouts[id])
    delete runningTimeouts[id]
    return
  }

  var nextWake
  var times = JSON.parse(event.times)
  var now = new Date()

  if (!times.repetitive) {
    var start = new Date(times.start * 1000)
    if (start > now) {
      // 1. Calculate next wake
      nextWake = start - now

      // 2. Set timeout
      runningTimeouts[id] = setTimeout(function () {
        wakeUpClients(id)
      }, nextWake)
    }
  } else {
    return false
    /*
    // 1. Calculate next wake
    nextWake = 99999999999

    // 2. Set timeout
    runningTimeouts[id] = setTimeout(function () {
      wakeUpClients(id)
      calcNextWake(id)
    }, nextWake)
    */
  }
}

// Wake all clients of event
async function wakeUpClients (id) {
  var event = await db.event.findOne({ where: { id: id }, include: ['groups', 'clients'] })
  if (!event.wakeonlan) return

  // 1. Fetch all clients
  var clients = []
  var groups = []
  var blacklistClients = []
  var blacklistGroups = []
  for (let i = 0; i < event.clients.length; i++) {
    if (event.clients[i].client_x_event.blacklist) blacklistClients.push(event.clients[i])
    else clients.push(event.clients[i])
  }
  for (let i = 0; i < event.groups.length; i++) {
    if (event.groups[i].group_x_event.blacklist) blacklistGroups.push(event.groups[i])
    else groups.push(event.groups[i])
  }
  var childs = await groupHelper.getAllChildren(groups, blacklistGroups, blacklistClients)
  clients = clients.concat(childs.clients)

  // 2. Wake all clients
  wolHelper.wakeUp(clients)
}