Name: Anonymous 2013-10-20 22:56
Post a random function that you made. May be from any project you've done or make one impromptu.
Any QUALITY is allowed. No bullying!
Any QUALITY is allowed. No bullying!
#!/usr/bin/perl -w
use strict;
use warnings;
use Encode qw(decode_utf8);
use File::Temp qw(tempdir tempfile);
use File::Path qw(make_path);
use HTML::Parser;
use LWP::Simple qw(getstore);
use LWP::UserAgent;
use URI::Escape qw(uri_unescape);
my $ua = LWP::UserAgent->new;
$ua->agent("Some kind of randomized wget machine/0.2.1");
my $pl_parser = HTML::Parser->new( api_version => 3,
start_h => [\&pl_start, "tagname, attr"],
end_h => [\&pl_end, "tagname"],
marked_sections => 1,
);
my $req = HTTP::Request->new(GET => 'http://otokei-douj.in/');
my $pl_in_playlist = 0;
my @playlist = ();
my $res = $ua->request($req);
if ($res->is_success) {
$pl_parser->parse(decode_utf8($res->content));
} else {
die ($res->status_line . "\n");
}
if ($#playlist < 0) {
die ("Couldn't get any elements - has the site changed layout?");
}
my $subpage = "http://otokei-douj.in/" . $playlist[rand @playlist];
$req = HTTP::Request->new(GET => $subpage);
@playlist = ();
$res = $ua->request($req);
if ($res->is_success) {
$pl_parser->parse(decode_utf8($res->content));
} else {
die ($res->status_line . "\n");
}
if ($#playlist < 0) {
die ("Couldn't get any elements - has the site changed layout?");
}
my $dlpage = "http://otokei-douj.in/download.php" . $playlist[rand @playlist];
my $dir = tempdir( CLEANUP => 1 );
my ($fh, $filename) = tempfile( DIR => $dir, SUFFIX => '.7z' );
my @title_parts = ($dlpage =~ /link=%2F(.*)&album=(.*)/);
system("wget -q \"$dlpage\" -O \"$filename\"");
# One side effect of not pulling the link exactly is that '+' is
# present where '%20' would be if a second page were followed. Actual
# '+' characters are still represented as %2B, so this will not harm
# actual filenames
$title_parts[0] =~ s/\+/%20/g;
$title_parts[0] = decode_utf8(uri_unescape($title_parts[0]));
make_path($title_parts[0]);
system("7z x \"-o$title_parts[0]\" \"$filename\"");
# ----------------------------------------------------------------------
# Parsing functions:
sub pl_start {
my ($tagname, $attr) = @_;
if ($tagname eq "ul" && $attr->{'class'} eq "playlist") {
$pl_in_playlist = 1;
} elsif ($tagname eq "a" && $pl_in_playlist == 1) {
push (@playlist, $attr->{'href'});
}
}
sub pl_end {
my ($tagname) = @_;
if ($tagname eq "ul") {
$pl_in_playlist = 0;
}
}