-
Notifications
You must be signed in to change notification settings - Fork 49
/
index.js
204 lines (167 loc) · 5.02 KB
/
index.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
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
const express = require('express');
const sharp = require('sharp');
const morgan = require('morgan');
const multer = require('multer');
const Redis = require('ioredis');
const request = require('request-promise-native');
const sha1 = require('sha1');
const Slack = require('slack-node');
const upload = multer({ storage: multer.memoryStorage() });
const SEVEN_DAYS = 7 * 24 * 60 * 60; // in seconds
//
// setup
const channel = process.env.SLACK_CHANNEL;
const appURL = process.env.APP_URL;
const redis = new Redis(process.env.REDIS_URL);
//
// slack
const slack = new Slack();
slack.setWebhook(process.env.SLACK_URL);
//
// express
const app = express();
const port = process.env.PORT || 11000;
app.use(morgan('dev'));
app.listen(port, () => {
console.log(`Express app running at http://localhost:${port}`);
});
//
// routes
app.post('/', upload.single('thumb'), async (req, res, next) => {
const payload = JSON.parse(req.body.payload);
const isVideo = (['movie', 'episode'].includes(payload.Metadata.type));
const isAudio = (payload.Metadata.type === 'track');
const key = sha1(payload.Server.uuid + payload.Metadata.ratingKey);
// missing required properties
if (!payload.user || !payload.Metadata || !(isAudio || isVideo)) {
return res.sendStatus(400);
}
// retrieve cached image
let image = await redis.getBuffer(key);
// save new image
if (payload.event === 'media.play' || payload.event === 'media.rate') {
if (image) {
console.log('[REDIS]', `Using cached image ${key}`);
} else {
let buffer;
if (req.file && req.file.buffer) {
buffer = req.file.buffer;
} else if (payload.thumb) {
console.log('[REDIS]', `Retrieving image from ${payload.thumb}`);
buffer = await request.get({
uri: payload.thumb,
encoding: null
});
}
if (buffer) {
image = await sharp(buffer)
.resize({
height: 75,
width: 75,
fit: 'contain',
background: 'white'
})
.toBuffer();
console.log('[REDIS]', `Saving new image ${key}`);
redis.set(key, image, 'EX', SEVEN_DAYS);
}
}
}
// post to slack
if ((payload.event === 'media.scrobble' && isVideo) || payload.event === 'media.rate') {
const location = await getLocation(payload.Player.publicAddress);
let action;
if (payload.event === 'media.scrobble') {
action = 'played';
} else if (payload.rating > 0) {
action = 'rated ';
for (var i = 0; i < payload.rating / 2; i++) {
action += ':star:';
}
} else {
action = 'unrated';
}
if (image) {
console.log('[SLACK]', `Sending ${key} with image`);
notifySlack(appURL + '/images/' + key, payload, location, action);
} else {
console.log('[SLACK]', `Sending ${key} without image`);
notifySlack(null, payload, location, action);
}
}
res.sendStatus(200);
});
app.get('/images/:key', async (req, res, next) => {
const exists = await redis.exists(req.params.key);
if (!exists) {
return next();
}
const image = await redis.getBuffer(req.params.key);
sharp(image).jpeg().pipe(res);
});
//
// error handlers
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send(err.message);
});
//
// helpers
function getLocation(ip) {
return request.get(`http://api.ipstack.com/${ip}?access_key=${process.env.IPSTACK_KEY}`, { json: true });
}
function formatTitle(metadata) {
if (metadata.grandparentTitle) {
return metadata.grandparentTitle;
} else {
let ret = metadata.title;
if (metadata.year) {
ret += ` (${metadata.year})`;
}
return ret;
}
}
function formatSubtitle(metadata) {
let ret = '';
if (metadata.grandparentTitle) {
if (metadata.type === 'track') {
ret = metadata.parentTitle;
} else if (metadata.index && metadata.parentIndex) {
ret = `S${metadata.parentIndex} E${metadata.index}`;
} else if (metadata.originallyAvailableAt) {
ret = metadata.originallyAvailableAt;
}
if (metadata.title) {
ret += ' - ' + metadata.title;
}
} else if (metadata.type === 'movie') {
ret = metadata.tagline;
}
return ret;
}
function notifySlack(imageUrl, payload, location, action) {
let locationText = '';
if (location) {
const state = location.country_code === 'US' ? location.region_name : location.country_name;
locationText = `near ${location.city}, ${state}`;
}
slack.webhook({
channel,
username: 'Plex',
icon_emoji: ':plex:',
attachments: [{
fallback: 'Required plain-text summary of the attachment.',
color: '#a67a2d',
title: formatTitle(payload.Metadata),
text: formatSubtitle(payload.Metadata),
thumb_url: imageUrl,
footer: `${action} by ${payload.Account.title} on ${payload.Player.title} from ${payload.Server.title} ${locationText}`,
footer_icon: payload.Account.thumb
}]
}, () => {});
}