DB/Util/Playlists.pm untested

filter: Statementstmt 0.0% 0 / 198 Branchbran 0.0% 0 / 36 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 280 CC 19 SCAR 24.4
CC
19
Cov
0%
add_to_playlist
30.0
fetch_playlists
30.0
process_requests
12.0
CRAP 11.5
1 # Playlists.pm provides a variety of methods for dealing with playlists.
2 # This includes the basics (like adding and deleting songs from playlists),
3 # To actual streaming of recalled playlists,
4 # to retrieving all playlists from all users for display
5  
6 # Flow
7 # 1. Authenticate (either through mod_auth or by reading cookie)
8 # 2. Grab the user id from the cookie
9 # 3. Use that to do any sort of deletes or inserts...
10  
11 # Handles:
12 # Displaying a given users list of playlists
13 # Retrieval of a single playlist
14 # Let's them add a new playlist
15  
16 # NEED TO STANDARDIZE THE NAVIGATION ELEMENTS
17 # Lists of playlists need
18 # stream fetch
19 # Each playlist needs
20 # stream fetch for each song and stream fetch for whole playlist
21  
22  
23  
24 package Audio::DB::Util::Playlists;
25  
26 # $Id: Playlists.pm,v 1.2 2005/02/27 16:56:25 todd Exp $
27  
28 use strict 'vars';
29  
30 use CGI qw/:standard *table/;
31 use Audio::DB::Web;
32 use Audio::DB::Util::Rearrange; # Ubiquitous rearrange...
33 use vars qw($VERSION @ISA);
34 @ISA = 'Audio::DB::Web';
35  
36 my $MAIN = 'My Playlists';
37 my $EDIT = 'images/edit.gif';
38 my $DELE = 'images/edit.gif';
39  
40 # Need to store a dbh handle here
41 # as well as the user ID...
42 sub new {
43 my ($self,$dbh,$user_id) = @_;
44 my $this = bless { dbh => $dbh,
45 user_id => $user_id
46 },$self;
47 $this->process_requests();
48 return $this;
49 }
50  
51  
52 sub process_requests {
53 my $self = shift;
54 my $coderef = url_param('playlist');
55  
56 # Some coderefs are actually NOT url_params, things
57 # like adding songs to playlists, etc
58 $coderef = param('todo') if param('todo');
59 $coderef =~ s/\s/_/g;
60 $self->$coderef;
61  
62 # Print out the appropriate title...
63 # Better to do it here so that I can jump in later
64 # and print forms on the fly without the intervening table
65 # IN an ideal world, that is how it would work
66  
67 # Print out the various playlist options
68 $self->display_options(1) unless ($coderef eq 'display_options');
69 print end_div;
70 }
71  
72 sub display_options {
73 my ($self,$suppress) = @_;
74 $self->print_navigation() unless ($suppress);
75 print start_div({-class=>'configoptions'});
76 print h4($self->build_nav_link(-class=>'playlist',-action=>'browse_user_playlists',
77 -text=>'Browse Your Playlists'));
78 print h4($self->build_nav_link(-class=>'playlist',-action=>'browse_all_playlists',
79 -text=>'Browse All Playlists'));
80 print h4($self->build_nav_link(-class=>'playlist',-action=>'create_new_playlist',
81 -text=>'Create New Playlist'));
82 print h4($self->build_nav_link(-class=>'playlist',-action=>'delete_all_playlists',
83 -text=>'Delete All Of Your Playlists'));
84 }
85  
86  
87 sub create_new_playlist {
88 my ($self,$suppress) = @_;
89 my $user_id = $self->{user_id};
90 if (param('submit')) {
91 $self->print_navigation('Create A New Playlist (Results)');
92 $self->add_entry(-table => 'playlists',
93 -success_msg => 'The playlist ' . span({-class=>'name'},param('playlist'))
94 . ' has been successfully added.',
95 -user_id=>$user_id);
96 } else {
97 unless ($suppress) {
98 $self->print_navigation($self->build_nav_link(-class=>'playlist',-action=>'create_new_playlist',
99 -text=>'Create New Playlist'));
100 }
101 print start_div({-class=>'actioncontent'});
102 print "Use this form to add a new playlist.";
103 Delete('playlist');
104 print startform(),
105 start_table(),
106 TR(td('Playlist Name'),td(textfield({-name=>'playlist'}))),
107 TR(td('Description'),td(textfield({-name=>'description'}))),
108 TR(td('Publically viewable?'),td(popup_menu({-name=>'is_shared',-values=>[qw/yes no/]}))),
109 TR(td({-colspan=>2,-align=>'right'},
110 submit(-name=>'submit',-label=>'Add New Playlist'))),
111 end_table;
112 # Fetch all the user playlists
113 print end_div;
114 }
115 }
116  
117  
118  
119  
120  
121 # Currently, this just displays a flat listing of the playlist?
122 sub display_playlist {
123 my ($self,$id) = @_;
124 $id ||= url_param('id');
125 my $tracks = $self->fetch_playlists(-type=>'filled',-id=>$id);
126 # I need some blanket description of the playlist here
127  
128 # Also need all of my typical checkboxes...
129 my @cols = qw/Select stream song artist album genre/;
130 print div({-class=>'actionbyline'},"Browsing Playlist");
131 print start_div({-class=>'actioncontent'});
132 print start_table(),TR(td(\@cols));
133
134 my $count;
135 my $total;
136 foreach my $song (@$tracks) {
137 # Build up some links for each item.
138 # can't use the normal mechanism since the individual songs are not blessed.
139 my $song_link = $self->build_url('song',$song);
140 my $album_link = $self->build_url('album',$song);
141 my $artist_link = $self->build_url('artist',$song);
142 my $genre_link = $self->build_url('genre',$song);
143
144 $total++;
145 $count = ($count eq 'one' ) ? 'two' : 'one';
146 print start_TR({-class=>"shade$count"});
147 # $self->print_checkboxes($song,$total);
148 my $track;
149
150 # I should only print the artist column if this is a compilation CD
151 print
152 td($song_link),
153 td($artist_link),
154 td($album_link),
155 td($song->{duration}),
156 td($song->{bitrate}),
157 td($genre_link),
158 end_TR;
159 }
160 # line 500
161 print end_table,end_div;
162 }
163  
164  
165  
166 #######################################################
167 # BROWSING PLAYLISTS
168 #######################################################
169 sub browse_all_playlists {
170 my $self = shift;
171 $self->print_navigation($self->build_nav_link(-class=>'playlist',
172 -action=>'browse_all_playlists',
173 -text=>'Browse All Playlists'));
174 my $playlists = $self->fetch_playlists(-type=>'all');
175 if ($playlists) {
176 print div({-class=>'actionbyline'},"All User Playlists");
177 print start_div({-class=>'actioncontent'});
178 my @cols = (qw/Playlist Owner Description Created/);
179 print start_table(),TR(td(\@cols));
180 foreach (@$playlists) {
181 print TR(td($self->link_playlist($_->{playlist},$_->{playlist_id})),
182 td($_->{username} . "(" . $_->{first_name} . ' ' . $_->{last_name} . ")"),
183 td($_->{description}),
184 td($_->{created}));
185 }
186 print end_table,end_div;
187 } else {
188 print div({-class=>'actionbyline'},"There aren't any user-created playlists yet.",br,
189 $self->build_nav_link(-class=>'playlist',
190 -action=>'create_new_playlist',
191 -text=>'Create A New Paylist'));
192 }
193 }
194  
195 sub browse_user_playlists {
196 my $self = shift;
197 $self->print_navigation($self->build_nav_link(-class=>'playlist',
198 -action=>'browse_user_playlists',
199 -text=>'Browse My Playlists'));
200 my $playlists = $self->fetch_playlists(-type=>'by_user');
201 if ($playlists) {
202 # Also need all of my typical checkboxes...
203 my @cols = qw/Playlist Description Public edit delete/;
204 print div({-class=>'actionbyline'},"These are your currently available playlists:");
205 print start_div({-class=>'actioncontent'});
206 print start_table(),TR(td(\@cols));
207 foreach (@$playlists) {
208 print TR(
209 # What should this link really be?
210 td($self->link_playlist($_->{playlist},$_->{playlist_id})),
211 td($_->{description}),
212 td($_->{is_shared}),
213 td($self->build_edit_link('edit',$_->{playlist_id})),
214 td($self->build_edit_link('delete',$_->{playlist_id})),
215 );
216 }
217 print end_table,end_div;
218 } else {
219 print div({-class=>'actionbyline'},"You haven't created any playlists yet.",br,
220 $self->build_nav_link(-class=>'playlist',
221 -action=>'create_new_playlist',
222 -text=>'Create A New Paylist'));
223 }
224 }
225  
226  
227 sub build_edit_link {
228 my ($self,$type,$id) = @_;
229 my $IMG;
230 if ($type eq 'edit') {
231 $IMG = $EDIT;
232 } else {
233 $IMG = $DELE;
234 }
235  
236 my $url = url();
237 return a({-href=>$url . '?playlist=' . $type . '_playlist&id=' . $id },
238 img({-src=>$IMG}));
239 }
240  
241 #######################################################
242 # EDITING PLAYLISTS
243 #######################################################
244 sub add_to_playlist {
245 my $self = shift;
246 my $dbh = $self->{dbh};
247  
248 # Which playlist are we trying to add to?
249 my $playlist_id = param('playlist');
250  
251 # Now, fetch out the id's of everything that we are trying to add to the playlist
252 # Have to iterate over the checkboxes to get them all. Yuck.
253 # There must be some way to shortcircuit though, yes?
254 my @to_add;
255 for (my $i=1;$i<=10000;$i++) {
256 push (@to_add,param('checkbox' . $i));
257 }
258  
259 # Can add several things:
260 # 1. A list of songs...
261 # 2. A list of albums...
262 # 3. A list of artists...
263 # 4. A list of genres...
264
265 # Each checkbox is called class_id
266 # Extract the class from the first element in the list
267 my $class = ($to_add[0] =~ /(.*)_.*/) ? $1 : 'songs';
268
269 # The easiest case - a bunch of songs.
270 # Just add them all to the playlist table.
271 my $count;
272 if ($class eq 'songs') {
273 foreach (@to_add) {
274 my $id = ($_ =~ /.*_(.*)/) ? $1 : '';
275 my $result = $self->insert_songs($playlist_id,$id);
276 $count += $result;
277 }
278 # Now I have to fetch all of the songs
279 # that are associated with a given album, artist, or genre...
280 } else {
281 my %queries = (albums => 'album_id',
282 artists => 'artist_id',
283 genres => 'genre_id');
284
285 my $query = $queries{$class};
286 my $sth = $dbh->prepare(qq{select song_id from songs where } . $query . qq{=?});
287 foreach (@to_add) {
288 my $id = ($_ =~ /.*_(.*)/) ? $1 : '';
289 $sth->execute($id);
290 while (my ($song_id) = $sth->fetchrow_array) {
291 my $result = $self->insert_songs($playlist_id,$song_id);
292 $count += $result;
293 }
294 }
295 }
296
297 # Now display a message and the number of tracks add ed to the playlist
298 print "$count tracks were added to: ";
299 $self->display_playlist($playlist_id);
300 }
301  
302  
303 sub insert_songs {
304 my ($self,$playlist_id,$song_id) = @_;
305 my $dbh = $self->{dbh};
306 $dbh->do("insert into playlist_songs (playlist_id,song_id) VALUES ($playlist_id"
307 . ',' . $dbh->quote($song_id) . ')');
308 my $result = abs $dbh->rows;
309 return $result;
310 }
311  
312  
313  
314  
315 # MAYBE EDITS SHOULD JUST BE SUPERSEDED WITH A SINGLE CHECBOX ON EACH
316 # listing?
317 # THIS NEEDS TO BE FLESHED OUT...
318 # I will be editing a single playlist at a time...
319 ### IT"S NOT DONE YET
320  
321 # THIS WILL BE A LINK IN
322 sub edit_playlist {
323 my $self = shift;
324 $self->print_navigation($self->build_nav_link(-class=>'playlist',
325 -action=>'edit_playlist',
326 -text=>'Edit Playlists'));
327
328 my $id = url_param('id');
329 my $tracks = $self->fetch_playlists(-type=>'filled',-id=>$id);
330  
331 my @cols = qw/select Song Artist Album Genre/;
332 print div({-class=>'actionbyline'},
333 "Use this form to edit the tracks of the current playlists");
334 print start_div({-class=>'actioncontent'});
335 print startform(),
336 start_table();
337 print TR(td(\@cols));
338
339 # First I need to print a header for the playlist, letting user edit the name
340 # and shared properties.
341 # print
342 # hidden(-name=>'playlist_id',-value=>$h->{playlist_id});
343 # print
344 # TR(td(textfield({-name=>'playlist',-value=>$h->{playlist},-size=>15})),
345 ## td(textfield({-name=>'description',-value=>$h->{description},-size=>15})),
346 # td(textfield({-name=>'email',-value=>$h->{created},-size=>20})),
347 # td(popup_menu({-name=>'is_shared',-values=>[qw/yes no/]})));
348 #
349 # $sth->execute();
350 # while (my $h = $sth->fetchrow_hashref) {
351 #
352 # }
353 print end_table;
354 print submit(-name=>'submit',-label=>'Update Users');
355 print end_div;
356 }
357  
358  
359 sub delete_playlist {
360  
361 }
362  
363  
364 sub delete_all_playlists {
365  
366 }
367  
368  
369  
370 sub playlist_popup {
371 my $self = shift;
372 # Flow
373 # 1. Create the popup window
374 # 2. Fetch user playlists
375 # 3. Display form
376
377 # Processing...
378 # Should songs be added to new playlist?
379 # Creat playlist, then add songs.
380 # Should songs be added to existing playlist?
381 # Popupmen presents: view playlist or return...
382  
383 # Example code for creating a javapopup window
384 # <script language="javascript" type="text/javascript">
385 # function OpenComments (c) {
386 # window.open('<$MTCGIPath$>mt-comments.cgi?' +
387 # 'entry_id=' + c,
388 # 'comments',
389 # 'width=480,height=480,scrollbars=yes,status=yes');
390 #}
391 #</script>
392 #
393 #}
394 }
395  
396  
397 #######################################################
398 # SUPPORT: Fetching, streaming, linking, navigating
399 #######################################################
400  
401 # Fetch all the current playlists associated with
402 # this user and return
403 # This could be generalized to get lists of all playlists
404 # from all users
405 # Or perhaps that should just be a seperate sub
406  
407 # Could also be modified to return a filled list
408 # This might actually be usefull, because then I can build the page
409 # from that
410  
411 # Should this be a factory churning out Playlistlist objects?
412  
413 sub fetch_playlists {
414 my ($self,@p) = @_;
415 my ($type,$id) = rearrange([qw/TYPE ID/],@p);
416  
417 # Cases:
418 # 1. fetch playlists for a specific user,
419 # 2. Browse all playlists
420 # 3. fetch an individual playlist
421
422 # UI could present a popupmenu for each user
423 # Or alternatively, could expand them all
424 my $user_id = $self->{user_id};
425 my $dbh = $self->dbh;
426  
427 # This is the flat query that simply returns all the playlists
428 # but does not actually list the song ids
429 my %queries = ( by_user => qq{select * from playlists where user_id=?},
430 all => qq{select * from playlists,users where
431 playlists.user_id=users.user_id
432 ORDER BY last_name},
433 expanded => qq{select *,count(song_id) from playlists,playlist_songs
434 where
435 playlists.user_id=?
436 and playlists.playlist_id=playlist_songs.playlist_id
437 GROUP BY playlist_id},
438 filled => qq{select * from playlists,playlist_songs,songs,artists,albums,genres
439 where
440 playlists.playlist_id=?
441 and playlists.playlist_id=playlist_songs.playlist_id
442 and playlist_songs.song_id=songs.song_id
443 and songs.artist_id=artists.artist_id
444 and songs.genre_id=genres.genre_id
445 and songs.album_id=albums.album_id});
446 my $results = [];
447 my $sth = $dbh->prepare($queries{$type});
448 if ($type eq 'by_user') {
449 $sth->execute($user_id);
450 } elsif ($type eq 'filled') {
451 # Argh! What should this be and where should it come from?
452 $sth->execute($id);
453 } elsif ($type eq 'all') {
454 $sth->execute();
455 } else {
456 $sth->execute();
457 }
458
459 my $c;
460 while (my $h = $sth->fetchrow_hashref) {
461 push (@$results,$h);
462 $c++;
463 }
464 return '' if $c < 1;
465 return $results;
466 }
467  
468  
469 # This will be a generic link in, and not for streaming
470 sub link_playlist {
471 my ($self,$playlist,$id) = @_;
472 my $url = url();
473 return a({-href=>$url . '?playlist=' . 'display_playlist&id=' . $id },$playlist);
474 }
475  
476 sub stream_link {
477  
478 }
479  
480  
481 # THIS CONTROLS NAVIGATIONAL FORMATTING
482 sub print_navigation {
483 my ($self,@fields) = @_;
484 print start_div({-class=>'actiontitle'}),
485 $self->build_nav_link(-class=>'playlist',-action=>'display_options',
486 -text=>$MAIN);
487 print ' / ' if (@fields);
488 print join (' / ',@fields);
489 print end_div;
490 }
491  
492  
493  
494  
495 1;
496  
497 =pod
498 Methods:
499 user management
500 multiplaylists / user (and option to share with others)
501
502 user ratings (for songs and playlists)
503
504 browse by letter of alphabet, genre, album
505 Stats reporting
506  
507  
508 =head1 NAME
509  
510 Apache::Audio::DB - Generate a database of your tunes complete with searchable interface and nifty statistical analyses!
511  
512 =head1 SYNOPSIS
513  
514 # httpd.conf or srm.conf
515 AddType audio/mpeg mp3 MP3
516
517 # httpd.conf or access.conf
518 <Location /songs>
519 SetHandler perl-script
520 PerlHandler Apache::MP3::Sorted
521 PerlSetVar SortFields Album,Title,-Duration
522 PerlSetVar Fields Title,Artist,Album,Duration
523 </Location>
524  
525 =head1 TODO
526  
527  
528 Streaming code and links
529  
530 BUILDING URLs from non-blessed items...need to handle this because
531 it will come up alot
532  
533 DB.pm Use lincolns code for scanning files
534  
535 Browse filesystem
536  
537 Update DB scripts
538  
539 HTML module of common formatting options
540 configuration page...
541 limits to return
542 option to download tarballs
543
544 Figure out how to track paths and such...
545 Preserving this state is kinda hairy
546  
547 CLEAN UP THE BUILD URL SUB
548 OPTIMIZE QUERIES AND OBJECT CONSTRUCTION
549 SEPEERATE OUT OBJECT CODE
550  
551 Seperate out HTML formatting into a seperate module
552  
553 Error checking and handling
554  
555 Streaming code
556 Column Sorting
557 User management
558 Playlist integration
559 Playlist sharing
560 Multiple Playlists
561 Interface preferences
562  
563  
564 =head1 DESCRIPTION
565  
566 Apache::Audio::DB subclasses Apache::MP3 to generate a relational database
567 of your music collection. This allows browsing by various criteria that
568 are not available when simply browsing the filesystem. For example,
569 users my browse by genre, year, or era. Apache::Audio::DB also provides
570 search capabilities.
571  
572 =head1 CUSTOMIZING
573  
574 This class adds several new Apache configuration variable.
575  
576 Database specific variables:
577 ----------------------------
578 Value Default
579 PerlSetVar DB_Name database name musicdb
580 PerlSetVar Create boolean no
581 PerlSetVar Host database user name localhost
582 PerlSetVar User user name
583 PerlSetVar Password db password
584
585 =over 4
586  
587 =item B<DB_Name> I<field>
588  
589 This is the name of the database. If not provided, musicdb will be used.
590  
591 =item B<Create>
592  
593 Examples:
594  
595 PerlSetVar SortFields Album,Title # sort ascending by album, then title
596 PerlSetVar SortFields +Artist,-Kbps # sort ascending by artist, descending by kbps
597  
598 When constructing a playlist from a recursive directory listing,
599 sorting will be B<global> across all directories. If no sort order is
600 specified, then the module reverts to sorting by file and directory
601 name. A good value for SortFields is to sort by Artist,Album and
602 track:
603  
604 PerlSetVar SortFields Artist,Album,Track
605  
606 Alternatively, you might want to sort by Description, which
607 effectively sorts by title, artist and album.
608  
609 The following are valid fields:
610  
611 Field Description
612
613 album The album
614 artist The artist
615 bitrate Streaming rate of song in kbps
616 comment The comment field
617 description Description, as controlled by DescriptionFormat
618 duration Duration of the song in hour, minute, second format
619 filename The physical name of the .mp3 file
620 genre The genre
621 samplerate Sample rate, in KHz
622 seconds Duration of the song in seconds
623 title The title of the song
624 track The track number
625  
626 Field names are case insensitive.
627  
628 =back
629  
630 =head1 METHODS
631  
632 Apache::MP3::Sorted overrides the following methods:
633  
634 sort_mp3s() mp3_table_header() mp3_list_bottom()
635  
636 It adds one new method:
637  
638 =over 4
639  
640 =item $field = $mp3->sort_fields
641  
642 Returns a list of the names of the fields to sort on by default.
643  
644  
645  
646 #### UI ELEMENTS THAT HAVEN'T BEEN REWORKED YET
647 #sub amg_link {
648 # my ($artist,$link_text) = @_;
649
650 # # Encode $artist for searching: UC, replace \s with |, replace ' and ,
651 # my $artist_encoded = uc $artist;
652 # $artist_encoded =~ s/\s/|/g;
653 # $artist_encoded =~ s/[,\'\-]//g;
654 # my $base_url = 'http://allmusic.com/cg/x.dll?p=amg&optl=1&sql=1';
655
656 # my $full_url = $base_url . $artist_encoded;
657
658 # # Formulate the AMG URL
659 # my $amg_link = '<a href="' . $base_url . $artist_encoded . '">' .
660 # $link_text . "</a>";
661
662 # return($amg_link);
663 #}