-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
65 lines (50 loc) · 2.39 KB
/
server.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
http = require('http')
request = require('request')
fs = require('fs')
path = require('path')
express = require("express");
app = express();
app.get('/', function (req, res) {
res.send('Copy the 8tracks playlist url and paste it in your browser as http://localhost:9000/d/:user/:playlist')
})
app.get('/d/:user/:playlist', function (req, res) {
var playlistName = req.params.playlist
var playlistUrl = 'http://8tracks.com/' + req.params.user + '/' + playlistName
res.write("Downloading playlist: " + playlistUrl + "\n\n")
request(playlistUrl, function (error, response, body) {
var playlistId = body.match(/mixes\/([0-9]+)\//)[1]
console.log("Playlist id: " + playlistId + "\n")
request('http://8tracks.com/sets/new?format=jsonh', function (error, response, body) {
var token = JSON.parse(body)["play_token"]
console.log("token: " + token + "\n")
request('http://8tracks.com/sets/' + token + '/play?mix_id=' + playlistId + '&format=jsonh', function (error, response, body) {
fs.mkdirSync(downloadPath(playlistName), 0777)
downloadTrack(res, playlistId, token, JSON.parse(body)["set"], playlistName)
})
})
})
})
function toFileName(name) { return name.replace(/[^a-zA-Z \-0-9]+/g, '-') }
function downloadPath(playlistName) { return path.join("playlists", playlistName) }
/**
* Downloads the current song in the playlist, then, if there are more, downloads more
*/
var downloadTrack = function (res, playlistId, token, playSet, playlistName) {
var track = playSet["track"]
var trackName = track["performer"] + " - " + track["name"]
var trackUrl = track["track_file_stream_url"]
res.write("Track: " + trackName + "\n")
console.log("Downloading track: " + trackName + " from " + trackUrl + "\n")
request(trackUrl).pipe(fs.createWriteStream(path.join(downloadPath(playlistName), toFileName(trackName) + ".m4a")))
// get next song
request('http://8tracks.com/sets/' + token + '/next?mix_id=' + playlistId + '&format=jsonh', function (error, response, body) {
var playSet = JSON.parse(body)["set"]
if (playSet["at_end"]) {
res.end("All tracks downloaded, done!\n")
} else {
downloadTrack(res, playlistId, token, playSet, playlistName)
}
})
}
app.listen(9000)
console.log('Express server started in port 9000')