#!/usr/bin/perl -CIOESA -w # Download quotes from noobfarm.org, format into a fortune file. ($SELF = $0) =~ s,.*/,,; $VERSION = "0.9.99"; $fortunefile = 'noobfarm'; $jsonfile = 'noobfarm.json'; $indent = " " x 30; use JSON; use Getopt::Long; sub usage { print <; # from_json will die() on invalid input. Let it. my $j = from_json($input); for(@{$j->{Quotes}}) { my $quote = $_->{Quote}; my $date = $_->{Submitted}; # \ are doubled $quote =~ s,\\\\,\\,g; # some (but not all!) newlines are encoded as \\n instead of \n. # this is a potentially lossy transform: if the user in the quote # actually said a literal '\n', this will turn it into a newline. # in practice, this doesn't seem to be a problem. $quote =~ s,\\\\?n,\n,g; # turn \uXXXX hex escapes back into utf8 sequences. $quote =~ s,\\u([0-9a-fA-F]{4}),chr(hex $1),ge,; # dates look like: 2020-10-09T22:38:39.404662072Z # we only want 2020-10-09. $date = substr($date, 0, 10); $quotes{$_->{ID}} = $quote; $dates{$_->{ID}} = $date; } for(sort { $a <=> $b } keys %quotes) { push @output, $quotes{$_} . "\n" . "$indent-- noobfarm.org, quote #$_, $dates{$_}\n"; } close $fh; return join "%\n", @output; } # main() $help = $dlonly = $process_only = $outdir = 0; ### Parse options GetOptions( 'help' => \$help, 'download-only' => \$dlonly, 'output-dir=s' => \$outdir, 'no-format' => \$no_format, 'process-only' => \$process_only, 'keep-json' => \$keep_json, ) || usage(1); $keep_json++ if $dlonly | $process_only; ### Check options die "--download-only and --process-only can't both be given\n" if $dlonly && $process_only; die "Unknown argument(s): @ARGV" if @ARGV; usage(0) if $help; ### Create output dir, if needed if($outdir) { $outdir =~ s/['\\]//g; system("mkdir", "-p", $outdir); exit 1 unless -d $outdir && -w _; $fortunefile = "$outdir/$fortunefile"; } ### Download the JSON file (and exit, if --download-only) download unless $process_only; exit 0 if $dlonly; ### Open input & output filehandles open($infh, "<", $jsonfile) or die $!; if($no_format) { open(OUT, ">", $fortunefile) or die $!; } else { # using a shell pipe like this is the reason for not allowing # single quotes or backslashes in the output dir. I know it's not # "modern" or "best practice" but it's *so* convenient. open(OUT, "|fmt -s > '$fortunefile'") or die $!; } ### Write output, close filehandles print OUT format_quotes($infh); close $infh; close OUT; ### Clean up, unless asked not to if($keep_json) { print STDERR "Keeping JSON file $jsonfile\n"; } else { unlink($jsonfile); } ### Create the index fortune needs. Let strfile's exit status be ours. exec("strfile '$fortunefile'");