summaryrefslogtreecommitdiffstats
path: root/server/api/events.js
blob: 7e330e5204d28fc309869fc4a2d9a740a89e9ed6 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))
var groupHelper = require(path.join(__appdir, 'lib', 'grouphelper'))
var express = require('express')
const { decorateApp } = require('@awaitjs/express')
var router = decorateApp(express.Router())
const zmq = require('zeromq')
const socket = zmq.socket('push')
socket.connect('ipc:///tmp/bas_zeromq_events')
const log = require(path.join(__appdir, 'lib', 'log'))
const HttpResponse = require(path.join(__appdir, 'lib', 'httpresponse'))

// ############################################################################
// ###########################  GET requests  #################################

/*
  * @return: Returns event of given id.
  */
router.getAsync('/:id', async (req, res) => {
  var event = await db.event.findOne({ where: { id: req.params.id }, include: ['config', 'clients', 'groups'] })
  if (event) res.send(event)
  else res.status(404).end()
})

/*
   * @return: Returns a list of all events in the database.
   */
router.getAsync('', async (req, res) => {
  var events = await db.event.findAll({ include: ['config', 'clients', 'groups'] })
  if (events) res.status(200).send(events)
  else res.status(404).end()
})

// ############################################################################
// ##########################  POST requests  #################################

/*
 * @return: Returns a list of all childs of the given groups
 * Is also used by the PermissionManager Frontend to get it's blacklist childs
 */
router.postAsync('/blacklist', async (req, res) => {
  if (req.body.groups) {
    var blacklist = await groupHelper.getAllChildren(req.body.groups)
    res.send(blacklist)
  } else res.status(404).end()
})

