Phoebe/Wikipedia.pm untested

filter: Statementstmt 0.0% 0 / 232 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 19 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 345 CC 28 SCAR 42.4
CC
28
Cov
0%
wikipedia
132.0
wikipedia_table
90.0
wikipedia_process
90.0
CRAP 69.2
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =head1 NAME
18  
19 App::Phoebe::Wikipedia - act as Wikipedia proxy from Phoebe
20  
21 =head1 DESCRIPTION
22  
23 This extension turns one of your hosts into a Wikipedia proxy.
24  
25 In your F<config> file, you need to specify which of your hosts it is:
26  
27 package App::Phoebe::Wikipedia;
28 our $host = "vault.transjovian.org";
29 use App::Phoebe::Wikipedia;
30  
31 You can also use L<App::Phoebe::Web> in which case web requests will get
32 redirected to the actual Wikipedia.
33  
34 =cut
35  
36 package App::Phoebe::Wikipedia;
37 use App::Phoebe qw($log @extensions $full_url_regex success result gemini_link);
38 use URI::Escape;
39 use Modern::Perl;
40 use MediaWiki::API;
41 use Text::SpanningTable;
42 use List::Util qw(sum min max);
43 use Encode;
44  
45 our $host;
46  
47 # Wikipedia
48  
49 push(@extensions, \&wikipedia);
50  
51 my $link_regex = "([-,.()'%&!?;<> _1-9A-Za-z\x{0080}-\x{fffd}]|[-,.()'%&!?;<> _0-9A-Za-z\x{0080}-\x{fffd}][-,.()'#%&!?;<> _0-9A-Za-z\x{0080}-\x{fffd}]+)"; # disallow "0" and must match HTML and plain text (ie. > and &gt;)
52  
53 sub wikipedia {
54 my $stream = shift;
55 my $url = shift;
56 my $headers = shift;
57 my $port = App::Phoebe::port($stream);
58 if ($url =~ m!^gemini://$host(?::$port)?/search/([a-z]+)/([^?;]+)!) {
59 wikipedia_serve_search($stream, $1, decode_utf8(uri_unescape($2)));
60 } elsif ($url =~ m!^gemini://$host(?::$port)?/text/([a-z]+)/([^?;]+)!) {
61 wikipedia_serve_text($stream, $1, decode_utf8(uri_unescape($2)));
62 } elsif ($url =~ m!^gemini://$host(?::$port)?/full/([a-z]+)/([^?;]+)!) {
63 wikipedia_serve_full($stream, $1, decode_utf8(uri_unescape($2)));
64 } elsif ($url =~ m!^gemini://$host(?::$port)?/raw/([a-z]+)/([^?;]+)!) {
65 wikipedia_serve_raw($stream, $1, decode_utf8(uri_unescape($2)));
66 } elsif ($url =~ m!^gemini://$host(?::$port)?/?$!) {
67 $log->info("Asking for a language");
68 result($stream, "10", "Search in which language? (ar, cn, en, fr, ru, es, etc.)");
69 } elsif ($url =~ m!^gemini://$host(?::$port)?/?\?([a-z]+)$!) {
70 $log->info("Redirecting to ask for a term");
71 my $lang = $1;
72 result($stream, "30", "gemini://$host:$port/$lang");
73 } elsif ($url =~ m!^gemini://$host(?::$port)?/([a-z]+)$!) {
74 $log->info("Asking for a term");
75 my $lang = $1;
76 result($stream, "10", "Search term");
77 } elsif ($url =~ m!^gemini://$host(?::$port)?/([a-z]+)\?([^?;]+)!) {
78 $log->info("Redirecting to text");
79 my $lang = $1;
80 my $term = $2;
81 result($stream, "30", "gemini://$host:$port/search/$lang/$term");
82 } elsif ($url =~ m!^gemini://$host(?::$port)?/robots\.txt$!) {
83 $log->info("Serving robots.txt");
84 success($stream, "text/plain");
85 $stream->write("User-agent: *\n");
86 $stream->write("Disallow: /\n");
87 } elsif (my ($lang, $term) = $url =~ m!^GET /(?:search/|text/|full/)?(?:([a-z]+)/)?(.*) HTTP/1\.[01]$!
88 and $headers->{host} and $headers->{host} =~ m!^$host(?::$port)?$!) {
89 $lang ||= "www";
90 my $url = "https://$lang.wikipedia.org/wiki/$term";
91 $log->info("Redirecting to $url");
92 $stream->write("HTTP/1.1 301 Back to Wikipedia!\r\n");
93 $stream->write("Location: $url\r\n");
94 $stream->write("Content-Type: text/plain\r\n");
95 $stream->write("\r\n");
96 $stream->write("See $url\n");
97 } else {
98 return 0;
99 }
100 return 1;
101 }
102  
103 sub wikipedia_serve_search {
104 my $stream = shift;
105 my $lang = shift;
106 my $term = shift;
107 $log->info("Searching $lang/$term");
108 my $mw = MediaWiki::API->new();
109 $mw->{config}->{api_url} = "https://$lang.wikipedia.org/w/api.php";
110 my $articles = $mw->list({
111 action => 'query',
112 list => 'prefixsearch',
113 pssearch => $term, });
114 if (not $articles) {
115 result($stream, "43", "Wikipedia says $mw->{error}->{code}: $mw->{error}->{details}");
116 $stream->close_gracefully();
117 return;
118 }
119 result($stream, "20", "text/gemini;lang=$lang");
120 $stream->write("# Searching for " . encode_utf8(uri_unescape($term)) . "\n");
121 foreach (@$articles) {
122 wikipedia_print_link($stream, $lang, $_->{title}, 'text', $_->{title});
123 }
124 $stream->write("\n\n");
125 $stream->write("=> https://$lang.wikipedia.org/wiki/" . uri_escape_utf8($term) . " Source\n");
126 }
127  
128 sub wikipedia_serve_raw {
129 my $stream = shift;
130 my $lang = shift;
131 my $term = shift;
132 $log->info("Wikipedia getting $lang/$term");
133 my $mw = MediaWiki::API->new();
134 $mw->{config}->{api_url} = "https://$lang.wikipedia.org/w/api.php";
135 my $result = $mw->api({
136 action => 'parse',
137 prop => 'wikitext',
138 formatversion => '2',
139 page => $term, });
140 result($stream, "20", "text/plain");
141 $stream->write(encode_utf8 $result->{parse}->{wikitext});
142 }
143  
144 sub wikipedia_print_link {
145 my $stream = shift;
146 my $lang = shift;
147 my $term = shift;
148 my $type = shift||"text";
149 my $title = shift||$term;
150 $stream->write("=> /$type/$lang/" . uri_escape_utf8($term) . " " . encode_utf8($title) . "\n");
151 }
152  
153 sub wikipedia_serve_text {
154 my $stream = shift;
155 my $lang = shift;
156 my $term = shift;
157 $log->info("Wikipedia getting $lang/$term");
158 my $mw = MediaWiki::API->new();
159 $mw->{config}->{api_url} = "https://$lang.wikipedia.org/w/api.php";
160 my $result = $mw->api({
161 action => 'parse',
162 prop => 'wikitext',
163 formatversion => '2',
164 page => $term, });
165 result($stream, "20", "text/gemini;lang=$lang");
166 my $title = $result->{parse}->{title};
167 my $text = wikipedia_extract($stream, $lang, $result->{parse}->{wikitext});
168 $stream->write(encode_utf8 "# $title\n");
169 $stream->write(encode_utf8 "$text\n\n");
170 wikipedia_print_link($stream, $lang, $term, 'full', "Full text");
171 wikipedia_print_link($stream, $lang, $term, 'raw', "Raw text");
172 $stream->write("=> https://$lang.wikipedia.org/wiki/" . uri_escape_utf8($term) . " Source\n");
173 }
174  
175 sub wikipedia_extract {
176 my $stream = shift;
177 my $lang = shift;
178 my $text = shift;
179 my @sections = split(/\n+==.*==\n+/, $text);
180 return wikipedia_text($stream, $lang, $sections[0]);
181 }
182  
183 sub wikipedia_text {
184 my $stream = shift; # only used to pass to gemini_link for the port
185 my $lang = shift;
186 my $text = shift;
187 # escape some stuff
188 my $ref = 0;
189 my @escaped;
190 # main articles and other templates
191 $text =~ s/^\{\{\s*main\s*\|(.+?)\}\}/push(@escaped, gemini_link($stream, "vault.transjovian.org", undef, "Main article: $1", "text\/$lang\/$1")); "\x03" . $ref++ . "\x04\n"/simeg;
192 # e.g. gemini://vault.transjovian.org/text/en/Zuihitsu
193 $text =~ s/\{\{\s*nihongo\s*\|(.+?)\|(.+?)\}\}/$1 ($2)/sig;
194 # strip citations
195 $text =~ s/\{\{\s*cite\s+[^{}]+\}\}//sig;
196 # handle quotes (now without the citations)
197 $text =~ s/\{\{\s*quote\s*\|(?:text=)?(.+?)\}\}/「$1」/sig;
198 # strip all other templates
199 do {} while $text =~ s/\{\{[^{}]+\}\}//g;
200 # strip remaining empty brackets
201 $text =~ s/\(\s*\)//g;
202 # handle tables
203 # $text =~ s/^(\{\|.+?\|\})\n?/push(@escaped, wikipedia_table($1)); "\x03" . $ref++ . "\x04"/mesg;
204 my @blocks = split(/\n\n+|\n(?=[*#=])|<br\s+\/>/, $text);
205 for my $block (@blocks) {
206 $block =~ s/\s+/ /g; # unwrap lines
207 $block =~ s/^\s+//; # trim
208 $block =~ s/\s+$//; # trim
209 $block = wikipedia_format($block);
210 }
211 $text = join("\n\n", @blocks);
212 # replace the preformatted blocks
213 $text =~ s/\x03(\d+)\x04/$escaped[$1]/g;
214 return $text;
215 }
216  
217 sub wikipedia_table {
218 my $text = shift;
219 my $caption = "";
220 my $data;
221 my @row;
222 $log->debug("Parsing table");
223 for (split(/\n/, $text)) {
224 if (/^\{\|.*/) { $log->debug("start of table"); }
225 elsif (/^\|\+\s*(.*)/) { $log->debug("caption"); $caption = $1 . "\n" }
226 elsif (/^\|-\s*/) { $log->debug("new row"); push(@$data, [@row]) if @row; @row = () }
227 elsif (/^!\s*(.*)/) { $log->debug("new header"); push(@row, split(/!!/, $1)) }
228 elsif (/^\|\s*(.*)/) { $log->debug("new cell"); push(@row, split(/\|\|/, $1)) }
229 elsif (/^\|\}/) { $log->debug("end of table"); push(@$data, [@row]) if @row }
230 }
231 my $width = wikipedia_process($data);
232 my $total = sum(@$width);
233 my @cols = map { min(30, max(8, int($_ * 120 / $total))) } @$width;
234 $log->debug("Column widths: @cols");
235 eval {
236 my $t = Text::SpanningTable->new(@cols);
237 $t->newlines(1);
238 for my $row (@$data) {
239 $t->row(@$row);
240 }
241 $text = $caption . $t->draw;
242 };
243 $log->debug("Table done $@");
244 return "```\n$text\n```\n";
245 }
246  
247 sub wikipedia_process {
248 my $data = shift;
249 my @width; # width of each column
250 my $r = 0;
251 for my $row (@$data) {
252 $log->debug("Processing row: @$row");
253 my $i = 0;
254 for my $cell (@$row) {
255 $i++, next unless $cell;
256 my ($attributes, $text);
257 if ($cell =~ /^((?:\s*[a-z-]+=(?:"[^"\n]+"|\w+))*)\s*\|\s*(.*)/) {
258 ($attributes, $text) = ($1, $2);
259 } else {
260 ($attributes, $text) = ("", $cell);
261 }
262 $text = wikipedia_format($text);
263 $i++, next unless $text;
264 $log->debug("Processing cell '$cell' to '$text'");
265 my $width = max(map { length } split/\n/, $text);
266 $log->warn("'$text' of '$cell' has no width") unless $width;
267 $width[$i] = $width if not $width[$i] or $width > $width[$i];
268 if ($attributes =~ /colspan=(?:"(\d+)"|(\d))/) {
269 $text = [$1||$2, $text];
270 # $width[$i] = 0;
271 } else {
272 $text = [1, $text];
273 }
274 if ($attributes =~ /rowspan="(\d+)"/) {
275 $log->debug("Rowspan $1 starting at (row $r, col $i)");
276 for my $n (1 .. $1 - 1) {
277 last if $r + $n > $#$data;
278 splice(@{$data->[$r + $n]}, $i, 0, "");
279 }
280 }
281 $cell = $text;
282 $i++;
283 }
284 $r++;
285 }
286 $log->debug("Max column width: @width");
287 return \@width;
288 }
289  
290 sub wikipedia_format {
291 my $text = shift;
292 $text =~ s/<(ref|gallery)(?:\s+[a-z-]+=(?:"[^"\n]+"|\w+))*>.*<\/\1>//g;
293 $text =~ s/<[a-z]+(?:\s+[a-z-]+=(?:"[^"\n]+"|\w+))*\s*\/?>//g;
294 $text =~ s/<\/[a-z]+>//g;
295 $text =~ s/(={1,6})(.+?)\1 */("#" x length($1)) . " $2\n\n"/ge;
296 $text =~ s/'''([^'\n]+)'''/**$1**/g;
297 $text =~ s/''([^'\n]+)''/*$1*/g;
298 $text =~ s/\[$full_url_regex ([^]]+)\]/$2/g;
299 $text =~ s/\[\[$link_regex\|([^\]|]+)\]\]/$2/g;
300 $text =~ s/\[\[$link_regex\]\]/$1/g;
301 $text =~ s/\[\[(?:File|Image|Category):.*?\]\] *//g;
302 $text =~ s/&nbsp;/ /g;
303 return $text;
304 }
305  
306 sub wikipedia_serve_full {
307 my $stream = shift;
308 my $lang = shift;
309 my $term = shift;
310 $log->info("Wikipedia serving full $lang/$term");
311 my $mw = MediaWiki::API->new();
312 $mw->{config}->{api_url} = "https://$lang.wikipedia.org/w/api.php";
313 my $result = $mw->api({
314 action => 'parse',
315 prop => 'wikitext',
316 formatversion => '2',
317 page => $term, });
318 result($stream, "20", "text/gemini;lang=$lang");
319 my $title = $result->{parse}->{title};
320 my $text = wikipedia_text($stream, $lang, $result->{parse}->{wikitext});
321 $stream->write(encode_utf8 "# $title\n");
322 $stream->write(encode_utf8 "$text\n\n");
323 wikipedia_print_link($stream, $lang, $term, 'text', "Short text");
324 $stream->write("=> https://$lang.wikipedia.org/wiki/" . uri_escape_utf8($term) . " Source\n");
325 }
326  
327 1;