CodeRepos Ubiquitifier

Gist Ubiquitifierが良さそうなアイデアだったので、CodeRepos Ubiquitifierを作ってみました。

nameにスクリプト名(スクリプトのname)、codereposのrevision番号がパラメータで、以下のようなURLに例えばアクセスします。

http://localhost/~dann/ubiquity.cgi?name=cpan&revision=18672

そうすると、subscribe画面が出るので後はインストールするだけです。
上記のURLでインストールされるのは、
http://coderepos.org/share/browser/lang/javascript/ubiquity/cpan.js
スクリプトです。


http://gist.github.com/8406

#!/usr/bin/perl
use strict;
use warnings;
 
use Readonly;
use Template;
use LWP::UserAgent;
use HTTP::Request;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use utf8;
use Encode;
use open ':utf8';
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";
 
Readonly my $BASEURL => 'http://coderepos.org/share/export/';
Readonly my $UBIQUITY_DIR => '/lang/javascript/ubiquity/';
Readonly my $EXTENSION => '.js';
 
our $q;
main();
 
sub main {
    init();
    print_header();
    my $params = parse_parameters();
    validate_parameters($params);
    process_templae($params);
}
 
sub init {
    $q = new CGI;
}
 
sub print_header {
    print $q->header( -charset => "UTF-8" );
}
 
sub validate_parameters {
    my $params = shift;
    check_script_existed( _script_url($params) );
}
 
sub parse_parameters {
    my $params = {};
    $params->{name} = decode( 'utf-8', $q->param('name') );
    $params->{revision} = decode( 'utf-8', $q->param('revision') );
    $params;
}
 
sub check_script_existed {
    my $url = shift;
    my $request = HTTP::Request->new( GET => $url );
    my $ua = LWP::UserAgent->new;
    my $response = $ua->request($request);
    if ( $response->is_success ) {
        return;
    }
    else {
        die "oooops. this script doesn't exist on coderepos:" . $url;
    }
}
 
sub process_templae {
    my $opt = shift;
    my $tt = Template->new() || die $Template::ERROR, "\n";
    my $vars = { %{$opt}, url => _script_url($opt), };
    $tt->process( \*DATA, $vars ) || die $tt->error(), "\n";
}
 
sub _script_url {
    my $opt = shift;
    return
          $BASEURL
        . $opt->{revision}
        . $UBIQUITY_DIR
        . $opt->{name}
        . $EXTENSION;
}
 
__END__
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>CodeRepos Ubiquitifier</title>
    <link href="[% url | html %]" name="[% name | html %]" rel="commands" />
  </head>
  <body>
    <h1>
      Install Ubiquity Command: [% name | html %]
    </h1>
    <p>
    The source of this command is
    <a href="[% url | html %]">[% url | html %]</a>
    </p>
  </body>
</html>