// Create, Update or Delete POST
router.postAsync(['', '/:id'], async (req, res) => {
  if (req.query.delete !== undefined && req.query.delete !== 'false') {
    const user = await db.user.findOne({ where: { id: req.user.id } })

    // Only need to log batch request if there is more than one event to delete.
    if (req.body.ids.length > 1) {
      await log({
        category: 'EVENT_BATCH_DELETE',
        description: 'Event batch deletion of ' + req.body.ids.length + ' events initiated by user.',
        user,
        userId: req.user.id
      })
    }

    let deletionCounter = 0
    // Delete every event on its own, to get a better log
    for (let index in req.body.ids) {
      const event = await db.event.findOne({ where: { id: req.body.ids[index] } })
      const count = await db.event.destroy({ where: { id: req.body.ids[index] } })
      if (count !== 1) {
        await log({
          category: 'ERROR_EVENT_DELETE',
          description: '[' + event.id + '] ' + event.name + ': Event could not be deleted.\n' +
                       'ID: ' + event.id + '\n' +
                       'Name: ' + event.name + '\n' +
                       'Description: ' + event.description + '\n' +
                       'Times: ' + event.times + '\n' +
                       'Important: ' + event.important + '\n' +
                       'Wake-on-Lan: ' + event.wakeonlan + '\n' +
                       'Config ID: ' + event.configId,
          user,
          userId: req.user.id
        })
      } else {
        await log({
          category: 'EVENT_DELETE',
          description: '[' + event.id + '] ' + event.name + ': Event successfully deleted.\n' +
                       'ID: ' + event.id + '\n' +
                       'Name: ' + event.name + '\n' +
                       'Description: ' + event.description + '\n' +
                       'Times: ' + event.times + '\n' +
                       'Important: ' + event.important + '\n' +
                       'Wake-on-Lan: ' + event.wakeonlan + '\n' +
                       'Config ID: ' + event.configId,
          user,
          userId: req.user.id
        })
        deletionCounter++
      }
    }
    if (req.body.ids.length > 1) {
      log({
        category: 'EVENT_BATCH_DELETE',
        description: deletionCounter + '/' + req.body.ids.length + ' events successfully deleted.',
        user,
        userId: req.user.id
      })
    }
    HttpResponse.successBatch('deleted', 'event', deletionCounter).send(res)

    await db.event.destroy({ where: { id: req.body.ids } }).then(count => { res.send({ count }) })
    req.body.ids.forEach(id => {
      socket.send(id)
    })
  } else {
    var promises = []
    var promisesBlacklist = []
    var eventDb
    if (req.body.config.length !== 1) req.body.config = null
    if (req.body.times.length === 0) req.body.times = null
    if (req.params.id > 0) {
      // Update existing event
      eventDb = await db.event.findOne({ where: { id: req.params.id } })
      if (eventDb !== null) {
        promises.push(eventDb.update({ name: req.body.name, description: req.body.description, times: req.body.times, important: req.body.important, wakeonlan: req.body.wakeonlan, configId: req.body.config || null }))
        promises.push(eventDb.setGroups(req.body.groups, { through: { blacklist: 0 } }))
        promises.push(eventDb.setClients(req.body.clients, { through: { blacklist: 0 } }))
        await Promise.all(promises)
        promisesBlacklist.push(eventDb.addGroups(req.body.blacklistGroups, { through: { blacklist: 1 } }))
        promisesBlacklist.push(eventDb.addClients(req.body.blacklistClients, { through: { blacklist: 1 } }))
        await Promise.all(promisesBlacklist)
        log({
          category: 'EVENT_EDIT',
          description: '[' + eventDb.id + '] ' + eventDb.name + ': Event successfully edited.\n' +
                       'ID: ' + eventDb.id + '\n' +
                       'Name: ' + eventDb.name + '\n' +
                       'Description: ' + eventDb.description + '\n' +
                       'Times: ' + eventDb.times + '\n' +
                       'Important: ' + eventDb.important + '\n' +
                       'Wake-on-Lan: ' + eventDb.wakeonlan + '\n' +
                       'Config ID: ' + eventDb.configId + '\n' +
                       'Groups: ' + req.body.groups + '\n' +
                       'Clients: ' + req.body.clients + '\n' +
                       'Blacklist-Groups: ' + req.body.blacklistGroups + '\n' +
                       'Blacklist-Clients: ' + req.body.blacklistClients,
          userId: req.user.id
        })

        socket.send(eventDb.id)
        res.send({ id: req.params.id })
      } else {
        res.status(404).end()
      }
    } else if (req.params.id === undefined) {
      // Create new event
      eventDb = await db.event.create({ name: req.body.name, description: req.body.description, times: req.body.times, important: req.body.important, wakeonlan: req.body.wakeonlan, configId: req.body.config || null })
      promises.push(eventDb.setGroups(req.body.groups, { through: { blacklist: 0 } }))
      promises.push(eventDb.setClients(req.body.clients, { through: { blacklist: 0 } }))
      await Promise.all(promises)
      promisesBlacklist.push(eventDb.addGroups(req.body.blacklistGroups, { through: { blacklist: 1 } }))
      promisesBlacklist.push(eventDb.addClients(req.body.blacklistClients, { through: { blacklist: 1 } }))
      await Promise.all(promisesBlacklist)
      log({
        category: 'EVENT_CREATE',
        description: '[' + eventDb.id + '] ' + eventDb.name + ': Event successfully created.\n' +
                     'ID: ' + eventDb.id + '\n' +
                     'Name: ' + eventDb.name + '\n' +
                     'Description: ' + eventDb.description + '\n' +
                     'Times: ' + eventDb.times + '\n' +
                     'Important: ' + eventDb.important + '\n' +
                     'Wake-on-Lan: ' + eventDb.wakeonlan + '\n' +
                     'Config ID: ' + eventDb.configId + '\n' +
                     'Groups: ' + req.body.groups + '\n' +
                     'Clients: ' + req.body.clients + '\n' +
                     'Blacklist-Groups: ' + req.body.blacklistGroups + '\n' +
                     'Blacklist-Clients: ' + req.body.blacklistClients,
        userId: req.user.id
      })
      socket.send(eventDb.id)
      res.send({ id: req.body.id })
    }
  }
})

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

module.exports.router = router