-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
263 lines (219 loc) · 7.89 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/**
* Created by solvek on 08.02.16.
*/
"use strict";
var fs = require('fs');
var http = require("http");
var urlParse = require("url").parse;
var m3u = require('m3ujs');
class Pled{
/**
* @param {Object|string[]} options Pled options object or array of sources
* @param {string[]} options.sources Sources of m3u files. Each source is either a path
* to local file of a url to an http file (starting from "http://" or "https://")
* @param {FilterFunction[]} [options.filters] Sequence of filters
* @param {string} [options.cachePath] Path to cache file
* @param {int} [options.cacheTime=5*24*60*60*1000] Time for cache in milliseconds. By default 5 days
* to not use the cache but regenerate content (however resulting content still can be saved to the cache)
*/
constructor(options){
if (Array.isArray(options)){
options = {sources: options};
}
if (!options.cacheTime){
options.cacheTime = 5*24*60*60*1000;
}
if (!options.filters){
options.filters = [];
}
this.options = options;
}
/**
* @name FilterFunction
* @function
* @param {Object} stream Stream object
* @param {string} [source] Source
* @param {Object[]} [collected] Already collected streams for result
* @return Either modified Stream Object of undefined. Undefined means that the stream should not be outputted in result.
*/
/**
* It is possible to use Pled in pair with [Express.js]{@link http://expressjs.com/}. Handles HTTP request.
* Query string can have "force=true" (or request.query.force true) query parameter. This allows to force reload data (ignoring cache)
* See `samples` directory for an example.
*/
handleRequest(request, response){
let loader = (request.query && request.query.force) ? this.executeNoCache : this.execute;
loader.call(this)
.then(content =>{
//console.log(`Received content: ${content}`);
//response.status(200);
response.setHeader('Content-type', 'audio/x-mpegurl');
response.setHeader("Content-Disposition", "attachment;filename=playlist.m3u");
response.charset = 'UTF-8';
response.write(content);
response.end();
})
.catch(error => {
response.status(500);
response.send("Failed to generate the playlist.m3u. Error: "+error.message);
});
}
/**
* Processes play list sources and generates resulting playlist as string
* If up to date cache content is available then cache will be returned without reloading
* @returns {Promise<string>} Promise with a string value - content of m3u
*/
execute(){
if (!this.options.cachePath){
return this.executeNoCache();
}
let obj = this;
return this.loadCache()
.then(cache => {
if (cache.status == Pled.CACHE_STATUS_OK){
return cache.content;
}
return obj.executeNoCache();
});
}
/**
* Creates content from sources omitting cache
* @returns {Promise<string>} Promise with a string value - content of m3u
*/
executeNoCache(){
let obj = this;
return this._handleSourceTail(0, {tracks: []})
.then(result => {
let content = m3u.format(result);
if (obj.options.cachePath){
return obj.saveCache(content);
}
return content;
});
}
/**
* @typedef CacheStatus
* @type Object
* @property {Symbol} status Cache status: CACHE_STATUS_OK, CACHE_STATUS_MISSING, CACHE_STATUS_OUTDATED
* @property {string} [content] Optional content. Specified only if cache status is CACHE_STATUS_OK
*/
/**
* Loads playlist from cache file.
* @returns {Promise<CacheStatus>}
*/
loadCache(){
let options = this.options;
if (!options.cachePath){
return Promise.reject(new Error("Path to cache file not specified"));
}
return new Promise(function (resolve) {
fs.stat(options.cachePath, (err, stat) => {
if (err){
resolve({status : Pled.CACHE_STATUS_MISSING});
return;
}
let now = new Date();
let age = now - stat.mtime;
//console.log(`Cache time: ${options.cacheTime}, now: ${now}, file time: ${stat.mtime}, age: ${age}`);
if (age > options.cacheTime){
resolve({status : Pled.CACHE_STATUS_OUTDATED});
return;
}
resolve(Pled.loadLocal(options.cachePath)
.then(content => {
return {status: Pled.CACHE_STATUS_OK, content: content};
}));
});
});
}
saveCache(content){
let obj = this;
return new Promise(
function(resolve, reject){
fs.writeFile(obj.options.cachePath, content, err => {
if (err) {
reject(err);
}
else {
resolve(content);
}
});
});
}
_handleSourceTail(sourceIdx, result){
if (sourceIdx >= this.options.sources.length){
return result;
}
let source = this.options.sources[sourceIdx];
let obj = this;
return this._handleSource(source, result)
.then(function(){
return obj._handleSourceTail(sourceIdx+1, result);
});
}
_handleSource(source, result){
let filters = this.options.filters;
return Pled.loadSource(source)
.then(content => {
let parsed = m3u.parse(content);
var filter;
parsed.tracks.forEach(track => {
for(var idx in filters){
filter = filters[idx];
track = filter(track, source, result);
if (!track) break;
}
if (track){
result.tracks.push(track);
}
});
});
}
static loadLocal(path){
return new Promise(
function(resolve, reject) {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
reject(err);
}
else {
resolve(data);
}
});
});
}
static loadRemote(url){
return new Promise(
function(resolve, reject){
var req = http.get(urlParse(url), function (res) {
if (res.statusCode !== 200) {
reject(new Error("Http returned status: "+req.statusCode));
return;
}
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
resolve(data);
});
});
req.on('error', function (e) {
reject(e);
});
req.end();
}
);
}
static loadSource(url){
if (url.startsWith('http://')||url.startsWith('http://')){
return Pled.loadRemote(url);
}
return Pled.loadLocal(url);
}
}
Pled.CACHE_STATUS_OK = Symbol();
Pled.CACHE_STATUS_MISSING = Symbol();
Pled.CACHE_STATUS_OUTDATED = Symbol();
Pled.filters = require('./filters');
module.exports = Pled;