#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell
# -*- coding: ascii -*-

#
# Copyright (C) 2010 Toni Gundogdu <legatvs@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use warnings;
use strict;

binmode( STDOUT, ":utf8" );
binmode( STDERR, ":utf8" );

use Getopt::ArgvFile( home => 1, startupFilename => [qw(.umphrc)] );
use Getopt::Long qw(:config bundling);

my $VERSION = "0.1.1";
my %config;
my @entries;
my $done = 0;

init();
main();
exit 0;

sub init {
    GetOptions(
        \%config,
        'interactive|i',
        'version|v' => \&print_version,
        'help|h'    => \&print_help,
    ) or exit(1);
}

sub print_version {
    print
"umph version $VERSION. Copyright (C) 2010 Toni Gundogdu. GNU GPL v3+.
This is free software; see the source for copying conditions. There is
NO warranty;  not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
";
    exit(0);
}

sub print_help {
    require Pod::Usage;
    Pod::Usage::pod2usage( -exitstatus => 0, -verbose => 1 );
}

sub main {

    print_help if scalar @ARGV == 0;

    my $req_body = "http://gdata.youtube.com/feeds/api/playlists/";

    my $url = $ARGV[0];

    if ( $url =~ /^http:/i ) {

        # Looks like an URL.
        if ( $url =~ /view_play_list\?p=(.*?)$/i ) {
            $url = "$req_body$1";
        }
    }
    else {

        # Assume playlist id.
        $url = "$req_body$url";
    }
    $url .= "?v=2";

    print STDERR "Fetch $url ...\n";

    require XML::DOM;

    my $p    = new XML::DOM::Parser;
    my $doc  = $p->parsefile($url);
    my $root = $doc->getDocumentElement;

    print STDERR ":: Parse playlist for video entries ...\n";

    for my $entry ( $root->getElementsByTagName("entry") ) {

        my $title = to_item( $entry, "title" )->getFirstChild->getNodeValue;

        my $link
            = to_item( $entry, "link" )->getAttributeNode("href")->getValue;

        my %data = ( title => $title, url => $link, selected => 1 );
        push @entries, \%data;
    }

    $doc->dispose;

    print STDERR "::: Found " . scalar @entries . " video entries\n";

    prompt() if $config{interactive};

    foreach (@entries) {
        print "$_->{url}\n" if $_->{selected} || !$config{interactive};
    }
}

sub to_item {
    my ( $entry, $name ) = @_;
    return $entry->getElementsByTagName($name)->item(0);
}

sub prompt {
    my $p    = "(umph) ";
    my %cmds = (
        'h' => \&help,
        'q' => \&quit,
        'l' => \&list,
        'd' => \&dump,
        'a' => \&select_all,
        'n' => \&select_none,
        'r' => \&revert_selection,
    );
    print STDERR "Enter prompt\nNote: all videos selected by default\n";
    print STDERR "Type \"help\" to get a list of commands\n";
    while ( !$done ) {
        print STDERR $p;
        my $ln = <STDIN>;
        next if !$ln;
        chomp $ln;
        if ( $ln =~ /(\d+)/ ) {
            toggle_number($1);
        }
        else {
            next if $ln !~ /(\w)/;
            $cmds{$1}() if defined $cmds{$1};
        }
    }
}

sub toggle_number {
    my $i = (shift) - 1;
    if ( $i >= 0 && exists $entries[$i] ) {
        $entries[$i]->{selected} = !$entries[$i]->{selected};
        list();
    }
    else {
        printf STDERR "error: out of range\n";
    }
}

sub help {
    print STDERR "
Commands:
  help      .. this
  list      .. display playlist entries (numbered, *=selected)
  all       .. select all videos
  none      .. select none
  revert    .. revert selection
  (number)  .. toggle (select, unselect) video, see list output
-
  dump      .. dump selected video urls to stdout and exit
  quit      .. terminate program

Command name abbreviations are allowed, e.g. \"a\" instead of \"all\".
";
}

sub quit {
    exit 0;
}

sub list {
    my $i = 0;
    foreach (@entries) {
        printf STDERR "%2d: $_->{title}%s\n", ++$i, $_->{selected} ? "*" : "";
    }
}

sub dump {
    $done = 1;
}

sub select_all {
    $_->{selected} = 1 foreach @entries;
    list();
}

sub select_none {
    $_->{selected} = 0 foreach @entries;
    list();
}

sub revert_selection {
    $_->{selected} = !$_->{selected} foreach @entries;
    list();
}

__END__

=head1 NAME

umph - Youtube video playlist parser for cclive and alike tools

=head1 SYNOPSIS

umph [options] [URL|PLAYLIST_ID]

=head1 DESCRIPTION

umph is a command line tool for parsing Youtube playlists. It prints
playlist video links, each separated with a newline, to the standard
output stream, while everything else gets printed to the standard
error stream. umph can be run with a simple interactive prompt to
select the printed video links.

=head1 OPTIONS

 -h, --help             print help and exit
 -v, --version          print version and exit
 -i, --interactive      be interactive, default is no

=head1 OPTION DESCRIPTIONS

=over 4

=item B<-h, --help>

Print help and exit.

=item B<-v, --version>

Print version and exit.

=item B<-i, --interactive>

Be interactive, default is no. Implies the interactive prompt which
can be used select the printed video links.

=back

=head1 EXAMPLES

=over 4

=item umph "http://www.youtube.com/view_play_list?p=AAF3A1D0CA1E304F"

=item umph AAF3A1D0CA1E304F

Both fetch and parse the same playlist (identified as "AAF3A1D0CA1E304F").

=item umph AAF3A1D0CA1E304F | cclive -f mp4

Passes the parsed video links to cclive.

=back

=head1 EXIT STATUS

Exits 0 on success, otherwise 1.

=head1 FILES

=over 4

=item $HOME/.umphrc, for example:

echo "--interactive" >> ~/.umphrc

=back

=head1 OTHER

umph depends on XML::DOM which uses LWP::UserAgent to retrieve
the playlist data. Note that LWP::UserAgent reads http_proxy
environment setting.

Project:
  http://umph.googlecode.com/

Development repository:
  git clone git://repo.or.cz/umph.git

=head1 SEE ALSO

C<cclive(1)> C<clive(1)>

=head1 AUTHOR

Toni Gundogdu <legatvs@gmail.com>

=cut


