Skip to content

Instantly share code, notes, and snippets.

@watzon
Created May 11, 2019 11:35
Show Gist options
  • Save watzon/1e6026c64665ed01b49079a5554f0fe4 to your computer and use it in GitHub Desktop.
Save watzon/1e6026c64665ed01b49079a5554f0fe4 to your computer and use it in GitHub Desktop.
Little script that searches for media using Crystal
class MediaFinder
alias FileInfo = NamedTuple(name: String, directory: String, size: UInt64)
DEFAULT_MEDIA_TYPES = {
images: ["jpg", "jpeg", "gif", "png", "exif", "tiff", "bmp"],
videos: ["webm", "mkv", "flv", "vob", "ogv", "ogg", "gifv", "mng", "avi", "mts", "m2ts", "mov", "qt", "wmv", "mp4", "m4p", "mpg", "mpeg", "m4v", "3gp", "3g2"],
audios: ["aa", "aac", "aax", "aiff", "flac", "m4a", "m4p", "mp3", "ogg", "sln", "wav", "wma"]
}
@media_types = DEFAULT_MEDIA_TYPES
@search_paths = [] of String
getter matches
@matches = [] of FileInfo
def initialize
end
def search_for(media_key : Symbol | String)
media_key = media_key.to_s
unless @media_types.has_key?(media_key)
raise "Media type '#{media_key}' is invalid"
end
file_exts = @media_types[media_key]
file_paths = [] of String
@search_paths.each do |path|
dir = Dir.glob(path)
puts "#{path}\t- found #{dir.size} files"
dir.reject! { |i| [".", ".."].includes?(i) }
file_paths.concat(dir)
end
file_paths.each do |p|
ext = p.split(".").last
info = {
name: File.basename(p),
directory: File.dirname(p),
size: File.size(p)
}
@matches.push(info) if file_exts.includes?(ext)
end
puts "Found #{@matches.size} #{media_key[0..-2]} files"
end
def add_search_path(path : String, base_dir = nil)
@search_paths.push( File.expand_path(path, base_dir) ).uniq!
end
end
m = MediaFinder.new
m.add_search_path "~/Pictures/**/*"
m.search_for :images
grouped = m.matches.group_by { |info| info[:directory] }
pp grouped
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment