Mostrando entradas con la etiqueta script. Mostrar todas las entradas
Mostrando entradas con la etiqueta script. Mostrar todas las entradas

sábado, 17 de septiembre de 2011

YouTube Searcher: Busca Videoclips de Música

Descripción:

Este script lista los videos de artistas (música) que están alojados en YouTube.

El listado de videos contempla el ID, nombre y duración de dichos videos.

Este script se puede complementar con otro script llamado "YouTube Downloader", el cual requiere del ID del video para descargarlo.

Enjoy!

#!/usr/bin/perl
use strict;
use HTTP::Lite;
use HTML::Entities;

#####################################################
#
# Desarrollado por: Zort
# Fecha: 16 de Septiembre de 2011
#
# Descripcion:
#   Este script lista los videos de artistas (musica) que
# estan alojados en YouTube.
#   El listado de videos contempla el ID, nombre y duracion
# de dichos videos.
#   Este script se puede complementar con otro script llamado
# "YouTube Downloader", el cual requiere del ID del video
# para descargarlo.
#
# Anexo:
#   Se omitieron todos los acentos en el codigo, para que no se
# vean caracteres erroneos en el caso de que el equipo donde
# se corra este codigo permita ver solo caracteres gringos.
#
#####################################################

my $artist = $ARGV[0];
$artist =~ s/^ +//;
$artist =~ s/ +$//;
$artist =~ s/ /_/g;

die "Usage: $0 artist\n\n" if ($artist eq '');

my $http = HTTP::Lite->new;
$http->http11_mode(1);

my $req = $http->request('http://www.youtube.com/artist/' . $artist);

if ($http->status() != 200) {
    print "No se pudo traer la pagina\n";
    exit;
}

# Getting the body page
my @body = split(/\n/, $http->body());

my $videos        = '';
my $artist_name   = '';
my $searching     = 0;
my $song_id       = 0;
my $song_duration = 0;
my $song_name     = 0;
foreach my $line (@body) {

    if ($line =~ /<h1>YouTube Mix for ([^<]*)</) {
        $artist_name = $1;
    }
    elsif ($line =~ /<h1>(Released in [0-9]+)/) {
        $videos .= "$1\n";
    }
    elsif ($line =~ / id="artist-videos" /) {
        $searching = 1;
    }
    elsif ($searching) {
        if ($line =~ /<li id="album-track-([^"]*)"/) {
            $song_id = $1;
        }
        elsif ($line =~ /<span class="album-track-duration">([^<]*)</) {
            $song_duration = $1;
        }
        elsif ($line =~ /<span class="description album-track-name">([^<]*)</) {
            $song_name = $1;
            $videos .= "  $song_id - " . decode_entities($song_name) . " ($song_duration)\n";
        }
    }
}

print "\n";
print 'Videos de "' . decode_entities($artist_name) . '":';
print "\n\n";
print $videos;

exit;

YouTube Downloader: Descarga Videos de YouTube

Yap, por fin salió!

Este script sirve para descargar videos de YouTube por CLI ;)

Lo único que tienen que hacer es ejecutar el script y pasarle como argumento el ID del video, luego el script preguntará el formato y resolución y... listo!

Enjoy!

#!/usr/bin/perl
use strict;
use HTTP::Lite;
use Data::Dumper;

#####################################################
#
# Desarrollado por: Zort
# Fecha: 16 de Septiembre de 2011
#
# Descripcion:
#   Este script descarga un video de YouTube especificado por
# el ID, el cual es entregado como parametro en la ejecucion.
#   A su vez, es posible elegir el formato y la resolucion
# del video segun la disponibilidad de YouTube de entregar el
# video con dichas caracteristicas.
#
# Anexo:
#   Se omitieron todos los acentos en el codigo, para que no se
# vean caracteres erroneos en el caso de que el equipo donde
# se corra este codigo permita ver solo caracteres gringos.
#   Se ha detectado que en ciertas ocasiones no se descarga
# el video. En estos casos se debe intentar nuevamente.
#
#####################################################

my $debug = 0;
my $video_id = $ARGV[0];

