module IRS::Utils

Public Class Methods

banner() click to toggle source
blank(str, d=true) click to toggle source
# File lib/utils.rb, line 232
def blank(str, d=true)
  str = str.tr('^A-Za-z0-9\ ', '')
  str.downcase! if d
  return str
end
blank_include?(this, includes_this) click to toggle source
# File lib/utils.rb, line 238
def blank_include?(this, includes_this)
  this = this.tr('^A-Za-z0-9\ ', '').downcase
  includes_this = self.blank(includes_this)
  if this.include?(includes_this)
    return true
  end
  return false
end
capitalize_all(string) click to toggle source
# File lib/utils.rb, line 273
def capitalize_all(string)
  (string.split(" ").map{|word| word.capitalize}).join(" ")
end
check_garbage_phrases(phrases, string, song) click to toggle source
# File lib/utils.rb, line 262
def check_garbage_phrases(phrases, string, song)
  phrases.each do |phrase|
    if self.blank(string).include?(phrase)
      if !self.blank(song).include?(phrase)
        return true
      end
    end
  end
  return false
end
console() click to toggle source
# File lib/utils.rb, line 95
      def console
        self.banner
        puts
        if ENV["SPOTIFY_AUTHENTICATED?"] == "TRUE"
          unicode = ["✔".green.bold, "currently", ""]
        else
          unicode = ["✘".red.bold, "not".red.bold, "This means\
 that you #{"cannot".red.bold} download playlists, To authenticate, \
you'll want to create an app here: https://developer.spotify.com/my-applications/\
, and then export the Client ID and Client Secret into the environment variables \
SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET, respectively."]
        end
        self.flush_puts(
"[#{unicode[0]}] You are #{unicode[1]} authenticated with spotify. #{unicode[2]}".reset_colors)
        puts
        self.flush_puts("Choose option from menu:")
        self.flush_puts("\t[#{"1".red.bold}] Download Single Song".gray.bold)
        self.flush_puts("\t[#{"2".red.bold}] Download Album".gray.bold)
        self.flush_puts("\t[#{"3".red.bold}] Download Playlist".gray.bold)
        
        print ("irs#{">".gray} ".blue.bold)
        print ("\e[0m")
        gets.chomp
      end
delete_all(locations) click to toggle source
# File lib/utils.rb, line 292
def delete_all(locations)
  if locations.is_a?(Array)
    locations.each do |loc|
      self.delete_whole_path(loc)
    end
  else
    self.delete_whole_path(locations)
  end
end
delete_whole_path(path) click to toggle source
# File lib/utils.rb, line 283
def delete_whole_path(path)
  paths = path.gsub("./", "").split("/")
  if File.directory?(paths[0])
    FileUtils.remove_dir(paths[0]) unless paths[0] == "." # Bad experiences with this...
  elsif File.file?(paths[0])
    File.delete(paths[0])
  end
end
finish_download_log_line(line, location) click to toggle source
# File lib/utils.rb, line 220
def finish_download_log_line(line, location)
  lines = File.readlines('.irs-download-log')
  lines.each do |l|
    if line == l
      new_line = l.split(" &@# ")
      new_line[-1] = "\"#{location}\"\n"
      lines[lines.index(l)] = new_line
    end
  end
  File.open('file', 'w') { |f| f.write(lines.join) }
