~rfm/import-album

ref: c2007957c3de3d6c4b5a95aaf9e3b1c07c8cd86b import-album/import-albums -rwxr-xr-x 8.7 KiB
c2007957 — Richard Mavis Update repository link in readme. 1 year, 5 months ago
                                                                                
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/env ruby

require 'fileutils'
require 'securerandom'

#
# Dependencies:
# cut
# file
# unzip
#

# default_library :: string
def default_library
  "#{Dir.home()}/Music"
end

# run :: [string] -> nil
def run(args)
  library = nil
  mode = {
    :confirm => nil,
    :copy => nil,
  }

  i = 0
  while (i < args.length)
    arg = args[i]
    # puts "Starting with '#{arg}'"
    if (arg[0] == '-')
      if ((arg == '-c') || (arg == '--copy'))
        mode[:copy] = true
      elsif ((arg == '-h') || (arg == '--help'))
        puts help_message
      elsif ((arg == '-i') || (arg == '--interactive'))
        mode[:confirm] = true
      elsif ((arg == '-l') || (arg == '--library'))
        library = File.absolute_path(args[(i + 1)])
        i += 1
      else
        STDERR.puts "Unrecognized option \"#{arg}\"."
      end
    elsif (File.file?(arg))
      handle_file!((library || default_library), arg, mode)
    else
      STDERR.puts "Argument \"#{arg}\" is neither an option nor a file."
    end
    i+= 1
  end

  if (!STDIN.tty?)
    begin
      while (line = STDIN.readline)
        handle_file!((library || default_library), line.strip, mode)
      end
    rescue => e
    end
  end

  return nil
end

# help_message :: string
def help_message
  <<~HELP
    Use import-album to move or copy files into your media library.

    import-album knows how to handle plain files or zip files of
    plain files. Files will be copied into the library directory
    according to the names present in the source file.

    For plain files, it expects the source to be in the format:

        {artist name} - {title}.{extension}

    And the destination file will be named:

        {library}/{artist name}/{title}/01 {title}.{extension}

    Zip files will be unzipped into a temporary directory in the
    same directory as the zip file. The temporary directory will be
    removed after the operation. The unzipped file names should be
    in the format:

        {artist name} - {album name} - {title}.{extension}

    And the destination file will be named:

        {library}/{artist name}/{album name}/{title}.{extension}

    The zipped file names will presumably contain numbers, if
    appropriate.

    Files in the temporary directory with a name that doesn't conform
    to the expected format (like "cover.jpg") will retain that name
    in the destination directory.

    The general form of the command is:

        import-album [-c] [-i] [-l DIR] FILE [FILE...]

    The options are:

        -c, --copy
            Copy files. The default behavior is to move them. For
            zip files, the unzip directory will still be removed.

        -i, --interactive
            Confirm values and actions before each copy/move.

        -l, --library
            Use the named DIR as the library directory. The
            default is ~/Music.
  HELP
end

# handle_file! :: (string, string, bool) -> nil
def handle_file!(library, filename, mode)
  path = File.absolute_path(filename)
  type = file_type(path)
  if (type == :album)
    # puts "Is an album"
    handle_album!(library, path, mode)
  elsif (type == :single)
    # puts "Is a single"
    handle_single!(library, path, mode)
  else
    STDERR.puts "File \"#{filename}\" is neither an audio nor a zip file."
  end
  return nil
end

# file_type :: string -> symbol?
def file_type(path)
  type = `file -ib "#{path}" | cut -d ";" -f 1`.strip
  if (type == "audio/mpeg")
    return :single
  elsif (type == "application/zip")
    return :album
  end
  return nil
end

# handle_single! :: (string, string, bool) -> nil
def handle_single!(library, filename, mode)
  begin
    file_parts = single_path_parts(filename)
    if (file_parts.nil?)
      raise "Filename \"#{filename}\" is not in the expected format."
    end

    if (mode[:confirm])
      library = prompt_for_value("Library", library)
      use_parts = { }
      {
        :primary => "Artist",
        :secondary => "Album",
        :file => "File",
      }.each do |key,prompt|
        use_parts[key] = prompt_for_value(prompt, file_parts[key])
      end
    else
      use_parts = file_parts
    end

    move_to!(library, filename, use_parts, mode)
  rescue => e
    STDERR.puts e.message
  end
  return nil
end

# single_path_parts :: string -> parts?
# parts = see `move_to!`
def single_path_parts(filename)
  extension = File.extname(filename)
  base = File.basename(filename, extension)
  index = base.index(' - ')
  if (index.nil?)
    return nil
  end
  artist = base[0...index]
  album = base[(index + 3)..(base.length)]
  return {
    :primary => artist,
    :secondary => album,
    :file => '01 ' + album + extension,
  }