die "Usage: $0 video_id\n\n" if ($video_id eq '');

my $http = HTTP::Lite->new;
$http->http11_mode(1);

my $req = $http->request("http://www.youtube.com/get_video_info?video_id=$video_id&eurl=http%3A%2F%2Flocalhost%2F&hl=en_US")
    or die "Unable to get document: $!";

&showResponse($http) if ($debug);

if ($http->status() != 200) {
    print "The return code is not valid!\n";
    exit;
}

my $seconds        = 0;
my $fmt_stream_map = '';
my $fmt_list       = '';
my $title          = '';
my $token          = '';
my $formats        = ();

my @infos = split(/&/, $http->body());
foreach my $info (@infos) {

    my ($name, $value) = split(/=/, $info);

    $seconds        = $value            if ($name eq 'length_seconds');
    $fmt_stream_map = urlDecode($value) if ($name eq 'url_encoded_fmt_stream_map');
    $fmt_list       = urlDecode($value) if ($name eq 'fmt_list');
    $title          = urlDecode($value) if ($name eq 'title');
    $token          = $value            if ($name eq 'token');
}

my @formats_list = split(/,/, $fmt_list);
foreach my $format_list (@formats_list) {

    $format_list =~ /^([^\/]+)\/([^\/]+)\//;
    $formats->{$1}->{'resolution'} = $2;
}

my @formats_map = split(/,/, $fmt_stream_map);
foreach my $format_map (@formats_map) {

    my $url           = '';
    my $quality       = '';
    my $fallback_host = '';
    my $type          = '';
    my $itag          = '';

    my @variables = split(/&/, $format_map);
    foreach my $variable (@variables) {

        my ($name, $value) = split(/=/, $variable);

        $url           = urlDecode($value) if ($name eq 'url');
        $quality       = urlDecode($value) if ($name eq 'quality');
        $fallback_host = urlDecode($value) if ($name eq 'fallback_host');
        $type          = urlDecode($value) if ($name eq 'type');
        $itag          = $value            if ($name eq 'itag');
    }

    $formats->{$itag}->{'url'}           = $url;
    $formats->{$itag}->{'quality'}       = $quality;
    $formats->{$itag}->{'fallback_host'} = $fallback_host;
    $formats->{$itag}->{'type'}          = $type;
}

print "Titulo: $title\n";
print "Formatos:\n";
foreach my $format (sort { $formats->{$a}->{'type'} cmp $formats->{$b}->{'type'} } keys %{$formats}) {
    print " - (" . sprintf("%2d", $format) . ") " . $formats->{$format}->{'type'} . " (" . $formats->{$format}->{'quality'} . ") [" . $formats->{$format}->{'resolution'} . "]\n";
}
print "Opcion: ";
my $option = <STDIN>;
chomp($option);
print "Descargando numero $option...\n";
$http->reset();
$req = $http->request($formats->{$option}->{'url'});

my $output = $title;
$output .= '.mp4' if ($formats->{$option}->{'type'} =~ /video\/mp4/);
$output .= '.flv' if ($formats->{$option}->{'type'} =~ /video\/x-flv/);
$output .= '.webm' if ($formats->{$option}->{'type'} =~ /video\/webm/);

open(FH, '>', $output);
binmode(FH);
print FH $http->body();
close(FH);
print "Done!\n";
print "Archivo: '$output'\n";

   


#################
##  FUNCTIONS  ##
#################

sub showResponse() {

    my $http = shift;

    my $status     = $http->status();
    my $status_msg = $http->status_message();
    my @headers    = $http->headers_array();

    $status_msg =~ s/[\n\r]//g;

    print "Return Code:\n";
    print "    $status ($status_msg)\n";
    print "Headers:\n";
    foreach my $header (@headers) {
        print "    $header\n";
    }
    print "---------------------------\n";

    return 0;
}

sub urlDecode() {

    $_ = shift;

    s/\+/ /g;
    s/\%([0-9A-F]{2})/@{[chr hex $1]}/g;

    return $_;
}

jueves, 9 de septiembre de 2010

GetLyric: Buscador de Letras de Canciones

Bueno, aquí se viene otro código más...

