|
1
|
|
|
import { FrameBuilder } from "../FrameBuilder" |
|
2
|
|
|
import { FrameReader } from "../FrameReader" |
|
3
|
|
|
import { Popularimeter } from "../types/TagFrames" |
|
4
|
|
|
|
|
5
|
|
|
export const POPM = { |
|
6
|
|
|
create: (data: Popularimeter): Buffer => { |
|
7
|
|
|
if(data.email == undefined) { |
|
8
|
|
|
throw new RangeError("An email is expected") |
|
9
|
|
|
} |
|
10
|
|
|
|
|
11
|
|
|
// TODO: starting version 0.3 for both rating and counter do not |
|
12
|
|
|
// implicitely trunc and use Number.isInteger() instead to validate |
|
13
|
|
|
|
|
14
|
|
|
const rating = Math.trunc(data.rating) |
|
15
|
|
|
if( isNaN(rating) || rating < 0 || rating > 255) { |
|
16
|
|
|
throw new RangeError( |
|
17
|
|
|
`Provided rating ${data.rating} is not in the valid range 0-255` |
|
18
|
|
|
) |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
// TODO: According to specs, the counter can be omitted |
|
22
|
|
|
// TODO: According to specs if the value is bigger than a 32 bits |
|
23
|
|
|
// a byte can be added and so on... (very unlikely to happen in |
|
24
|
|
|
// real life as it means more than 4GB listenings!) |
|
25
|
|
|
|
|
26
|
|
|
const counter = Math.trunc(data.counter) |
|
27
|
|
|
if (isNaN(counter) || counter < 0) { |
|
28
|
|
|
throw new RangeError( |
|
29
|
|
|
`Provided counter ${data.counter} is not a positive integer` |
|
30
|
|
|
) |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return new FrameBuilder("POPM") |
|
34
|
|
|
.appendTerminatedText(data.email) |
|
35
|
|
|
.appendNumber(rating, {size: 1}) |
|
36
|
|
|
.appendNumber(counter, {size: 4}) |
|
37
|
|
|
.getBufferWithPartialHeader() |
|
38
|
|
|
}, |
|
39
|
|
|
read: (buffer: Buffer): Popularimeter => { |
|
40
|
|
|
const reader = new FrameReader(buffer) |
|
41
|
|
|
return { |
|
42
|
|
|
email: reader.consumeTerminatedText(), |
|
43
|
|
|
rating: reader.consumeNumber({size: 1}), |
|
44
|
|
|
counter: reader.consumeNumber({size: 4}) |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|