-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpressAPI.mjs
216 lines (180 loc) · 6.95 KB
/
expressAPI.mjs
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// API ROUTER | AUSTIN GINN 2023
import express from 'express';
import cronParser from 'cron-parser';
import cron from 'node-cron';
const router = express.Router();
// Middleware to parse JSON request bodies
router.use(express.json());
// TVControl API routes
export default function expressAPI(TVs, tvFileHandler, cronJobs, tcl, logger) {
// API version endpoint
router.get('/', (req, res) => {
// console.log(TVs);
return res.status(200).json({ version: '1.0' });
});
// GET data
router.get('/data', (req, res) => {
return res.status(200).json(TVs);
});
// add a new tv
router.post('/tv/add', async (req, res) => {
try {
// console.log(req.body);
const { name, ipAddress, group, description } = req.body;
// Check if the TV already exists
if (TVs.tvs.find((tv) => tv.ipAddress === ipAddress)) {
return res.status(409).json({ error: `TV '${ipAddress}' already exists.` });
}
// save the new TV
TVs.tvs.push({ name, ipAddress, group, description });
await tvFileHandler.saveJSON(TVs);
logger.info('Added new TV: ' + name + " - " + ipAddress);
return res.status(201).json({ message: 'TV added successfully' });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ error: 'Internal server error' });
}
});
// Update a TV
router.put('/tv/update', async (req, res) => {
try {
const { name, ipAddress, group, description } = req.body;
// Check if the TV exists
const tvIndex = TVs.tvs.findIndex((tv) => tv.ipAddress === ipAddress);
if (tvIndex === -1) {
return res.status(404).json({ error: `TV '${ipAddress}' does not exist` });
}
// Update the TV
TVs.tvs[tvIndex] = { name, ipAddress, group, description };
await tvFileHandler.saveJSON(TVs);
logger.info("Updated TV: " + name + " - " + ipAddress);
return res.status(200).json({ message: 'TV updated successfully' });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ error: 'Internal server error' });
}
});
// Delete a TV
router.delete('/tv/delete', async (req, res) => {
try {
const { ipAddress } = req.query;
// Check if the TV exists
const tvIndex = TVs.tvs.findIndex((tv) => tv.ipAddress === ipAddress);
if (tvIndex === -1) {
return res.status(404).json({ error: `TV '${ipAddress}' does not exist` });
}
TVs.tvs.splice(tvIndex, 1);
await tvFileHandler.saveJSON(TVs);
logger.info("Deleted TV: " + ipAddress);
return res.status(200).json({ message: 'TV deleted successfully' });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ error: 'Internal server error' });
}
});
// add a new group
router.post('/group/add', async (req, res) => {
try {
// console.log(req.body);
const { name, powerOn, powerOff } = req.body;
// Check if the TV already exists
if (TVs.groups.find((group) => group.name === name)) {
return res.status(409).json({ error: `Group '${name}' already exists.` });
}
//would be nice to save a human readable string as well.
// save the new TV
TVs.groups.push({ name, powerOn, powerOff });
await tvFileHandler.saveJSON(TVs);
logger.info("Added new group - " + name + ". Starting cron job...");
if (powerOn != "") {
const onCron = cron.schedule(powerOn, async () => {
//Power on all tvs in the group
logger.info("Powering on all tvs in group: " + name);
for (let i = 0; i < TVs.tvs.length; i++) {
logger.info("Powering on tv: " + TVs.tvs[i].name);
try {
await tcl.powerOn(TVs.tvs[i].ipAddress);
} catch (error) {
logger.error(error.message);
}
}
});
cronJobs[name + " - on"] = onCron;
}
if (powerOff != "") {
const offCron = cron.schedule(powerOff, async () => {
//Power on all tvs in the group
logger.info("Powering off all tvs in group: " + name);
for (let i = 0; i < TVs.tvs.length; i++) {
logger.info("Powering off tv: " + TVs.tvs[i].name);
try {
await tcl.powerOff(TVs.tvs[i].ipAddress);
} catch (error) {
logger.error(error.message);
}
}
});
cronJobs[name + " - off"] = offCron;
}
return res.status(201).json({ message: 'Group added successfully' });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ error: 'Internal server error' });
}
});
// Delete a group
// TODO - delete group from tvs
router.delete('/group/delete', async (req, res) => {
try {
const { name } = req.query;
// Check if the group exists
const groupIndex = TVs.groups.findIndex((group) => group.name === name);
if (groupIndex === -1) {
return res.status(404).json({ error: `Group'${name}' does not exist` });
}
TVs.groups.splice(groupIndex, 1);
//Try to stop the cron job if it exists and log it to the console
logger.info("Attempting to stop cron jobs");
if (cronJobs[name + " - on"]) {
cronJobs[name + " - on"].stop();
logger.info("Stopped cron job: " + name + " - on");
}
if (cronJobs[name + " - off"]) {
cronJobs[name + " - off"].stop();
logger.info("Stopped cron job: " + name + " - off");
}
await tvFileHandler.saveJSON(TVs);
// console.log(TVs);
return res.status(200).json({ message: 'Group deleted successfully' });
} catch (error) {
logger.error(error.message);
return res.status(500).json({ error: 'Internal server error' });
}
});
// //API endpoint that returns a cron expression based on human readable input
// router.post('/cron', async (req, res) => {
// try {
// const { humanReadable } = req.body;
// const cronExpression = cronParser.parseExpression(humanReadable);
// return res.status(200).json({ cronExpression: cronExpression });
// } catch (error) {
// console.error('Error:', error);
// return res.status(500).json({ error: 'Internal server error' });
// }
// });
// // Power on a TV
// router.post('/power-on', async (req, res) => {
// // Implement the logic to power on the TV using the provided IP address
// const { ipAddress } = req.body;
// console.log(`TV at ${ipAddress} powered on`);
// return res.status(200).json({ message: `TV at ${ipAddress} powered on` });
// });
// // Power off a TV
// router.post('/power-off', async (req, res) => {
// // Implement the logic to power off the TV using the provided IP address
// const { ipAddress } = req.body;
// console.log(`TV at ${ipAddress} powered off`);
// return res.status(200).json({ message: `TV at ${ipAddress} powered off` });
// });
return router;
}