Skip to content

Instantly share code, notes, and snippets.

@therobot
Created January 16, 2012 10:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therobot/1620169 to your computer and use it in GitHub Desktop.
Save therobot/1620169 to your computer and use it in GitHub Desktop.
Delete songs present in the itunes music folder but not in itunes library
#!/usr/bin/env ruby
#
# Dependencies:
#
# This script requires to build and install the branch 'location' of this https://github.com/jaymcgavren/itunes-library fork of 'itunes-library'
# It also requires to install 'colorize' gem
#
# License: GPLv2
# http://www.gnu.org/licenses/gpl-2.0.html
#
require 'rubygems'
require 'itunes-library/library'
require 'find'
require 'colorize'
ITUNES_DIR='/Users/therobot/Music/iTunes/iTunes Music'
ITUNES_LIBRARY='/Users/therobot/Music/iTunes/iTunes Music Library.xml'
MEGABYTE = 1024.0 * 1024.0
def to_mb bytes
bytes / MEGABYTE
end
def get_itunes_library
library = ITunes::Library.load(ITUNES_LIBRARY)
begin
library.size
rescue
puts "iTunes library not found, check the ITUNES_LIBRARY constant for a valid path to the itunes music library xml."
exit -1
end
library
end
def find_and_clean(library)
total_size = 0
Find.find(ITUNES_DIR) do |f|
unless File.directory?(f)
total_size += clean_file(f, library)
end
end
puts "A total of #{(to_mb(total_size)).to_s} MB have been freed."
end
def song_in_itunes?(file, library)
library.music.tracks.select { |t| t.location.sub('file://localhost','').downcase == file.downcase }.empty?
end
def podcast_in_itunes?(file, library)
library.podcasts.tracks.select { |t| t.location.sub('file://localhost','').downcase == file.downcase }.empty?
end
def file_in_itunes?(file, library)
! song_in_itunes?(file, library) || ! podcast_in_itunes?(file, library)
end
def is_dsstore?(file)
File.basename(file) == '.DS_Store'
end
def mark_for_deletion(file, library)
mark = true
if is_dsstore?(file)
puts "Deleting file #{file.red}"
elsif ! file_in_itunes?(file, library)
puts "Deleting #{file.red} since it is not your in itunes anymore but the file still exists."
else
mark = false
end
mark
end
def clean_file(file, library)
size = 0
if mark_for_deletion(file, library)
size = File.size(file)
File.delete(file)
end
size
end
def main
library = get_itunes_library
find_and_clean(library)
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment