-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
114 lines (85 loc) · 2.33 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
/**
* Created by solvek on 26.01.16.
*/
var EXTM3U = '#EXTM3U';
var EXTINF = '#EXTINF:';
var REGEX_PARAMS = /\s*("([^"]+)"|([^=]+))=("([^"]+)"|(\S+))/g;
var REGEX_DURATION = /\s*(-?\d+)/g;
//var util = require('util');
function parseParams(data){
var result = {};
var m, key, value;
while ((m = REGEX_PARAMS.exec(data)) !== null) {
if (m.index === REGEX_PARAMS.lastIndex) {
REGEX_PARAMS.lastIndex++;
}
//console.log(util.inspect(m));
key = m[2] ? m[2] : m[3];
value = m[5] ? m[5] : m[6];
result[key] = value;
}
//console.log(util.inspect(result));
return result;
}
function formatParams(params){
var result = '';
for(var key in params){
result += ' ' + key + '="' + params[key]+'"';
}
return result;
}
function parse(content){
var result = {
tracks: []
};
//console.log(content);
var lines = content.split('\n');
var line, current = {}, pos, duration;
for(var i=0;i<lines.length;i++){
line = lines[i].trim();
if (line == ''){
continue;
}
if (line.indexOf(EXTM3U) == 0){
result.header = parseParams(line.substr(EXTM3U.length));
continue;
}
if (line.indexOf(EXTINF) == 0){
pos = line.lastIndexOf(',');
current.title = line.substr(pos+1).trim();
line = line.substring(EXTINF.length, pos).trim();
duration = line.match(REGEX_DURATION);
current.length = parseInt(duration[0]);
current.params = parseParams(line.substr(duration[0].length));
continue;
}
if (line.indexOf("#") == 0){
continue;
}
current.file = line;
//console.log(util.inspect(current));
result.tracks.push(current);
current = {};
}
return result;
}
function format(m3u){
var result = EXTM3U;
if (m3u.header){
result += formatParams(m3u.header);
}
result+= '\n';
m3u.tracks.forEach(function(track){
result += EXTINF
+track.length
+formatParams(track.params)
+","
+track.title
+'\n'
+track.file
+'\n';
});
return result;
}
module.exports.parse = parse;
module.exports.format = format;