-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnotifier.js
85 lines (71 loc) · 1.9 KB
/
notifier.js
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
const express = require('express');
const app = express();
const port = process.env.PORT || 1337;
// Register all available notification handlers.
const handlers = {
telegram: require('./interface/telegram'),
discord: require('./interface/discord')
};
// Parse JSON request bodies.
app.use(express.json({
type: 'application/vnd.docker.distribution.events.v1+json'
}));
// POST endpoint for /docker.
app.post('/docker', async (req, res, next) => {
const events = req.body.events;
// Check the body for validity.
if (!events || events.constructor === Object && Object.keys(events).length === 0) {
return res.status(400).end();
}
// Send response first, docker registry could be set as being impatient.
res.header('Content-type', 'text/html');
res.sendStatus(200);
try {
// Attempt to handle the event array.
for (event of events) {
await handleEvent(event);
}
} catch (error) {
next(error);
}
});
// Default error handler.
app.use(async (err, req, res, next) => {
console.error(err);
await handlers.telegram.sendError(err);
res.status(500).json({ error: err.message });
});
// Start listening.
app.listen(port, () => {
console.log(`Notification handler listening on port ${port}`);
});
/**
* Handles an incoming docker event.
*
* @param {object} event
* @returns {Promise<void>}
*/
async function handleEvent(event) {
if (event.target.tag && canHandleEvent(event)) {
console.log(`Handling ${event.action} event ${event.id}!`);
for (handler in handlers) {
console.log(`Firing ${handler} handler!`);
try {
await handlers[handler].send(event);
} catch (error) {
console.error(error.message);
}
}
}
}
/**
* Returns whether an event can be handled based on its method and action.
*
* @param {object} event
* @returns {boolean}
*/
function canHandleEvent(event) {
return [
'PUT_push'
].includes(`${event.request.method}_${event.action}`);
}