Skip to content

Instantly share code, notes, and snippets.

@ecounysis
Created July 11, 2011 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecounysis/1075214 to your computer and use it in GitHub Desktop.
Save ecounysis/1075214 to your computer and use it in GitHub Desktop.
console tool for reading Hacker News
#!/usr/bin/env perl
use JSON;
use strict;
no warnings;
use HTML::Entities;
my $command = @ARGV[0];
my $home = $ENV{'HOME'};
if (not (-e "$home/.hn")) {
mkdir "$home/.hn"
}
if (($command eq "get") or ($command eq "next") or ($command eq "")) {
my $next = "";
if ($command eq "next") {
open HNJSON, "<", "$home/.hn/json";
my $jsonstring = <HNJSON>;
close HNJSON;
my $json_obj = decode_json $jsonstring;
$next = "/" . %$json_obj->{'nextId'};
}
my $url = "http://api.ihackernews.com/page$next";
print "$url\n\n";
my $jsonstring = `curl -s $url`;
my $json_obj = decode_json $jsonstring;
open HNJSON, ">", "$home/.hn/json";
print HNJSON $jsonstring;
close HNJSON;
my $items = %$json_obj->{'items'};
my $ctr = 1;
my $title;
my $points;
foreach my $item (@$items) {
$title = $item->{'title'};
$points = $item->{'points'};
print "[$ctr] $title ($points) \n";
$ctr += 1;
}
}
elsif (($command >= 1) and ($command <= 30)) {
my $url;
open HNJSON, "<", "$home/.hn/json";
my $jsonstring = <HNJSON>;
close HNJSON;
my $json_obj = decode_json $jsonstring;
my $items = %$json_obj->{'items'};
$url = @$items[$command-1]->{'url'};
if ((substr $url, 0, 8) eq "/comment") {
$url = "http://ihackernews.com" . $url;
}
elsif (($ARGV[1] eq "comments") or ($ARGV[1] eq "c")) {
$url = "http://ihackernews.com" . "/comments/" . @$items[$command-1]->{'id'};
}
print "$url\n\n";
my $text = `curl -s $url`;
decode_entities($text);
$text =~ s/<br ?\/?>/LINEBREAKLINEBREAK/gi; # convert br tags
$text =~ s/<\/title>/LINEBREAKLINEBREAKLINEBREAK/gi;
$text =~ s/<\/h[1-9]>/LINEBREAK/gi;
$text =~ s/<\/p>/LINEBREAK/gi; # convert p tags
$text =~ s/<\/li>/ /gi;
$text =~ s/<!--.*?-->//g; # don't care about comments
$text =~ s/<script.*?<\/script>//gis; # don't care about scripts
$text =~ s/<style.*?<\/style>//gis; # don't care about styles
$text =~ s/<[^>]*>//g; # remove the rest of the tags and leave text
$text =~ s/\t/\n/g;
$text =~ s/\s{4,}/\n/g;
$text =~ s/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+//g; # remove blank lines
$text =~ s/LINEBREAK/\n/g;
$text =~ s/(.{70,80})\s/\1\n/g; # add line breaks
print $text;
}
else {
print "usage: hn [command]\n";
print " commands\n";
print " get\n";
print " next\n";
print " 1\n";
print " 2\n";
print " ...\n";
print " 30\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment