1 | #!/usr/bin/env node
|
2 | var programm = require('commander');
|
3 | var request = require('request');
|
4 | var fs = require('fs');
|
5 | var async = require('async');
|
6 | var util = require('util');
|
7 | var ProgressBar = require('progress');
|
8 | var google = require('./lib/providers/google');
|
9 | var iTunes = require('./lib/itunes');
|
10 |
|
11 | var DOWNLOAD_DIR = process.env.HOME + '/.gmsync-cache';
|
12 |
|
13 | programm
|
14 | .version(require('./package').version)
|
15 | .usage('[options]')
|
16 | .option('-p, --playlist [num]', 'Show playlist')
|
17 | .option('-d, --download', 'Download songs and sync with iTunes')
|
18 | .parse(process.argv);
|
19 |
|
20 | function downloadSongs(playlist, cb) {
|
21 | try {
|
22 | fs.mkdirSync(DOWNLOAD_DIR);
|
23 | } catch (e) {};
|
24 | var playlistName = 'gm-' + playlist.name;
|
25 | var bar = new ProgressBar('Downloading [:bar] :percent :etas', {
|
26 | complete: '#',
|
27 | total: playlist.songs.length,
|
28 | width: 50
|
29 | });
|
30 | iTunes.createPlaylist(playlistName);
|
31 | bar.tick(0);
|
32 |
|
33 | async.each(
|
34 | playlist.songs,
|
35 | function (song, cb) {
|
36 | var filename = util.format('%s/%s — %s.mp3', DOWNLOAD_DIR, song.artist, song.title);
|
37 | fs.readFile(filename, function (err) {
|
38 | if (!err) {
|
39 | iTunes.addFilenameToPlaylist(playlistName, filename, cb);
|
40 | return bar.tick();
|
41 | }
|
42 | google.getStreamUrl(song.storeId, function (err, url) {
|
43 | if (err) {
|
44 | return cb(err);
|
45 | }
|
46 | request(url)
|
47 | .pipe(fs.createWriteStream(filename))
|
48 | .on('error', console.error)
|
49 | .on('close', function () {
|
50 | bar.tick();
|
51 | iTunes.addFilenameToPlaylist(playlistName, filename, cb);
|
52 | });
|
53 | });
|
54 | });
|
55 | },
|
56 | cb
|
57 | );
|
58 | }
|
59 |
|
60 | function printSongs(playlist) {
|
61 | playlist.songs.forEach(function (item, index) {
|
62 | console.log('%s) %s — %s', index, item.artist, item.title);
|
63 | });
|
64 | }
|
65 |
|
66 | if (programm.playlist) {
|
67 | google.getPlayListWithSongs(programm.playlist, function (err, playlist) {
|
68 | if (err) {
|
69 | return console.error(err);
|
70 | }
|
71 | if (programm.download) {
|
72 | downloadSongs(playlist);
|
73 | } else {
|
74 | printSongs(playlist);
|
75 | }
|
76 | });
|
77 | } else {
|
78 | google.getPlayLists(function (err, playlists) {
|
79 | if (err) {
|
80 | return console.error(err);
|
81 | }
|
82 | console.log('Your playlists:');
|
83 | playlists.forEach(function (item, index) {
|
84 | console.log('%s) %s', index, item.name);
|
85 | });
|
86 | });
|
87 | }
|
88 |
|