Este entrega la letra (o lyric) de una cierta canción!

Como funciona:
Fácil, solo tienen que correr el Escri por linea de comando (usa Perl) y pasarle como parámetro el nombre del artista y el nombre de la canción.
El script buscará la letra en dos sitios distintos (en caso de que falle el primero, se utiliza el segundo ;) ) y si dá con él entonces lo mostrará por pantalla, sino, se queda callado y termina la ejecución del script corta y fome :P

Yap, espero que en este código no se me haya quedado una password o algo por el estilo (información sensible) ya que últimamente he cometido ese tipo de errores (pero gracias a Dios que tengo buenos amigos ;) )

Bueno, ahí está el código... Enjoy!

#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use HTML::Entities;


if (($ARGV[0] eq '') || ($ARGV[1] eq '')) {

    print "GetLyric 1.0 ( http://wischv.blogspot.com/ )\n";
    print "Autor: Walter Schmidt\n";
    print "Usage: $0 \"Artist\" \"Song\"\n";
    exit;
}

#################################################


#my $artist = '311';
#my $song   = 'Do You Right';
my $artist = $ARGV[0];
my $song   = $ARGV[1];


my $lyric = '';
if ($lyric = get_lyric_lyricsplugin($artist, $song)) {
    print $lyric;
}
elsif ($lyric = get_lyric_songlyrics($artist, $song)) {
    print $lyric;
}


#################
##  FUNCIONES  ##
#################

sub get_lyric_songlyrics {

    my $body;
    my $artist_song = lc($_[0] . '/' . $_[1]);
    $artist_song =~ s/' / /g; # Livin' And Rockin' => livin-and-rockin
    $artist_song =~ s/'$//g;  # Livin' And Rockin' => livin-and-rockin
    $artist_song =~ s/'$//g;  # Livin' And Rockin' => livin-and-rockin
    $artist_song =~ s/[\?\&\.' ]/-/g; # It's Alright => it-s-alright
    $artist_song =~ s/[^a-zA-Z0-9\-\/]//g;
    # El exceso de '-' (Ej: '---') son limpiados por el server

    my $ua = new LWP::UserAgent;
    my $resource = $ua->get("http://www.songlyrics.com/$artist_song-lyrics/");

    if ($resource->is_success) {

        $body = $resource->content;
        $body =~ s/[^[:print:]]//g;
        $body =~ /(<p id="songLyricsDiv".*)<p id="songLyricsSmallDiv"/i;
        my $lyric = $1;

        decode_entities($lyric);

        $lyric =~ s/<br \/>/\n/g; # Convierte los <br /> en <ENTER>'s
        $lyric =~ s/<[^>]*>//g;   # Elimina los TAGs de HTML existentes
        $lyric =~ s/\n\[ [^\n]+ are found on www.songlyrics.com \]//g; # Elimina los mensajes de Songlyric
        $lyric =~ s/ +/ /g;    # Elimina el exceso de espacios entre las palabras
        $lyric =~ s/^\s+//g;   # Elimina los espacios y <ENTER>'s del comienzo del Lyric
        $lyric =~ s/\n +/\n/g; # Elimina los espacios del comienzo de cada linea
        $lyric =~ s/ +\n/\n/g; # Elimina los espacios del final de cada linea
        $lyric =~ s/\n+$/\n/g; # Elimina el exceso de <ENTER> al final del Lyric

        return $lyric;
    }
    else {

        #print $resource->status_line . "\n";
        return 0;
    }
}


sub get_lyric_lyricsplugin {

    my $artist = shift;
    my $song   = shift;

    my $site   = 'http://www.lyricsplugin.com';
    my $ua = new LWP::UserAgent;
    my $resource = $ua->get("$site/wmplayer03/plugin/?title=$song&artist=$artist");


    if ($resource->is_success) {

        my $body = $resource->content;
        $body =~ /javascript:getContent\('([^']*)', '([^']*)', '([^']*)', '([^']*)'\)/;

        $resource = $ua->get("$site/wmplayer03/plugin/content.php?artist=$1&title=$2&timestamp=$3&hash=$4", 'Referer' => "http://www.lyricsplugin.com/wmplayer03/plugin/?title=$2&artist=$1");

        if ($resource->is_success) {

            my $lyric = '';
            my $lyric_flag = 0;
            foreach my $line (split /\n/, $resource->content) {

                last if (($line =~ /<\/div>/) && ($lyric_flag));
                if ($lyric_flag) {

                    $line =~ s/\r//;
                    $line =~ s/<br \/>/\n/;
                    $lyric .= $line;
                }
                $lyric_flag = 1 if ($line =~ /<div id="lyrics">/);
            }

            return ($lyric eq '') ? 0 : $lyric . "\n";
        }
        else {

            #print $resource->status_line . "\n";
            return 0;
        }
    }
    else {

        #print $resource->status_line . "\n";
        return 0;
    }
}

lunes, 12 de julio de 2010

[Script] Información de minutos utilizados en Entel

Yap, amigos míos... (no se a quien le hablo, si mal que mal, nadie me lee jajaja)
voy a subir un código de mi autoría.
Ya se... muchos tienen que estar preguntándose: ¿y a mi que!?. Bueno, a mi me gusta el código y lo subo igual, punto :)

