DB/Web.pm untested

filter: Statementstmt 0.0% 0 / 230 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 345 CC 24 SCAR 30.6
CC
24
Cov
0%
process_requests
90.0
add_entry
20.0
build_url
20.0
CRAP 21.3
1 package Audio::DB::Web;
2  
3 # $Id: Web.pm,v 1.2 2005/02/27 16:56:25 todd Exp $
4  
5 # ALL THE SQL queries need to be moved in dbi::mysql module
6  
7 use strict 'vars';
8 use vars qw(@ISA $VERSION);
9 #use Apache::Constants qw(:common REDIRECT HTTP_NO_CONTENT);
10  
11 use CGI qw/:standard *table *div *TR/;
12 use CGI::Cookie;
13  
14 use DBI;
15 use Audio::DB;
16 use Audio::DB::Query;
17 use Audio::DB::Util::Rearrange;
18 use Audio::DB::Util::SystemConfig;
19 use Audio::DB::Util::Playlists;
20  
21 use Audio::DB::DataTypes::Artist;
22 use Audio::DB::DataTypes::ArtistList;
23 use Audio::DB::DataTypes::Album;
24 use Audio::DB::DataTypes::AlbumList;
25 use Audio::DB::DataTypes::Genre;
26 use Audio::DB::DataTypes::GenreList;
27 use Audio::DB::DataTypes::Song;
28 use Audio::DB::DataTypes::SongList;
29  
30 @ISA = qw/Audio::DB Audio::DB::Query/;
31  
32 ###################################################
33 # The new constructor is inherited from Audio::DB #
34 ###################################################
35  
36 # Farms out requests to various subs,
37 # creating the appropriate objects
38 sub process_requests {
39 my $self = shift;
40 return ($self->authenticate()) if (param('submit') eq 'Log In');
41
42 # Nothing to process if the action is a 'tryin'
43 # to retrieve the search form...passed as the 'search' value to the action key
44 return if (url_param('action') eq 'search');
45
46 # System Configuration, including user management
47 return Audio::DB::Util::SystemConfig->new($self->dbh) if (url_param('admin'));
48
49 # PLAYLISTS - Either trying to manipulate a playlist
50 # by a form, grab it by a url...
51 if (param('todo') eq 'add to playlist' || url_param('playlist')) {
52 return Audio::DB::Util::Playlists->new($self->{dbh},$self->{user_id});
53 } elsif (url_param('song_id')) {
54 return ($self->_fetch_song);
55 } else {
56 # Searches from the form
57 # Generating a coderef on the fly??
58 my $coderef = 'search' if param('search_term');
59 $coderef ||= url_param('action') . '_' . url_param('class')
60 if (url_param('action') && url_param('class'));
61 if ($coderef) {
62 my $results = $self->$coderef;
63 return $results;
64 }
65 }
66 }
67  
68  
69  
70 ################################
71 # Generic database manipulation
72 ################################
73 # Used for adding playlists and new users to the database...
74 # This is a generic variant of the add...
75 sub add_entry {
76 my ($self,@p) = @_;
77 my ($table,$msg,$detailed,$user_id) = rearrange([qw/TABLE SUCCESS_MSG DETAILED USER_ID/],@p);
78 my $dbh = $self->{dbh};
79 Delete('submit');
80
81 my @params = param();
82 my (@cols,@quoted);
83 foreach (@params) {
84 push (@quoted,$dbh->quote(param($_)));
85 push (@cols,$_);
86 }
87  
88 if ($user_id) {
89 push(@quoted,$user_id);
90 push(@cols,'user_id');
91 }
92  
93 my $result = $dbh->do("insert into " . $table . "("
94 . join(",",@cols)
95 . ") VALUES ("
96 . join(",",@quoted) .")");
97 if ($result) {
98 print div({-class=>'success'},$msg);
99 if ($detailed) {
100 print start_div({-class=>'actioncontent'});
101 my @ordered_params = qw/first_name last_name username password email joined privs/;
102
103 print start_table(-width=>'50%');
104 foreach (@ordered_params) {
105 print TR(td($_),td(param($_)));
106 }
107 print end_table,end_div;
108 }
109 } else {
110 $self->print_sql_error($dbh->errstr);
111 }
112 }
113  
114  
115  
116 # DEPRECATED BUT MAY BE USEFUL FOR GENERATING PAN QUERIES
117 ## Should I expand the artist query?
118 #my %queries = (
119 # # Get a count of the distinct albums so
120 # # information can easily be presented on
121 # # a preliminary page without additional queries
122 # artist => qq{select *,COUNT(DISTINCT album)
123 # from artists,album_artists,albums
124 # where artist REGEXP ?
125 # and artists.artist_id=album_artists.artist_id
126 # and album_artists.album_id=albums.album_id
127 # GROUP by artist ORDER BY artist},
128 #
129 # # Group on album_id to keep from clobbering
130 # # albums of the same name
131 # album => qq{select * from albums,album_artists,artists
132 # where album REGEXP ?
133 # and albums.album_id=album_artists.album_id
134 # and album_artists.artist_id=artists.artist_id
135 # GROUP BY albums.album_id ORDER BY album},
136 #
137 # song => qq{select * from songs,artists,albums
138 # where song REGEXP ?
139 # and songs.artist_id=artists.artist_id
140 # and songs.album_id=albums.album_id
141 # GROUP by title ORDER by title}
142 # );
143  
144  
145  
146 # SONG SEARCH NEEDS TO BE IMPLEMENTED
147 sub search {
148 my $self = shift;
149
150 my $class = lc param('class');
151 my $query = '.*' . param('search_term') . '.*';
152 my $field = $class;
153
154 # Create a generic container object of the appropriate class
155 # to return the results
156 my $this = bless { class=>ucfirst $field . 'List'},"Audio::DB::DataTypes::" .
157 ucfirst param('class') . 'List';
158  
159 my $adaptor = $self->adaptor;
160 $this = $adaptor->generic_search(-class=>$class,
161 -query=>$query,
162 # -container=>$container);
163 );
164 return $this;
165 }
166  
167  
168  
169 ##########################################
170 # Miscellaneous formatting and navigation
171 ##########################################
172 # Some navigation tools
173 sub browse_navigation {
174 my ($self,$msg) = @_;
175 my @values = qw/0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z/;
176 my @links;
177 foreach (@values) {
178 # This should be a constant
179 push @links,
180 a({-href=>"/music.cgi?action=browse&class=$msg&$msg=$_"},$_);
181 }
182 return \@links;
183 }
184  
185  
186 # If provided with a blessed object, generate a link to that object
187 # Optionally provided with a class, will link to that
188 # if that psuedo class exists within the object
189 # It's also possible to just pass in a "fake" (non-blessed)
190 # object for linking...
191 sub build_url {
192 my ($self,$class,$fake_object) = @_;
193 $class ||= $self->{class};
194
195 my ($link_text,$target);
196 if ($fake_object) {
197 $link_text = $fake_object->{$class};
198 # Kludge for column name
199 $link_text = $fake_object->{title} if ($class eq 'song');
200 $target = $fake_object->{$class . '_id'};
201 } else {
202 $link_text = $self->{$class};
203 $target = $self->{$class . '_id'};
204 # Kludge for column name
205 $link_text = $self->{title} if ($class eq 'song');
206 }
207 my $action = url_param('action') || 'browse';
208 my $primary = $class ."_id";
209
210 $link_text =~ s/[<>]//g;
211 $target =~ s/[<>]//g;
212
213 my $full_url = url();
214 my $url = '<a href="' . $full_url .
215 "?action=$action" . "&class=$class" .
216 "&$primary=$target"
217 .'">' . $link_text . "</A>";
218 }
219  
220 # Build up some generic URL for navigation
221 sub build_nav_link {
222 my ($self,@p) = @_;
223 my ($class,$action,$text) = rearrange([qw/CLASS ACTION TEXT/],@p);
224 my $url = url();
225 my $link = a({-href=>$url . '?' . $class . '=' . $action},$text);
226 return $link;
227 }
228  
229  
230 sub table_navigation {
231 my ($self,@p) = @_;
232 my ($type,$span) = rearrange([qw/TYPE SPAN/],@p);
233  
234 my @values = qw/# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z/;
235 print start_div({-class=>"navigation"});
236 print start_table();
237 my $count = 0;
238 foreach (@values) {
239 # End the previous row if necessary...
240 if ($count == $span) {
241 print end_TR;
242 $count = 0;
243 }
244
245 if ($count == 0) {
246 print start_TR({-class=>'navigation'});
247 }
248
249 print td({-class=>'navcell'},
250 a({-href=>"/music/music.cgi?action=browse&class=$type&$type=$_"},$_));
251 $count++;
252 }
253 print end_table;
254 print end_div;
255 }
256  
257 # Display buttons for the bottom of the page
258 sub buttons {
259 my $self = shift;
260 my $playlists = Audio::DB::Util::Playlists->fetch_playlists(-type=>'by_user');
261 # my $playlists = $self->fetch_playlists(-type=>'by_user');
262 my $playlists = [];
263 my (@ids,%labels);
264 foreach (@$playlists) {
265 push (@ids,$_->{playlist_id});
266 $labels{$_->{playlist_id}} = $_->{playlist};
267 }
268 print start_table({-width=>'100%'});
269 print TR({-class=>'colheaders'},td('action'),td('tracks'),td('Available Playlists'),td(''));
270 print TR(
271 td(radio_group({-name=>'todo',
272 -values=>['stream','fetch','add to playlist'],
273 -linebreak=>1})),
274 # td(popup_menu({-values=>['stream','fetch','to playlist...']})),
275 td(radio_group({-name=>'the_chosen',
276 -values=>[qw/All Selected/],
277 -linebreak=>1})),
278 td(popup_menu({-name=>'playlist',
279 -values=>\@ids,
280 -labels=>\%labels})),
281 td(submit()));
282  
283 print a({-href=>"javascript:OpenPlaylists(" . $self->{user_id} . ")"},
284 "Add to playlist...");
285  
286 # print a({-onclick=>"window.open('music.cgi?action=add_to_playlist&user
287 #-href=>"javascript:OpenPlaylists(" . $self->{user_id} . ")"},
288 # "Add to playlist...");
289 }
290  
291  
292 # NEED TO FIGURE OUT HOW TO LINK IN...
293 # THIS BELONGS IN THE MODULE
294 sub print_checkboxes {
295 my ($self,$obj,$count) = @_;
296 my $class = $obj->class;
297 my $id_coderef = $class . '_id';
298 print
299 td({-align=>'center'},
300 checkbox({-name =>'checkbox' . $count,
301 -value =>$class . 's_' . $obj->$id_coderef,
302 -label => ''})
303 );
304 print td('stream');
305 }
306  
307  
308 #######################################
309 # Basic browsing and searching methods
310 #######################################
311 # This is for generic letter based browsing...
312 sub browse_by_letter {
313 my ($self,$field) = @_;
314  
315 my $query = "^" . url_param($field) . '.*';
316 my $adaptor = $self->adaptor;
317  
318 # This creates a container object in which to store everything
319 my $this = bless { class=>ucfirst $field . 'List'},"Audio::DB::DataTypes::" . ucfirst $field . 'List';
320 my $sth = $adaptor->fetch_by_letter($query,$field);
321 my $dbh = $self->dbh;
322  
323 # This should all probably be moved to dbi::mysql since it has the fetchrow query
324 while (my $h = $sth->fetchrow_hashref) {
325 # Create brief summary objects of each of the albums or artists that are
326 # returned.
327 if ($field eq 'album') {
328 my $obj = Audio::DB::DataTypes::Album->new(-data=>$h);
329 push (@{$this->{albums}},$obj);
330 } else {
331 my $obj = Audio::DB::DataTypes::Artist->new(-data=>$h);
332 push (@{$this->{artists}},$obj);
333 }
334 }
335 return $this;
336 }
337  
338  
339 # Browse specific wrappers around different parameters
340 sub browse_genre {
341 my $self = shift;
342 my $artist_id = url_param('artist_id');
343 my $genre_id = url_param('genre_id');
344 my $adaptor = $self->adaptor;
345  
346 # Browse by an artist id....
347 if ($artist_id) {
348 return (Audio::DB::DataTypes::Artist->new(-adaptor=>$adaptor,-id=>$artist_id));
349 # Or a genre id...
350 } elsif ($genre_id) {
351 return (Audio::DB::DataTypes::Genre->new(-adaptor=>$adaptor,-id=>$genre_id));
352 } else {
353 return (Audio::DB::DataTypes::GenreList->new(-adaptor=>$adaptor));
354 }
355 return;
356 }
357  
358 sub browse_artist {
359 my $self = shift;
360 my $artist = url_param('artist');
361 my $artist_id = url_param('artist_id');
362 my $album_id = url_param('album_id');
363 my $adaptor = $self->adaptor;
364  
365 # 2004: THIS SHOULD BE FETCH ARTIST...
366 if ($artist) {
367 return ($self->browse_by_letter('artist'));
368 } elsif ($album_id) {
369 return (Audio::DB::DataTypes::Album->new(-adaptor=>$adaptor,-id=>$album_id));
370 } else {
371 return (Audio::DB::DataTypes::Artist->new(-adaptor=>$adaptor,-id=>$artist_id));
372 }
373 }
374  
375  
376  
377 sub browse_album {
378 my $self = shift;
379 my $album = url_param('album');
380 my $album_id = url_param('album_id');
381 my $adaptor = $self->adaptor;
382  
383 my $results = [];
384 if ($album) {
385 return ($self->browse_by_letter('album'));
386 } elsif ($album_id) {
387 return (Audio::DB::DataTypes::Album->new(-adaptor=>$adaptor,-id=>$album_id));
388 } else { }
389  
390 ### EMPTY - SHOULD JUST RETURN THE NAVIGATION
391
392 # This should just return the naviagation...
393 # $results = $self->retrieve_artist();
394 # }
395 return $results;
396 }
397  
398  
399 # NOT YET IMPLEMENTED
400 sub _fetch_song {
401 my $self = shift;
402 my $dbh = $self->dbh;
403
404 my $sth = $dbh->prepare(qq{select * from songs,genres,artists,albums
405 where songs.song_id=?
406 and songs.artist_id=artists.artist_id
407 and songs.genre_id=genres.genre_id
408 and songs.album_id=albums.album_id});
409 $sth->execute(url_param('song_id'));
410 my $h = $sth->fetchrow_hashref;
411 return (Audio::DB::DataTypes::Song->new($h));
412 }
413  
414  
415  
416  
417 ####################################
418 # Authentication and cookie control
419 ####################################
420 # This is my simple-minded cookie-based authentication scheme
421 # Move into sql
422 #sub check_cookie {
423 # my $self = shift;
424 #
425 # # Fetch the cookie if there is one...
426 # my %cookie = cookie(-name => 'musicdb');
427 # my $user_id = $cookie{userid};
428 #
429 # # If a cookie was present, let's make sure to reset it ...
430 # if ($user_id) {
431 # $self->build_cookie($user_id);
432 # return;
433 # } elsif (param('submit') eq 'Log In') {
434 # $self->authenticate();
435 # } else {
436 # $self->{cookie} = 'NOT AUTHENTICATED';
437 # }
438 #}
439 #
440 #sub build_cookie {
441 # my ($self,$user_id) = @_;
442 # # Store the user id in the object for
443 # # building custom page elements
444 # $self->{user_id} = $user_id;
445 #
446 # # Could easily store more information in the cookie, too...
447 # my %vals = (userid => $user_id);
448 # my $cookie = cookie(-name =>'musicdb',
449 # -value=>\%vals);
450 # $self->{cookie} = $cookie;
451 # return;
452 #}
453 #
454 #sub authenticate {
455 # my $self = shift;
456 # my $password = param('password');
457 # my $dbh = $self->dbh;
458 # my $sth = $dbh->prepare(qq{select password,user_id from users where username=?});
459 # $sth->execute(param('username'));
460 # my ($pass,$user_id) = $sth->fetchrow_array;
461 # if ($pass eq $password) {
462 # $self->build_cookie($user_id);
463 # return;
464 # } else {
465 # $self->{cookie} = 'BOGUS GUESS';
466 # }
467 #}
468  
469  
470  
471 1;
472  
473  
474 =pod
475  
476 =head1 NAME
477  
478 Audio::DB::Web - Assists in web-based queries of an MP3 Database
479  
480 =head1 SYNOPSIS
481
482 use Audio::DB::Web;
483 my $mp3->
484  
485  
486 =head1 DESCRIPTION
487  
488 Audio::DB is a module for creating relational databases of MP3 files directly
489 from data stored in ID3 tags. Once created, Audio::DB provides various
490 methods for creating reports and web pages of your collection. Although
491 it's nutritious and delicious on its own, Audio::DB was created for use
492 with Apache::Audio::DB, a subclass of Apache::MP3. This module makes it
493 easy to make your collection web-accessible, complete with browsing,
494 searching, streaming, multiple users, playlists, ratings, and more!
495  
496 =head1 REQUIRES
497  
498 This module is designed to work with the data schema created
499 and loaded by B<Audio::DB>. It's not going to do you mch good without it.
500  
501 =head1 EXPORTS
502
503 No methods are exported.
504
505 =head1 CAVEATS
506  
507 =head1 METHODS
508  
509  
510 =head2 fetch_user_playlists();
511  
512 Title : fetch_user_playlists
513 Usage : $mp3->fetch_user_playlists();
514 Function : fetches all playlists
515 Returns : A hash reference relating user playlist names to IDs
516 suitable for building forms.
517 Args : -filled
518 Status : Public
519  
520  
521  
522 Methods:
523 user management
524 multiplaylists / user (and option to share with others)
525
526 user ratings (for songs and playlists)
527
528 browse by letter of alphabet, genre, album
529 Stats reporting
530  
531  
532 =head1 NAME
533  
534 Apache::Audio::DB - Generate a database of your tunes complete with searchable interface and nifty statistical analyses!
535  
536 =head1 SYNOPSIS
537  
538 # httpd.conf or srm.conf
539 AddType audio/mpeg mp3 MP3
540
541 # httpd.conf or access.conf
542 <Location /songs>
543 SetHandler perl-script
544 PerlHandler Apache::MP3::Sorted
545 PerlSetVar SortFields Album,Title,-Duration
546 PerlSetVar Fields Title,Artist,Album,Duration
547 </Location>
548  
549 =head1 TODO
550  
551  
552 Streaming code and links
553  
554 BUILDING URLs from non-blessed items...need to handle this because
555 it will come up alot
556  
557 DB.pm Use lincolns code for scanning files
558  
559 Browse filesystem
560  
561 Update DB scripts
562  
563 HTML module of common formatting options
564 configuration page...
565 limits to return
566 option to download tarballs
567
568 Figure out how to track paths and such...
569 Preserving this state is kinda hairy
570  
571 CLEAN UP THE BUILD URL SUB
572 OPTIMIZE QUERIES AND OBJECT CONSTRUCTION
573 SEPEERATE OUT OBJECT CODE
574  
575 Seperate out HTML formatting into a seperate module
576  
577 Error checking and handling
578  
579 Streaming code
580 Column Sorting
581 User management
582 Playlist integration
583 Playlist sharing
584 Multiple Playlists
585 Interface preferences
586  
587  
588 =head1 DESCRIPTION
589  
590 Apache::Audio::DB subclasses Apache::MP3 to generate a relational database
591 of your music collection. This allows browsing by various criteria that
592 are not available when simply browsing the filesystem. For example,
593 users my browse by genre, year, or era. Apache::Audio::DB also provides
594 search capabilities.
595  
596 =head1 CUSTOMIZING
597  
598 This class adds several new Apache configuration variable.
599  
600 Database specific variables:
601 ----------------------------
602 Value Default
603 PerlSetVar DB_Name database name musicdb
604 PerlSetVar Create boolean no
605 PerlSetVar Host database user name localhost
606 PerlSetVar User user name
607 PerlSetVar Password db password
608
609 =over 4
610  
611 =item B<DB_Name> I<field>
612  
613 This is the name of the database. If not provided, musicdb will be used.
614  
615 =item B<Create>
616  
617 Examples:
618  
619 PerlSetVar SortFields Album,Title # sort ascending by album, then title
620 PerlSetVar SortFields +Artist,-Kbps # sort ascending by artist, descending by kbps
621  
622 When constructing a playlist from a recursive directory listing,
623 sorting will be B<global> across all directories. If no sort order is
624 specified, then the module reverts to sorting by file and directory
625 name. A good value for SortFields is to sort by Artist,Album and
626 track:
627  
628 PerlSetVar SortFields Artist,Album,Track
629  
630 Alternatively, you might want to sort by Description, which
631 effectively sorts by title, artist and album.
632  
633 The following are valid fields:
634  
635 Field Description
636
637 album The album
638 artist The artist
639 bitrate Streaming rate of song in kbps
640 comment The comment field
641 description Description, as controlled by DescriptionFormat
642 duration Duration of the song in hour, minute, second format
643 filename The physical name of the .mp3 file
644 genre The genre
645 samplerate Sample rate, in KHz
646 seconds Duration of the song in seconds
647 title The title of the song
648 track The track number
649  
650 Field names are case insensitive.
651  
652 =back
653  
654 =head1 METHODS
655  
656 Apache::MP3::Sorted overrides the following methods:
657  
658 sort_mp3s() mp3_table_header() mp3_list_bottom()
659  
660 It adds one new method:
661  
662 =over 4
663  
664 =item $field = $mp3->sort_fields
665  
666 Returns a list of the names of the fields to sort on by default.
667  
668  
669  
670 #### UI ELEMENTS THAT HAVEN'T BEEN REWORKED YET
671 #sub amg_link {
672 # my ($artist,$link_text) = @_;
673
674 # # Encode $artist for searching: UC, replace \s with |, replace ' and ,
675 # my $artist_encoded = uc $artist;
676 # $artist_encoded =~ s/\s/|/g;
677 # $artist_encoded =~ s/[,\'\-]//g;
678 # my $base_url = 'http://allmusic.com/cg/x.dll?p=amg&optl=1&sql=1';
679
680 # my $full_url = $base_url . $artist_encoded;
681
682 # # Formulate the AMG URL
683 # my $amg_link = '<a href="' . $base_url . $artist_encoded . '">' .
684 # $link_text . "</a>";
685
686 # return($amg_link);
687 #}
688  
689 #sub print_search_button {
690 # print center(
691 # startform(-action=>$full_url),
692 # submit(-name=>'submit',
693 # -value=>'Search Again'),
694 # endform);
695 # return;
696 #}