end

# handle_album! :: (string, string, bool) -> nil
def handle_album!(library, filename, mode)
  path = File.absolute_path(filename)
  dir = File.dirname(path)
  tmp_dir = dir + '/' + SecureRandom.uuid
  if (File.exists?(tmp_dir))
    raise "Could not create temp directory \"#{tmp_dir}\": already exists"
  end
  begin
    Dir.mkdir(tmp_dir)
  rescue
    raise "Could not create temp directory \"#{tmp_dir}\""
  end

  `unzip -d "#{tmp_dir}" "#{path}"`
  if (Dir.empty?(tmp_dir))
    raise "Temp directory empty: did \"#{path}\" unzip properly?"
  end

  file_parts = album_path_parts(path)
  if (file_parts.nil?)
    raise "Filename \"#{filename}\" is not in the expected format."
  end
  if (mode[:confirm])
    library = prompt_for_value("Library", library)
    use_parts = { }
    {
      :primary => "Artist",
      :secondary => "Album",
    }.each do |key,prompt|
      use_parts[key] = prompt_for_value(prompt, file_parts[key])
    end
  else
    use_parts = file_parts
  end

  pattern = Regexp.new("^#{file_parts[:primary]} - #{file_parts[:secondary]} - ")
  Dir.each_child(tmp_dir) do |name|
    if (name.match?(pattern))
      use_parts[:file] = name.sub(pattern, "")
    else
      use_parts[:file] = name
    end
    if (mode[:confirm])
      use_parts[:file] = prompt_for_value("File", use_parts[:file])
    end
    move_to!(library, tmp_dir + '/' + name, use_parts, mode)
  end

  `rm -rf #{tmp_dir}`
  return nil
end

# album_path_parts :: string -> parts?
# parts = see `ensure_directories!`
def album_path_parts(filename)
  base = File.basename(filename, '.*')
  index = base.index(' - ')
  if (index.nil?)
    return nil
  end
  return {
    :primary => base[0...index],
    :secondary => base[(index + 3)..(base.length)],
  }
end

# move_to! :: (string, string, parts, bool) -> nil
# parts = {
#   :primary => string
#   :secondary => string
#   :file => string
# }
def move_to!(library, old_path, parts, mode)
  new_path = library + '/' + parts[:primary] + '/' + parts[:secondary] + '/' + parts[:file]

  begin
    ensure_directories!(library, parts)
  rescue => e
    STDERR.puts e.message
  end

  if (mode[:copy])
    begin
      if ((mode[:confirm]) &&
          (!prompt_for_confirmation("Copy \"#{old_path}\" to \"#{new_path}\"?")))
        return nil
      end
      FileUtils.copy(old_path, new_path)
    rescue => e
      raise "Could not copy \"#{old_path}\" to \"#{new_path}\": #{e.message}"
    end
  else
    begin
      if ((mode[:confirm]) &&
          (!prompt_for_confirmation("Move \"#{old_path}\" to \"#{new_path}\"?")))
        return nil
      end
      File.rename(old_path, new_path)
    rescue => e
      raise "Could not move \"#{old_path}\" to \"#{new_path}\": #{e.message}"
    end
  end

  return nil
end

# ensure_directories! :: (string, parts)
# parts = {
#   :primary => string
#   :secondary => string
# }
def ensure_directories!(library, parts)
  # puts "Checking library \"#{library}\""
  if (!((File.directory?(library)) &&
        (File.writable?(library))))
    raise library + ' is not a writable directory.'
  end

  [
    library + '/' + parts[:primary],
    library + '/' + parts[:primary] + '/' + parts[:secondary]
  ].each do |dir|
    # puts "Checking directory \"#{dir}\""
    if (!File.exists?(dir))
      begin
        Dir.mkdir(dir)
      rescue
        raise "Could not create directory \"#{dir}\""
      end
    end
  end
end

# prompt_for_value :: (string, string) -> string
def prompt_for_value(prompt, value)
  print "#{prompt}? [#{value}] "
  input = STDIN.gets.strip
  if (input == "")
    return value
  end
  return input
end

# prompt_for_confirmation :: (string, [(string) yes, (string) no]?) -> bool
def prompt_for_confirmation(prompt, vals = ['y', 'n'])
  correct = false
  val_string = vals[0].upcase + '/' + vals[1]
  while !correct do
    print "#{prompt} [#{val_string}] "
    input = STDIN.gets.strip.downcase
    if ((input == "") || (input == vals[0].downcase))
      correct = true
    elsif (input == vals[1].downcase)
      return false
    else
      STDERR.puts "Please enter \"#{vals[0]}\", \"#{vals[1]}\", or hit Enter to accept the default (#{vals[0].upcase})."
    end
  end
  return true
end

run(ARGV)