~rfm/import-album

954734a5c4ca5a66ffe6084825aacca8ebae61bd — Richard Mavis 1 year, 5 months ago
In the beginning was init.
2 files changed, 403 insertions(+), 0 deletions(-)

A README.md
A import-albums
A  => README.md +50 -0
@@ 1,50 @@
# import-album

`import-album`---move or copy files into your media library.


## Synopsis

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

    -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.


## Description

`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.

A  => import-albums +353 -0
@@ 1,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)