get_factordb.pl 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 16 December 2019
  4. # https://github.com/trizen
  5. # Extract factors from factordb.com for a given number, using FactorDB's API.
  6. use 5.020;
  7. use warnings;
  8. use experimental qw(signatures);
  9. use CHI;
  10. use JSON qw(from_json);
  11. use WWW::Mechanize::Cached;
  12. use URI::Escape qw(uri_escape);
  13. use File::Basename qw(dirname);
  14. use File::Spec::Functions qw(rel2abs catdir);
  15. use constant {
  16. USE_TOR_PROXY => 1, # true to use the Tor proxy to connect to factorDB (127.0.0.1:9050)
  17. };
  18. my $cache = CHI->new(driver => 'BerkeleyDB',
  19. root_dir => catdir(dirname(rel2abs($0)), 'cache'));
  20. my $mech = WWW::Mechanize::Cached->new(
  21. autocheck => 1,
  22. show_progress => 0,
  23. stack_depth => 10,
  24. cache => $cache,
  25. agent => "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0",
  26. );
  27. {
  28. state $accepted_encodings = HTTP::Message::decodable();
  29. $mech->default_header('Accept-Encoding' => $accepted_encodings);
  30. };
  31. {
  32. require LWP::ConnCache;
  33. my $cache = LWP::ConnCache->new;
  34. $cache->total_capacity(undef); # no limit
  35. $mech->conn_cache($cache);
  36. };
  37. if (USE_TOR_PROXY) {
  38. $mech->proxy(['http', 'https'], "socks://127.0.0.1:9050");
  39. }
  40. my $expr = $ARGV[0] || die "usage: perl $0 [NUMBER | EXPR]\n";
  41. $expr = join('', split(' ', $expr)); # remove any whitespace
  42. my $main_url = "http://factordb.com/api?query=" . uri_escape($expr);
  43. my $resp = $mech->get($main_url);
  44. if (not $resp->is_success) {
  45. $mech->invalidate_last_request;
  46. $resp = $mech->get($main_url);
  47. }
  48. if (not $resp->is_success) {
  49. $mech->invalidate_last_request;
  50. die "Failed to get factors...\n";
  51. }
  52. my $data = eval { from_json($resp->decoded_content) } // do {
  53. $mech->invalidate_last_request;
  54. die "Failed to get factors...\n";
  55. };
  56. if ($data->{status} =~ /^(?:C|CF|U|PRP)\z/i) {
  57. $mech->invalidate_last_request;
  58. }
  59. my @factor_exp = @{$data->{factors}};
  60. foreach my $pp (@factor_exp) {
  61. foreach my $k (1 .. $pp->[1]) {
  62. say $pp->[0];
  63. }
  64. }