El código fue creado con la intención de meterlo dentro de mi iPhone para consultar mis minutos utilizados en la telefonía movil de Entel (o EntelPCS), sin tener que logearme en el pinche sitio para ver la info (esa pega se la dejo al "escri").

Dentro del script hay una sección para que ingresen su RUT, número de teléfono y PIN (tranquilos, que el código NO toma esa información para luego enviármela a mi server super secreto "roba-password-entel" ;) ).

Yap... aquí va... (mientras no encuentre un sitio donde almacenarlo, lo subiré aquí grotescamente).

#!/usr/bin/perl

#####################################################
#
# Desarrollado por: Zort
# Fecha: 11 de Julio de 2010
#
# Descripcion:
#   Obtiene la cantidad de minutos hablados (llamadas realizadas),
# los SMS-MMS enviados y los KB navegados (Banda Ancha solamente)
# de la pagina de Entel.
#
# Anexo:
#   Se omitieron todos los acentos en el codigo, para que no se
# vean caracteres erroneos en el caso de que el equipo donde
# se corra este codigo permita ver solo caracteres gringos.
#
# TODO:
#   Ver la posibilidad de que corra bajo SSL.
#
#####################################################

use strict;
use HTTP::Lite;

# Configuracion
# -----------------------
my $debug = 0;
my $movil = ""; # AQUI INGRESEN EL NUMERO DE TELEFONO
my $rut   = ""; # AQUI INGRESEN EL RUT (EJ: 11.222.333-4)
my $pin   = ""; # AQUI INGRESEN EL PIN (EJ: 1234)
# -----------------------


my $value_voz;
my $value_mensajes;
my $value_banda_ancha;
my $flag_voz;
my $flag_mensajes;
my $flag_banda_ancha;
my $flag = 0;
my $cookie;
my $status_message;
my $location;
my $http = new HTTP::Lite;

# Realizando la primera consulta al servidor
# --------------------------------------------------------
my $buic_rutdv = $rut;
$buic_rutdv =~ s/[\.\-]//g;
$location = "http://www.entelpcs.cl/login/valida_ws.iws?origen=home";
my %vars = (
    "funcion" => "ingreso",
    "ext" => "%2526Sistema%253D1011%2526Portal%253DON%2526desdelogin%253D%2526miEPCS%253DNEW%2526MENU%253DSI",
    "Sistema" => "1011",
    "Portal" => "ON",
    "desdelogin" => "SI",
    "buic_rutdv" => $buic_rutdv,
    "miEPCS" => "NEW",
    "buic" => "yes",
    "Movil" => $movil,
    "Rut" => $rut,
    "PIN" => $pin
);
$http->prepare_post(\%vars);
print "*** Consulta: $location\n" if ($debug);
my $req = $http->request($location)
    or die "Unable to get document: $!";
$status_message = $http->status_message();
$status_message =~ s/[^[:print:]]//g;
print "STATUS: $status_message ($req)\n" if ($debug);
# --------------------------------------------------------