end
flush_puts(msg, time=0.03) click to toggle source
# File lib/utils.rb, line 120
def flush_puts(msg, time=0.03)
  # For slow *burrrp* scroll text, Morty. They-They just love it, Morty.
  # When they see this text. Just slowwwly extending across the page. Mmm, mmm.
  # You just give the time for how *buurp* slow you wa-want it, Morty.
  # It works with colors and escape characters too, Morty.
  # Your grandpas a genius *burrrp* Morty
  msg = msg.split(/(\e\[\d+m)/)
  msg.map!{ |e|
    if !e.include?("\e")
      e.split("")
    else
      e
    end
  }.flatten!
  msg.each do |char|
    if ![" ", "\n"].include?(char) or char =~ /\e\[\d+m/
      sleep time
    end
    print char
  end
  puts
end
format_download_log_data(data) click to toggle source
# File lib/utils.rb, line 209
      def format_download_log_data(data)
        lines = []
        data.each do |t|
          lines.push(
"#{t[:song]} &@# #{t[:artist]} &@# #{t[:album].id} &@# #{t[:genre]} &@# #{t[:track_number]} \
&@# #{t[:disc_number]} &@# #{t[:compilation]} &@# #{t[:prefix]} &@# not_finished"
          )
        end
        return lines.join("\n")
      end
individual_word_match(to_match, match) click to toggle source
# File lib/utils.rb, line 173
def individual_word_match(to_match, match)
  # Returns a percentage in the form of `10% => .1`, `85% => .85`
  to_match = to_match.split(" ").map{ |word| self.blank(word) }
  match = match.split(" ").map{ |word| self.blank(word) }

  matched = []
  to_match.each do |to_match|
    match.each do |word|
      if to_match == word
        matched.push(word)
      end
    end
  end
  return matched.uniq.size.to_f / to_match.size.to_f
end
nl(text, sleep_n=0) click to toggle source
# File lib/utils.rb, line 277
def nl(text, sleep_n=0)
  system "clear"
  puts text
  sleep sleep_n
end
organize_it(locations) click to toggle source
# File lib/utils.rb, line 143
def organize_it(locations)
  new_locs = []
  locations.each do |loc|
    metadata = Id3Tags.read_tags_from(loc)

    new_loc = ["."]

    if metadata[:artist]
      artist_folder = self.blank(metadata[:artist], d=false)
      new_loc.push(artist_folder)

      if metadata[:album]
        album_folder = self.blank(metadata[:album], d=false)
        new_loc.push(album_folder)
      end
    end

    FileUtils::mkdir_p(new_loc.join("/")) unless File.directory?(new_loc.join("/"))

    file_name = File.basename(loc.gsub("\\","/"))
    new_loc.push(file_name)
    new_loc = new_loc.join("/")

    File.rename(loc, new_loc)
    new_locs.push(new_loc)
  end

  return new_locs
end
read_download_log() click to toggle source
# File lib/utils.rb, line 189
def read_download_log()
  data = []
  File.open(".irs-download-log", "r") do |line|
    line.split!(" &@# ")
    if line[-1] == "not_finished"
      data.push({
        song: line[0],
        artist: line[1],
        album: RSpotify::Album.fing(line[2]),
        genre: line[3],
        track_number: line[4],
        disc_number: line[5],
        compilation: (line[6] == "true"),
        prefix: line[7],
      })
    end
  end
  return data
end
unzip_file(file) click to toggle source
# File lib/utils.rb, line 247
def unzip_file(file)
  locations = []
  Zip::File.open(file) do |zip_file|
    zip_file.each do |f|

      FileUtils.mkdir_p(File.dirname(f.name))

      if !File.exist?(f.name)
        zip_file.extract(f, f.name)
        locations.push(f.name)
      end
    end
  end
end
zip_it(locations, zipname="") click to toggle source
# File lib/utils.rb, line 303
def zip_it(locations, zipname="")
  if locations.is_a?(Array)
    folder = "."
    zipfile_name = "./#{zipname.tr('^A-Za-z0-9\ ', '')}.zip"

    Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      locations.each do |filename|
        zipfile.add(filename, "#{folder}/#{filename}")
      end
      #zipfile.get_output_stream("txt") { |os| os.write "myFile contains just this" }
    end
  else
    parent_dir = locations
    path = File.dirname(File.dirname(locations))
    zipfile_name = path + '.zip'
    FileUtils.rm(zipfile_name, force: true)
    Zip::File.open(zipfile_name, 'w') do |zipfile|
      Dir["#{path}/**/**"].reject{ |f| f == zipfile }.each do |file|
        zipfile.add(file.sub(parent_dir + "/" + path + '/', ''), file)
      end
    end
  end
  return zipfile_name
end
❨╯°□°❩╯︵┻━┻() click to toggle source
# File lib/utils.rb, line 328
def ❨╯°□°❩╯︵┻━┻ # Autogenerated - do not remove: critical table flip api!
  ut = self

  ut.nl("(._. ) ┬─┬", 3)
  ut.nl("( ._.) ┬─┬", 3)
  ut.nl("(._. ) ┬─┬", 2)
  ut.nl("(•-• ) ┬─┬", 3)
  space = ""
  (`tput cols`.to_i - 12).times do
    ut.nl("(╯°Д°)╯  " + space + "┻━┻", 0.005)
    space += " "
  end
  ut.nl("(╯°-°)╯" + space + "┻ ━ ┻")
  return "Calm down, bro."
end