1 # id3fs - a FUSE-based filesystem for browsing audio metadata
2 # Copyright (C) 2010 Ian Beckwith <ianb@erislabs.net>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 our $SCHEMA_VERSION=1;
26 my $dbfile=".id3fs"; # default
31 my $class=ref($proto) || $proto;
36 $self->{verbose}=shift;
39 $self->{dbpath}=shift || ($self->{base} . "/" . $dbfile);
40 $self->{dbpath}=Cwd::abs_path($self->{dbpath});
41 $self->{absbase}=Cwd::abs_path($self->{base});
43 my $connectstr="dbi:SQLite:dbname=$self->{dbpath}";
44 my $exists=-f $self->{dbpath};
45 $self->{dbh}=DBI->connect($connectstr, undef, undef,
47 unless(defined($self->{dbh}))
49 die("$self->{me}: DB Error: " . $DBI::errstr . "\n");
60 $self->enable_foreign_keys();
64 # search parent directories for db
68 shift if(ref($_[0]) eq "ID3FS::DB");
70 my($me, $init, @dirs)=@_;
74 # my $path=Cwd::abs_path($dir);
79 $path=~s/(.*)\/.*/$1/;
81 while(! -f "$base/$dbfile" && length($path) && -d $path);
82 if(-f "$base/$dbfile")
87 if(!-f "$base/$dbfile")
91 print "$me: db not found at $base/$dbfile\n";
100 sub base_dir { return shift->{base}; }
105 my @schema=split(/\n\n/,join("", <DATA>));
107 for my $cmd (@schema)
109 $self->{dbh}->do($cmd);
111 $self->cmd("INSERT INTO id3fs (schema_version, last_update) VALUES (?, ?)",
112 $SCHEMA_VERSION, time());
118 my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
119 if(!defined($version) || $version != $SCHEMA_VERSION)
121 die("$self->{me}: id3fs database version " .
122 defined($version) ? $version : '""' .
123 "not known, current version is $SCHEMA_VERSION.\n");
130 $self->cmd("ANALYZE");
133 sub enable_foreign_keys
136 $self->cmd("PRAGMA foreign_keys = ON");
141 my($self, $newval)=@_;
144 $self->cmd("UPDATE id3fs SET last_update=?", $newval);
148 ($newval)=$self->cmd_onerow("SELECT last_update from id3fs");
156 my $sql=("SELECT t1.name FROM tags t1\n" .
157 "LEFT JOIN tags t2 on t1.id=t2.parents_id\n" .
158 "WHERE t1.parents_id='' AND t2.id IS NULL\n" .
159 "GROUP BY t1.name\n");
160 my @names=$self->cmd_firstcol($sql);
167 my $sql=("SELECT p.name, t.name FROM tags t\n" .
168 "INNER JOIN tags p ON t.parents_id=p.id\n" .
169 "GROUP BY p.name, t.name\n");
170 my $result=$self->cmd_rows($sql);
172 for my $pair (@$result)
174 push(@{$tags->{$pair->[0]}}, $pair->[1]);
182 my $sql=("SELECT COUNT(*) FROM tags\n\t" .
183 "WHERE tags.parents_id=?\n");
184 my ($rows)=$self->cmd_onerow($sql, $id);
190 my($self, $path, $name, $mountpoint, $querypath)=@_;
191 my $rpath="$self->{absbase}/$path";
192 my $vpath=$mountpoint . $querypath;
193 my @path=split(/\//,$rpath);
194 my @rel=split(/\//,$vpath);
195 # drop filename from rel
197 # absolute paths have empty first element due to leading /
198 shift(@path) if($path[0] eq "");
199 shift(@rel) if($rel[0] eq "");
200 # f: /home/foo/bar/baz.mp3
201 # r: /home/ianb/music/albums
202 while(@path && @rel && ($path[0] eq $rel[0]))
207 my $upcount=scalar(@rel);
208 my $result="../" x $upcount;
209 $result .= join("/",@path);
217 my $relpath=Cwd::abs_path($path);
218 $relpath =~ s/^\Q$self->{absbase}\E\/?//;
219 my($filepart,$pathpart);
227 ($pathpart, $filepart) = ($relpath =~ /(.*)\/(.*)/);
229 my $file=ID3FS::AudioFile->new($path, $self->{me});
230 return unless(defined($file));
231 my $artist=$file->artist();
232 my $album=$file->album();
233 my $v1genre=$file->v1genre();
234 my $year=$file->year();
235 my $audiotype=$file->audiotype();
236 my @tags=$file->tags();
237 my $haspic=$file->haspic();
238 my $channels=$file->channels();
239 my $bitrate=$file->bitrate();
240 my $samplerate=$file->samplerate();
242 $artist=undef unless($self->ok($artist));
243 print "$self->{me}: $path: no artist tag defined\n" unless(defined($artist));
244 my $artist_id=$self->add_to_table("artists", $artist);
245 my $path_id=$self->add_to_table("paths", $pathpart);
246 $album=undef unless($self->ok($album));
247 # if($self->{verbose} && !defined($album)) FIXME
250 print "$self->{me}: $path: no album tag defined\n";
253 my $albums_id=$self->add_to_table("albums", $album);
254 my $file_id=$self->add_to_table("files", $filepart,
255 { "artists_id" => $artist_id,
256 "albums_id" => $albums_id,
257 "paths_id" => $path_id });
259 $self->remove_tag_refs($file_id);
264 $self->add_tag($file_id, @$tag);
269 $self->add_tag($file_id, "UNTAGGED");
272 $year="UNKNOWN" if(!$self->ok($year) || $year =~ /^0+$/);
273 $year+=1900 if($year=~/^\d\d$/);
274 $self->add_tag($file_id, "year", $year);
275 if($year=~/^(\d\d\d)\d$/)
277 $self->add_tag($file_id, "decade", "${1}0s");
281 $self->add_tag($file_id, "decade", "UNKNOWN");
284 if($self->ok($v1genre))
286 $self->add_tag($file_id, "v1genre", $v1genre);
291 $self->add_tag($file_id, "haspic", undef);
294 if($self->ok($audiotype))
296 $self->add_tag($file_id, "audiotype", $audiotype);
300 # should never happen
301 $self->add_tag($file_id, "audiotype", "UNKNOWN");
304 if($self->ok($channels))
306 if ($channels eq "2") { $channels="stereo"; }
307 elsif ($channels eq "1") { $channels="mono"; }
308 elsif ($channels eq "0") { $channels="UNKNOWN"; }
309 $self->add_tag($file_id, "channels", $channels);
312 if($self->ok($bitrate))
314 $bitrate="UNKNOWN" if($bitrate=~/^0+$/);
315 $self->add_tag($file_id, "bitrate", $bitrate);
318 if($self->ok($samplerate))
320 $samplerate="UNKNOWN" if($samplerate=~/^0+$/);
321 $self->add_tag($file_id, "samplerate", $samplerate);
328 my($self, $file_id, $tag, $value)=@_;
329 my $tag_id=$self->add_to_table("tags", $tag,
330 { "parents_id" => undef });
331 $self->add_relation("files_x_tags",
332 { "files_id" => $file_id,
333 "tags_id" => $tag_id });
334 if(defined($value) && length($value))
336 my $val_id=$self->add_to_table("tags", $value,
337 { "parents_id" => $tag_id });
338 $self->add_relation("files_x_tags",
339 { "files_id" => $file_id,
340 "tags_id" => $val_id });
346 my($self, $table, $name, $extradata)=@_;
348 if($extradata && $extradata->{parents_id})
350 $parent=$extradata->{parents_id};
352 my $id=$self->lookup_id($table, $name, $parent);
355 my $sql="INSERT INTO $table (";
357 if(defined($extradata))
359 push(@fields, sort keys(%$extradata));
361 $sql .= join(", ", @fields);
363 $sql .= join(", ", map { "?"; } @fields);
365 $id=$self->cmd_id($sql, $name, map { $extradata->{$_} || ""; } sort keys %$extradata);
372 my ($self, $relname, $fields)=@_;
373 return if($self->relation_exists($relname, $fields));
374 my $sql="INSERT INTO $relname (";
375 $sql .= join(", ", sort keys(%$fields));
376 $sql .= ") VALUES (";
377 $sql .= join(", ", map { "?"; } sort keys(%$fields));
379 $self->cmd($sql, map { $fields->{$_}; } sort keys(%$fields));
382 # remove existing files_x_tags relations before reindexing
386 my $sql="DELETE FROM files_x_tags WHERE files_id=?\n";
387 return($self->cmd($sql, $id));
393 my $sql=("SELECT files.name FROM files\n" .
394 "INNER JOIN paths ON files.paths_id=paths.id\n" .
395 "WHERE paths.name=?\n");
396 return($self->cmd_firstcol($sql, $dir));
401 my($self, $path, $file)=@_;
402 my $sql=("DELETE FROM files WHERE id IN (" .
403 "\tSELECT files.id FROM files\n" .
404 "\tINNER JOIN paths ON paths.id=files.paths_id\n" .
405 "\tWHERE paths.name=? and files.name=? )\n");
406 $self->cmd_rows($sql, $path, $file);
410 sub prune_directories
412 my($self,@includepaths)=@_;
413 my $sql=("SELECT name, id FROM paths\n");
414 my $pathsref=$self->cmd_rows($sql);
416 for my $pathpair (@$pathsref)
418 my($path, $id)=@$pathpair;
419 my $relpath = $self->{base} . "/" . $path;
420 next unless(grep { $relpath =~ /^$_/; } @includepaths);
421 my $fullpath="$self->{absbase}/$path";
427 $self->prune_paths(@ids);
435 my $sql=("DELETE FROM files WHERE paths_id IN (\n\t" .
436 join(', ', map { "\"$_\""; } @ids). "\n\t)");
444 DELETE FROM artists WHERE id IN (
445 SELECT artists.id FROM artists
446 LEFT JOIN files ON files.artists_id=artists.id
447 WHERE files.id IS NULL);
449 DELETE FROM albums WHERE id IN (
450 SELECT albums.id FROM albums
451 LEFT JOIN files ON files.albums_id=albums.id
452 WHERE files.id IS NULL);
454 DELETE FROM paths WHERE id IN (
455 SELECT paths.id FROM paths
456 LEFT JOIN files ON files.paths_id=paths.id
457 WHERE files.id IS NULL);
459 DELETE FROM files_x_tags WHERE files_id IN (
460 SELECT files_x_tags.files_id FROM files_x_tags
461 LEFT JOIN files ON files.id=files_x_tags.files_id
462 WHERE files.id IS NULL);
464 DELETE FROM tags WHERE id IN (
465 SELECT tags.id FROM tags
466 LEFT JOIN files_x_tags ON files_x_tags.tags_id=tags.id
467 WHERE files_x_tags.files_id IS NULL);
471 # print "SQL: $sql\n";
472 my @sql=split(/\n\n/, $sql);
473 $self->cmd($_) for (@sql);
478 my ($self, $relname, $fields)=@_;
479 my $sql="SELECT count(1) FROM $relname WHERE ";
482 for my $field (keys %$fields)
485 push(@vals,$fields->{$field});
487 $sql .= join(' AND ', map { "$_=?"; } @exprs);
488 my ($ret)=$self->cmd_onerow($sql, @vals);
494 my($self, $thing)=@_;
495 return(defined($thing) && length($thing) && $thing =~ /\S+/);
498 # actually call the database
501 my($self, $sql, @params)=@_;
502 my $sth=$self->{dbh}->prepare($sql);
504 for my $param (@params)
506 $param="" unless(defined($param));
507 $sth->bind_param($idx++, $param);
513 # pass cmd to db, ignore response
516 my ($self, @args)=@_;
517 # don't care about retcode
518 $self->cmd_sth(@args);
524 my ($self, @args)=@_;
525 my $sth=$self->cmd_sth(@args);
526 return($sth->fetchrow_array());
532 my ($self, @args)=@_;
533 my $sth=$self->cmd_sth(@args);
534 return $sth->fetchall_arrayref();
537 # returns just the first column
540 my ($self, @args)=@_;
541 return(map { $_->[0] } @{$self->cmd_rows(@args)});
544 # runs cmd, returns id of last insert
547 my ($self, @args)=@_;
548 $self->cmd_sth(@args);
549 return($self->last_insert_id());
555 return $self->{dbh}->last_insert_id("","","","");
558 # lookup id of $name in $table, also matching on $parent if needed
561 my($self, $table, $name, $parent)=@_;
562 my $sql="SELECT id FROM $table where name=?";
566 $sql .= " AND parents_id=?";
567 push(@args, $parent);
569 my($id)=$self->cmd_onerow($sql, @args);
576 schema_version INTEGER,
586 CREATE TABLE artists (
592 CREATE TABLE albums (
605 FOREIGN KEY(artists_id) REFERENCES artists(id) ON DELETE CASCADE ON UPDATE CASCADE,
606 FOREIGN KEY(albums_id) REFERENCES albums(id) ON DELETE CASCADE ON UPDATE CASCADE,
607 FOREIGN KEY(paths_id) REFERENCES paths(id) ON DELETE CASCADE ON UPDATE CASCADE
617 CREATE TABLE files_x_tags (
620 FOREIGN KEY(files_id) REFERENCES files(id) ON DELETE CASCADE ON UPDATE CASCADE,
621 FOREIGN KEY(tags_id) REFERENCES tags(id) ON DELETE CASCADE ON UPDATE CASCADE
624 CREATE INDEX idx_fxt_both ON files_x_tags (files_id, tags_id)
626 CREATE INDEX idx_fxt_tags ON files_x_tags (tags_id)
628 CREATE INDEX idx_files_id_name ON files (id, name)
630 CREATE INDEX idx_files_name_id ON files (name, id)
632 CREATE INDEX idx_tags_id_parent_name ON tags (id, parents_id, name)
634 CREATE INDEX idx_tags_parent_id_name ON tags (parents_id, id, name)
636 CREATE INDEX idx_tags_name ON tags (name)