# Obteniendo la direccion del nuevo salto y la cookie asignada
# --------------------------------------------------------
my @headers = $http->headers_array();
foreach my $header (@headers) {

    print $header . "\n" if ($debug);
    if ($header =~ /^Location: (.*)$/) {

        $location = $1;
    }
    elsif ($header =~ /^Set-Cookie: (.*)/) {

        $cookie = $1;
    }
}
print "------------------------------------\n" if ($debug);
# --------------------------------------------------------


# Realizando la segunda consulta al servidor
# --------------------------------------------------------
$http->reset();
$http->add_req_header("Cookie", $cookie);
print "*** Consulta: $location\n" if ($debug);
my $req = $http->request($location)
    or die "Unable to get document: $!";
$status_message = $http->status_message();
$status_message =~ s/[^[:print:]]//g;
print "STATUS: $status_message ($req)\n" if ($debug);
# --------------------------------------------------------


# Obteniendo la direccion del nuevo salto y la cookie asignada
# --------------------------------------------------------
my @headers = $http->headers_array();
foreach my $header (@headers) {

    print $header . "\n" if ($debug);
    if ($header =~ /^Location: (.*)$/) {

        $location = $1;
    }
    elsif ($header =~ /^Set-Cookie: (.*)/) {

        $cookie = $1;
    }
}
print "------------------------------------\n" if ($debug);
# --------------------------------------------------------


# Realizando la tercera consulta al servidor
# --------------------------------------------------------
$http->reset();
$http->add_req_header("Cookie", $cookie);
my $req = $http->request($location)
    or die "Unable to get document: $!";
$status_message = $http->status_message();
$status_message =~ s/[^[:print:]]//g;
print "STATUS: $status_message ($req)\n" if ($debug);
# --------------------------------------------------------


# Obteniendo la direccion del nuevo salto y la cookie asignada
# --------------------------------------------------------
my @headers = $http->headers_array();
foreach my $header (@headers) {

    print $header . "\n" if ($debug);
    if ($header =~ /^Location: (.*)$/) {

        $location = $1;
    }
    elsif ($header =~ /^Set-Cookie: (.*)/) {

        $cookie = $1;
    }
}
print "------------------------------------\n" if ($debug);
# --------------------------------------------------------


# Obteniendo el valor del trafico
# --------------------------------------------------------
my @body = split(/\n/, $http->body());
foreach my $line (@body) {

    if ($line =~ /Voz /) {

        $flag_voz = 1;
    }
    elsif (($flag_voz ==1) && ($line =~ /center/)) {

        $line =~ /align="center">([^<\( ]*)/;
        $value_voz = $1;
        $flag_voz = 0;
    }
    elsif ($line =~ /Banda Ancha/) {

        $flag_banda_ancha = 1;
    }
    elsif (($flag_banda_ancha ==1) && ($line =~ /center/)) {

        $line =~ /align="center">([^<\( ]*)/;
        $value_banda_ancha = $1;
        $flag_banda_ancha = 0;
    }
    elsif ($line =~ /Mensajes/) {

        $flag_mensajes = 1;
    }
    elsif (($flag_mensajes ==1) && ($line =~ /center/)) {

        $line =~ /align="center">([^<\( ]*)/;
        $value_mensajes = $1;
        $flag_mensajes = 0;
    }
}
# --------------------------------------------------------


# Deslogeandose del servidor
# --------------------------------------------------------
$http->reset();
$location = "http://mipcs.entelpcs.com/mipcs2/login?accion=salir";
$http->add_req_header("Cookie", $cookie);
my $req = $http->request($location)
    or die "Unable to get document: $!";
$status_message = $http->status_message();
$status_message =~ s/[^[:print:]]//g;
print "STATUS: $status_message ($req)\n" if ($debug);
# --------------------------------------------------------


print "Trafico Voz        : $value_voz minutos\n";
print "Trafico Mensajes   : $value_mensajes SMS, MMS, otros\n";
print "Trafico Banda Ancha: $value_banda_ancha kilobytes\n";


exit 1;


Shaludos!
Zort