-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.js
99 lines (86 loc) · 2.26 KB
/
main.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
var request = require("request"),
commander = require("commander"),
config = require("./config.json"),
currentTrack;
function fetchLastPlayedTrack(username, callback) {
var url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks" +
"&user=" + username +
"&api_key=" + config.lastfm.apiKey +
"&format=json",
data,
track;
request(url, function (error, response, body) {
if (error) {
console.error(error);
} else if (response.statusCode != 200) {
console.error("Unhandled response type:", response.statusCode);
} else {
try {
data = JSON.parse(body);
if (data.recenttracks && data.recenttracks.track) {
track = data.recenttracks.track;
if (Array.isArray(track)) {
track = track[0];
}
if (callback) {
callback(track);
} else {
console.log(track);
}
} else if (data.error && data.message) {
console.error(data.message)
} else {
console.error("Unrecognized data", data);
}
setTimeout(function () {
fetchLastPlayedTrack(username, checkIfTrackIsPlayingAndNew);
}, 10000);
} catch (e) {
console.error(e, body);
}
}
});
}
function checkIfTrackIsPlayingAndNew(track) {
var trackName;
if (track.hasOwnProperty("@attr") &&
track["@attr"].nowplaying &&
"true" == track["@attr"].nowplaying) {
trackName = "\"" + track.name + "\" by " + track.artist["#text"];
if (currentTrack != trackName) {
console.log(trackName);
if (!commander.quiet) {
sendMessageToSlack(trackName);
}
currentTrack = trackName;
}
}
}
function sendMessageToSlack(message) {
var payload = {
text: message,
username: config.slack.username,
icon_emoji: config.slack.icon
},
url = config.slack.url;
request.post({
url: url,
form: { payload: JSON.stringify(payload) }
}, function(error, response, body) {
if (error) {
console.error(error);
} else if (response.statusCode != 200) {
console.error("Unhandled response type:", response.statusCode);
}
});
}
// Parse args
commander
.version("1.0.0")
.usage("[options] <username>")
.option("-q, --quiet", "Don't send message to Slack")
.parse(process.argv);
if (!commander.args.length) {
commander.help();
}
fetchLastPlayedTrack(commander.args[0], checkIfTrackIsPlayingAndNew);