-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·77 lines (64 loc) · 2.36 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
#!/usr/bin/env node
const EventEmitter = require("events");
const camelcaseKeys = require("camelcase-keys");
const electron = require("electron");
const proc = require("child_process");
const path = require("path");
const { SEPARATOR } = require("./tokens");
const EVENT_NAME_FROM_APP = {
spotify: "com.spotify.client.PlaybackStateChanged",
itunes: "com.apple.iTunes.playerInfo",
};
const EVENT_NAMES = [EVENT_NAME_FROM_APP.spotify, EVENT_NAME_FROM_APP.itunes];
const getAppFromEventName = (eventName) =>
Object.keys(EVENT_NAME_FROM_APP).find(
(key) => EVENT_NAME_FROM_APP[key] === eventName
);
const parseEvent = (rawEvent) => {
const [eventName, serializedUserInfo] = rawEvent.split(SEPARATOR);
const userInfo = JSON.parse(serializedUserInfo);
return { eventName, userInfo };
};
class NowPlaying extends EventEmitter {
constructor() {
super();
this.setupNotifications();
}
setupNotifications() {
const child = proc.spawn(electron, [
path.join(__dirname, "electronNotificationListener.js"),
EVENT_NAMES.join(SEPARATOR),
]);
child.stdout.on("data", (rawData) => {
try {
const data = rawData.toString();
const { eventName, userInfo } = parseEvent(data);
const camelCasedUserInfo = camelcaseKeys(userInfo);
const playerState =
camelCasedUserInfo.playerState.toLowerCase();
camelCasedUserInfo.eventName = eventName;
camelCasedUserInfo.source = getAppFromEventName(eventName);
if (
eventName === EVENT_NAME_FROM_APP.itunes &&
camelCasedUserInfo.storeUrl ===
"itmss://itunes.com/link?n=Connecting%E2%80%A6"
) {
this.emit("connecting", camelCasedUserInfo);
} else {
this.emit(playerState, camelCasedUserInfo);
}
} catch (err) {
this.emit("error", err);
}
});
child.stdout.on("error", (err) => {
this.emit("error", err);
});
["exit", "SIGINT", "SIGTERM"].forEach((eventName) => {
process.on(eventName, () => {
child.kill();
});
});
}
}
module.exports = new NowPlaying();