commit:32a4b6e15c792e9ff9cb0a4bf7b5ffc806e90305
author:Chip Black
committer:Chip Black
date:Mon Feb 9 02:15:54 2009 -0600
parents:982003c8b1a20123a9dde92b4009dc57f778e725
Made cleaning more robust, added scan function

Fixed some unicode issues in the clean function.  Apparently the sqlite
DBD returns octets that may or may not be UTF, and it's up to you to
tell Perl to do the right thing by decode()ing it.

Added a scan function to replace the find | udb add method (which was
a bit clumsy).  Also changed fullpath() so that it lops off a leading
./ in paths.
diff --git a/udb.pl b/udb.pl
line changes: +29/-5
index 9a12b5e..262cb5f
--- a/udb.pl
+++ b/udb.pl
@@ -4,10 +4,14 @@ use strict;
 use DBI;
 use Digest::MD5;
 use Audio::TagLib;
+use File::Find;
+use Encode;
 
 my $uthome = "$ENV{HOME}/.utunes";
 
-my $dbh = DBI->connect("dbi:SQLite:dbname=$uthome/tunes.db","","");
+my $dbh = DBI->connect("dbi:SQLite:dbname=$uthome/tunes.db","","")
+	or die "Could not open utunes DB";
+$dbh->{unicode} = 1;
 my $rv = $dbh->do("SELECT count(*) FROM tunes LIMIT 1");
 if (!$rv) {
 	print "Creating database schema...\n";
@@ -37,7 +41,8 @@ my $pwd;	# Our working directory won't change
 chomp ($pwd = `pwd`);
 sub fullpath {
 	my $path = shift;
-	return $path if m'^/';
+	return $path if $path =~ m'^/';
+	$path =~ s'^\./'';
 	return "$pwd/$path";
 }
 
@@ -96,7 +101,7 @@ sub db_add {
 
 	my $r = $dbh->selectrow_arrayref(qq{SELECT count(*) FROM tunes WHERE hash="$hash"});
 	if ($r->[0] == 1) {
-		return;
+		return 1;
 	}
 
 	my $f = Audio::TagLib::FileRef->new($file);
@@ -152,6 +157,8 @@ sub db_add {
 	my $statement = "INSERT INTO tunes (" . join(',',@keys) . ") values (" . join(',',@values) . ")";
 	#print $statement,"\n";
 	$dbh->do($statement);
+
+	return 1;
 }
 
 sub db_rm {
@@ -220,8 +227,9 @@ if ($ARGV[0] eq 'add') {
 	$sth->execute;
 	my $r;
 	while ($r = $sth->fetchrow_hashref()) {
-		if (blacklisted($r->{filename}) || ! -e $r->{filename}) {
-			print "Purging $r->{filename}\n";
+		if (blacklisted($r->{filename}) ||
+		    ! (-e $r->{filename} || -e decode('utf8', $r->{filename}))) {
+			print "Purging |$r->{filename}|\n";
 			my $hash = $r->{hash};
 			$dbh->do(qq{DELETE FROM tunes WHERE hash="$hash"});
 		}
@@ -297,6 +305,22 @@ if ($ARGV[0] eq 'add') {
 			last unless @files;
 		}
 	}
+} elsif ($ARGV[0] eq 'scan') {
+	shift;
+	unless (@ARGV) {
+		print "No directories specified\n";
+		exit 1;
+	}
+	for my $dir (@ARGV) {
+		unless (-d $dir) {
+			print "$dir is not a directory\n";
+			exit 1;
+		}
+	}
+	find(sub {
+		return unless -f;
+		db_add($File::Find::name) or print "Could not add $File::Find::name\n";
+	}, @ARGV);
 } elsif ($ARGV[0] eq 'import') {
 	my $db = $ARGV[1];
 	unless ($db) {