1826063cb064d8a345464348d3054f0a2aa1d113
[scpubgit/System-Introspector-Report.git] / lib / System / Introspector / Report / Publish / MediaWiki / Connection.pm
1 package System::Introspector::Report::Publish::MediaWiki::Connection;
2 use Moo;
3 use MediaWiki::API;
4 use URI;
5 use aliased 'System::Introspector::Report::Publish::MediaWiki::Page';
6
7 has api             => (is => 'lazy');
8 has api_uri         => (is => 'ro', required => 1);
9 has username        => (is => 'ro', required => 1);
10 has password        => (is => 'ro', required => 1);
11 has allow_create    => (is => 'ro', default => sub { 0 });
12 has http_auth       => (is => 'ro');
13 has http_realm      => (is => 'ro');
14
15 my $_api_fail = sub {
16   my $api = shift;
17   die sprintf "MediaWiki Error %s: %s\n",
18     $api->{error}{code},
19     $api->{error}{details};
20 };
21
22 sub _build_api {
23   my ($self) = @_;
24   my $api_uri = URI->new($self->api_uri);
25   my $api = MediaWiki::API->new({ api_url => $self->api_uri });
26   my $passwd = $self->password;
27   if ($ENV{TEST_SI_MEDIAWIKI_GETPW}) {
28     system "stty -echo";
29     printf "MediaWiki password for '%s': ", $self->username;
30     $passwd = <STDIN>;
31     chomp $passwd;
32     system "stty echo";
33     print "\n";
34   }
35   $api->{ua}->credentials(
36     join(':', $api_uri->host, $api_uri->port),
37     $self->http_realm || 'Wiki',
38     $self->username,
39     $passwd,
40   ) if $self->http_auth;
41   $api->login({
42     lgname      => $self->username,
43     lgpassword  => $passwd,
44   }) or $api->$_api_fail;
45   return $api;
46 }
47
48 sub get {
49   my ($self, $page_name) = @_;
50   my $page = $self->api->get_page({ title => $page_name })
51     or $self->api->$_api_fail;
52   if (defined $page->{missing}) {
53     die "MediaWiki page '$page_name' does not exist\n"
54       unless $self->allow_create;
55     return Page->new(
56       name      => $page_name,
57       content   => '',
58     );
59   }
60   return Page->new(
61     name        => $page_name,
62     timestamp   => $page->{timestamp},
63     content     => $page->{'*'} || '',
64   );
65 }
66
67 sub put {
68   my ($self, $page) = @_;
69   $self->api->edit({
70     action      => 'edit',
71     title       => $page->name,
72     text        => $page->content,
73     $page->has_timestamp
74       ? (basetimestamp => $page->timestamp)
75       : (),
76   }) or $self->api->$_api_fail;
77   return 1;
78 }
79
80 1;