webmention.pl 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #! /usr/bin/perl -w
  2. # Copyright (C) 2019 Alex Schroeder <alex@gnu.org>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. =head1 Webmention from one site to another
  17. If you link from page A on your site to page B on some other site, you can
  18. invoke this script with the command-line arguments A and B. In theory, this will
  19. create a link back from B to A, letting them and all their visitors know that
  20. you wrote something in response.
  21. =cut
  22. use Modern::Perl;
  23. use XML::LibXML;
  24. use LWP::UserAgent;
  25. use Data::Dumper;
  26. if (@ARGV != 2) {
  27. die "Usage: webmention FROM TO\n";
  28. }
  29. my $parser = XML::LibXML->new(recover => 2);
  30. my ($from, $to) = @ARGV;
  31. my $ua = LWP::UserAgent->new(agent => "Oddmuse Webmention Client/0.1");
  32. print "Getting $from\n";
  33. my $response = $ua->get($from);
  34. if (!$response->is_success) {
  35. die $response->status_line;
  36. }
  37. print "Parsing $from\n";
  38. my ($username, $homepage);
  39. my $dom = $parser->load_html(string => $response->decoded_content);
  40. my @nodes = $dom->findnodes('//*[@rel="author"]');
  41. if (@nodes) {
  42. my $node = shift @nodes;
  43. $username = $node->textContent;
  44. $homepage = $node->getAttribute('href');
  45. }
  46. print "Webmention from " . join(", ", $username, $homepage) . "\n"
  47. if $username or $homepage;
  48. print "Getting $to\n";
  49. $response = $ua->get($to);
  50. if (!$response->is_success) {
  51. die $response->status_line;
  52. }
  53. print "Parsing $to\n";
  54. $dom = $parser->load_html(string => $response->decoded_content);
  55. my $webmention = $dom->findvalue('//link[@rel="webmention"]/@href');
  56. if (!$webmention) {
  57. die "Webmention URL not found in $to\n";
  58. }
  59. print "Webmention URL is $webmention\n";
  60. $response = $ua->post($webmention, { source => $from, target => $to });
  61. my $message = $response->code . " " . $response->message . "\n";
  62. if ($response->is_success) {
  63. print $message;
  64. } else {
  65. die $message;
  66. }