-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathid3-reader.js
109 lines (102 loc) · 2.72 KB
/
id3-reader.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
var fs = require('fs');
var sys = require('sys');
Id3Reader = function(filename) {
this.filename = filename;
this.flags = 'r';
this.offset = 0;
this.data = {};
};
//Set up the collection
Id3Reader.prototype.getFile = function(callback) {
var cur = this;
fs.open(this.filename, this.flags, function(error, data) {
if (error) callback(error);
else callback(null, data);
});
};
Id3Reader.prototype.isId3v2 = function(callback) {
var cur = this;
this.getFile(function(error, data) {
if (error) {
global.setTimeout(cur.isId3v2(callback), 1000);
}
else {
var buffer = new Buffer(3);
fs.read(data, buffer, 0, 3, 0, function(err, bytesRead) {
if(buffer.toString() == "ID3") {
callback(null, true, data);
} else {
fs.close(data, function() {
callback(null, false);
});
}
});
}
});
};
Id3Reader.prototype.readData = function(callback) {
//We're referencing this in the callbacks - make sure it stays correct
var cur = this;
cur.isId3v2(function(error, isId3, data) {
if (isId3) {
var read = new Buffer(10);
fs.read(data, read, 0, 10, 0, function(err, bytesRead) {
var size = read.slice(6,10);
cur.offset = 10;
cur.length = cur.intFromBytes(size, 7);
cur.readFrame(data, callback);
});
} else {
callback(false);
}
});
};
Id3Reader.prototype.readFrame = function(data, callback) {
if(this.offset < this.length) {
var buff = new Buffer(10);
var cur = this;
fs.read(data, buff, 0, 10, cur.offset, function(err, bytesRead) {
var frame = buff.slice(0,4);
var size = cur.intFromBytes(buff.slice(4,8));
cur.offset += 10;
if (cur.intFromBytes(frame) > 0) {
if (size > 0) {
var contents = new Buffer(size);
fs.read(data, contents, 0, size, cur.offset, function(err, bytesRead) {
cur.offset += size;
if (frame.toString()[0] == "T") {
//We do not want the encoding byte for 'T' frames
contents = contents.slice(1, contents.length);
if(contents[contents.length-1] == 0) {
//Get rid of shitty tags with random extra blank bytes
contents = contents.slice(0, contents.length-1);
}
}
cur.data[frame.toString()] = contents.toString();
cur.readFrame(data, callback);
});
} else {
cur.readFrame(data, callback);
}
} else {
fs.close(data, function() {
callback(cur.data);
});
}
});
} else {
fs.close(data, function() {
callback(this.data);
});
}
};
Id3Reader.prototype.intFromBytes = function(buffer, sigBits) {
sigBits = sigBits || 8;
var total = 0;
for(var i = 0; i < buffer.length; i++) {
total += buffer[i] << (sigBits * (buffer.length - (i+1)));
}
return total;
};
//export so we can import it like a module
exports.Id3Reader = Id3Reader;