-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
243 lines (199 loc) · 6.51 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// ======= Globals =======
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const RSS = require('rss');
const crypto = require('crypto');
const PORT = process.env.PORT || 8080;
const server_host = process.env.HOSTNAME || get_IP_address();
const TTL = process.env.TTL || 1;
const root_media_directory = '/usr/share/media';
const accepted_mime_types = [
"image/png",
"image/jpg",
"image/bmp",
"video/mp4",
"video/x-msvideo",
"video/h264",
"video/mp2t",
"video/mpeg",
"video/webm",
"video/x-matroska",
"video/quicktime",
"video/x-motion-jpeg"
]
// ======= Feed generator =======
function create_RSS_feed(media_directory) {
fs.readdir(media_directory, (err, files) => {
let promise_map = files.map((file) => {
let fileDetails = fs.lstatSync(path.resolve(media_directory, file));
if (!fileDetails.isDirectory()) {
item_url = `${media_directory}/${file}`
return get_checksum(item_url);
}
});
Promise.all(promise_map).then((value) => {
const feed_base_url = `http://${server_host}:${PORT}/`;
feed_name = feed_dir_to_name(media_directory);
let feed_is_empty = true;
let feed = new RSS({
title: `${feed_name} MRSS Feed`,
description: 'MRSS feed for Brightsign player',
feed_url: `${feed_base_url}${feed_name}_feed.xml`,
site_url: feed_base_url,
ttl: TTL.toString(),
custom_namespaces: {
'media': 'http://search.yahoo.com/mrss/'
}
});
value.forEach((item) => {
if (!item) {
return false;
}
item.mime_type = mime.getType(item.path);
if (!accepted_mime_types.includes(item.mime_type)) {
return false;
}
item.url = encodeURI(feed_base_url + item.path.replace('/usr/share/', ''));
feed_is_empty = false;
feed.item(MRSS_item(item));
});
if (feed_is_empty) {
feed.item(MRSS_item({
url: encodeURI(feed_base_url + 'img/no_feed.png'),
mime_type: 'image/png',
path: './public/img/no_feed.png',
hash: 'nofeed'
}));
}
fs.writeFile(`public/${feed_name}_feed.xml`, feed.xml(), function (err) {
if (err) {
console.err(err);
}
console.log(`public/${feed_name}_feed.xml was saved`);
});
})
});
}
function MRSS_item(item) {
item.size = fs.statSync(item.path).size
return {
title: path.basename(item.path),
guid: item.hash,
description: '',
url: item.url,
categories: [item.mime_type.split("/")[0]],
custom_elements: [{
'media:content': {
_attr: {
url: item.url,
fileSize: item.size,
type: item.mime_type,
medium: item.mime_type.split("/")[0]
}
}
}]
}
}
// ======= Watch /media folder =======
function refresh_RSS_feeds() {
const feed_directories = get_directories_recursive(root_media_directory);
feed_directories.forEach(directory => {
create_RSS_feed(directory);
});
// Remove orphan feeds
const feed_list = feed_directories.map((value, index) => {
return `${feed_dir_to_name(value)}_feed.xml`;
});
fs.readdirSync('public').forEach(file => {
if (!file.endsWith('_feed.xml')) {
return false;
}
if (feed_list.includes(file)) {
return false;
} else {
const orphan_feed = path.resolve('public', file);
fs.stat(orphan_feed, function (err, stats) {
if (err) {
return console.error(err);
}
fs.unlink(orphan_feed,function(err){
if(err) return console.log(err);
console.log(`${file} feed deleted successfully`);
});
});
}
});
}
refresh_RSS_feeds();
fs.watch(root_media_directory, { recursive: true }, (eventType, filename) => {
console.log('Watch event:', eventType, 'File:', filename);
refresh_RSS_feeds();
});
// ======= Static web server =======
const express = require('express');
const app = express();
app.set('trust proxy', true)
const logger = function (request, response, next) {
const date = new Date();
console.log(date.toISOString(), "- Served:", request.path);
next();
}
app.use(logger); // for all routes.
app.use(express.static('public'));
app.use('/media', express.static('../../share/media'));
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
// ======= Utilities =======
function get_directories(dirpath) {
return fs
.readdirSync(dirpath)
.map(file => path.join(dirpath, file))
.filter(
pth =>
fs.statSync(pth).isDirectory(),
);
}
function get_directories_recursive(dirpath) {
return [
dirpath,
...flatten(
get_directories(dirpath).map(get_directories_recursive),
),
];
}
function flatten(arr) {
return arr.slice().flat();
}
function get_IP_address() {
var interfaces = require('os').networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
return alias.address;
}
}
}
return '0.0.0.0';
}
function get_checksum(path) {
return new Promise(function (resolve, reject) {
const hash = crypto.createHash('md5');
const input = fs.createReadStream(path);
input.on('error', reject);
input.on('data', function (chunk) {
hash.update(chunk);
});
input.on('close', function () {
resolve({
path: path,
hash: hash.digest('hex')
});
});
});
}
function feed_dir_to_name(dir) {
const feed_dir = dir.replace(root_media_directory, '');
return feed_dir.replace(/\//g, '_').replace('_', '');
}