Module: Exportify::CLI

Defined in:
lib/exportify/cli.rb

Constant Summary collapse

DEFAULT_OUTPUT_DIR =
'musics'

Class Method Summary collapse

Class Method Details

.open_ttyObject



158
159
160
# File 'lib/exportify/cli.rb', line 158

def open_tty
  IO.console || $stdin
end

.read_secret(tty) ⇒ Object



162
163
164
165
166
167
168
# File 'lib/exportify/cli.rb', line 162

def read_secret(tty)
  if tty.respond_to?(:noecho)
    tty.noecho(&:gets).chomp
  else
    tty.gets.chomp
  end
end

.run(argv) ⇒ Object



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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/exportify/cli.rb', line 17

def run(argv)
  return run_init(argv[1]) if argv[0] == 'init'

  retag = false
  sync  = false

  parser = OptionParser.new do |opts|
    opts.banner = "Usage:\n  " \
                  "exportify init\n  " \
                  'exportify <spotify_playlist_url> [--retag] [--sync]'
    opts.on('--retag', 'Regravar tags ID3 nos arquivos existentes') { retag = true }
    opts.on('--sync',  'Remover arquivos locais que não estão mais na playlist') { sync = true }
  end

  parser.parse!(argv)
  playlist_url = argv[0]&.split('?', 2)&.first

  abort parser.banner unless playlist_url

  abort 'Credenciais não configuradas. Execute: exportify init' unless Auth.client_id && Auth.client_secret

  playlist_id = playlist_url.match(%r{playlist/([A-Za-z0-9]+)})&.captures&.first
  abort 'Invalid playlist URL' unless playlist_id

  puts 'Authenticating with Spotify...'
  token = Auth.access_token

  puts 'Fetching playlist...'
  name       = Spotify.playlist_name(playlist_id, token)
  tracks     = Spotify.playlist_tracks(playlist_id, token)
  tracks     = Spotify.enrich_with_genres(tracks, token)
  output_dir = File.expand_path(File.join(Config.output_dir, Downloader.sanitize(name)))

  FileUtils.mkdir_p(output_dir)

  puts "#{tracks.size} tracks found"
  puts "Output: #{output_dir}\n\n"

  ok = skip = failed = 0

  tracks.each_with_index do |track, i|
    artist   = Downloader.sanitize(track[:artist])
    name     = Downloader.sanitize(track[:name])
    filename = "#{artist} - #{name}.mp3"
    filepath = File.join(output_dir, filename)

    print "[#{i + 1}/#{tracks.size}] #{filename} "

    if retag
      if File.exist?(filepath)
        Tagger.tag(filepath, track)
        puts '(retagged)'
        ok += 1
      else
        puts '(not found, skipping)'
        skip += 1
      end
      next
    end

    if File.exist?(filepath)
      puts '(already exists, skipping)'
      skip += 1
      next
    end

    puts '(downloading...)'
    success = Downloader.download(track, output_dir)

    if success && File.exist?(filepath)
      Tagger.tag(filepath, track)
      ok += 1
    else
      failed += 1
    end
  end

  removed = 0

  if sync
    expected = tracks.to_set do |track|
      "#{Downloader.sanitize(track[:artist])} - #{Downloader.sanitize(track[:name])}.mp3"
    end

    Dir.glob(File.join(output_dir, '*.mp3')).each do |file|
      next if expected.include?(File.basename(file))

      puts "Removing #{File.basename(file)}"
      File.delete(file)
      removed += 1
    end
  end

  if retag
    puts "\nDone: #{ok} retagged, #{skip} not found."
  else
    removed_msg = sync ? ", #{removed} removed" : ''
    puts "\nDone: #{ok} downloaded, #{skip} skipped, #{failed} failed#{removed_msg}."
  end
end

.run_init(dir = nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/exportify/cli.rb', line 118

def run_init(dir = nil)
  require 'io/console'

  cfg = Config.load
  tty = open_tty

  puts '=== Exportify Setup ==='
  puts

  default_dir = dir || cfg.fetch('output_dir', DEFAULT_OUTPUT_DIR)
  print "Diretório principal [#{default_dir}]: "
  dir_input = tty.gets.chomp
  new_dir   = dir_input.empty? ? default_dir : dir_input

  current_id = cfg['spotify_client_id'] || ''
  id_hint    = current_id.empty? ? '' : " [#{current_id[0..7]}...]"
  print "Spotify Client ID#{id_hint}: "
  id_input = tty.gets.chomp
  new_id   = id_input.empty? ? current_id : id_input

  secret_hint = cfg['spotify_client_secret'] ? ' [configurado]' : ''
  print "Spotify Client Secret#{secret_hint}: "
  new_secret = read_secret(tty)
  puts
  new_secret = cfg['spotify_client_secret'] if new_secret.empty?

  abort 'Client ID não pode ser vazio.' if new_id.empty?
  abort 'Client Secret não pode ser vazio.' if new_secret.to_s.empty?

  Config.save(
    'output_dir' => File.expand_path(new_dir),
    'spotify_client_id' => new_id,
    'spotify_client_secret' => new_secret
  )

  puts "\nConfiguração salva em #{Config::CONFIG_PATH}"
ensure
  tty&.close
end