From 79a9c99ec8598b4e6c84118fc26298d201686055 Mon Sep 17 00:00:00 2001 From: Andinus Date: Thu, 19 Nov 2020 00:42:29 +0530 Subject: Initial commit --- draco.pl | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100755 draco.pl (limited to 'draco.pl') diff --git a/draco.pl b/draco.pl new file mode 100755 index 0000000..da7f89a --- /dev/null +++ b/draco.pl @@ -0,0 +1,81 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use HTTP::Tiny; +use JSON::MaybeXS; + +# Priting UTF-8 to STDOUT. +binmode(STDOUT, "encoding(UTF-8)"); + +die "usage: draco \n" unless scalar @ARGV; + +# $url contains the reddit post. +my $url = shift @ARGV; +my $json_url = "${url}.json"; + +my $http = HTTP::Tiny->new( verify_SSL => 1 ); + +# Fetch the post. +my $response = $http->get($json_url); +die "Unexpected response - $response->{status}: $response->{reason}" + unless $response->{success}; + +# Decode json. +my $json_data = decode_json($response->{content}); + +# $post contains post data +my $post = $json_data->[0]->{data}->{children}->[0]->{data}; + +print "* ", "$post->{title}\n"; + +# Add various details to :PROPERTIES:. +print ":PROPERTIES:\n"; +foreach my $detail (qw( subreddit created_utc author permalink + upvote_ratio ups downs score )) { + print ":${detail}: =$post->{$detail}=\n" + if scalar $post->{$detail}; +} +print ":END:\n"; + +# Add selftext/url if present. +print "\n#+BEGIN_SRC markdown\n", "$post->{selftext}\n", "#+END_SRC\n" + if scalar $post->{selftext}; +print "$post->{url}\n" if scalar $post->{selftext}; + +# $comments contains comment data. We are interested in: replies, +# author, body, created_utc & permalink. +my $comments = $json_data->[1]->{data}->{children}; +# Iterate over top-level comments. +foreach my $comment ($comments->@*) { + print_comment_chain($comment->{data}, 0); +} + +# print_comment_chain will print the whole chain of comment while +# accounting for level. +sub print_comment_chain { + my $comment = shift @_; + my $level = shift @_; + + print "*" x ($level + 2), " ", "$comment->{author}\n"; + + # Print comment details. + print ":PROPERTIES:\n"; + foreach my $detail (qw( created_utc author permalink upvote_ratio + ups downs score edited is_submitter + stickied controversiality )) { + print ":${detail}: =$comment->{$detail}=\n" + if scalar $comment->{$detail}; + } + print ":END:\n"; + + print "\n#+BEGIN_SRC markdown\n", "$comment->{body}\n", "#+END_SRC\n"; + + # If the comment has replies then iterate over those too. + if (scalar $comment->{replies}) { + foreach my $reply ($comment->{replies}->{data}->{children}->@*) { + print_comment_chain($reply->{data}, $level + 1); + } + } +} -- cgit 1.4.1-2-gfad0