word edit: language input as wikipedia domain
[sheet.git] / writer.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'words cheat sheet admin',
5         version => '1.0',
6         nocache => 1,
7         raw => <<'EOT',
8 <style>
9 dd > input {
10         width: 32em;
11         max-width: 100%;
12         padding: 1ex;
13         font-family: monospace;
14 }
15 dl > dt, dl > dd {
16         float: none;
17         display: inline-block;
18         box-sizing: border-box;
19         width: 50%;
20         margin: 0;
21         line-height: 4ex;
22         vertical-align: text-top;
23 }
24 dd > img {
25         max-width: 300px;
26         display: block;
27 }
28 dd input ~ button {
29         margin-left: -5em;
30 }
31
32 ul.popup {
33         display: flex;
34         flex-wrap: wrap;
35         align-items: end;
36         position: fixed;
37         left: 0;
38         top: 0;
39         margin: auto;
40         max-height: 90%;
41         max-width: 90%;
42         overflow: auto;
43         background: rgba(0, 0, 0, .8);
44         border: 1px solid #CCC;
45 }
46
47 section {
48         position: absolute;
49         top: 7ex;
50         right: 1em;
51 }
52 section > ul {
53         margin-top: 1ex;
54 }
55 section > ul strong, section form {
56         line-height: 2;
57 }
58 </style>
59
60 <script>
61 document.addEventListener('DOMContentLoaded', () => {
62         var wpinput = document.getElementById('wptitle');
63         var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
64         wpbutton.type = 'button';
65         wpbutton.append('Copy');
66         wpbutton.onclick = () => {
67                 let wptitle = wpinput.value || document.getElementById('form').value;
68                 let wplang = document.getElementById('lang').value.substr(0, 2); // crude iso-639-3→2
69                 let wpapi = `https://${wplang}.wikipedia.org/w/api.php`;
70                 let wppage = wpapi+'?action=parse&format=json&origin=*&prop=text&page='+wptitle;
71                 fetch(wppage).then(res => res.json()).then(json => {
72                         if (json.error) throw `error returned: ${json.error.info}`;
73                         wpinput.value = json.parse.title;
74                         let imginput = document.getElementById('source');
75                         if (imginput.value) return;
76                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
77                         let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
78                         wpselect.className = 'popup';
79                         wpimages.forEach(img => {
80                                 let selectitem = wpselect.appendChild(document.createElement('li'));
81                                 selectitem.insertAdjacentHTML('beforeend', img);
82                                 selectitem.onclick = e => {
83                                         let imgsrc = e.target.src
84                                                 .replace(/^(?=\/\/)/, 'https:')
85                                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
86                                         imginput.value = imgsrc;
87                                         wpselect.remove();
88                                         return false;
89                                 };
90                         });
91                 }).catch(error => alert(error));
92                 return false;
93         };
94 });
95 </script>
96 EOT
97 });
98
99 use List::Util qw( pairs pairkeys );
100
101 my $db = eval {
102         my @dbinfo = (
103                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
104         ) or die "database not configured\n";
105         require DBIx::Simple;
106         DBIx::Simple->new(@dbinfo[0..2], {
107                 RaiseError => 1,
108                 pg_enable_utf8 => 1,
109         });
110 } or Abort('Database error', 501, $@);
111
112 my @wordcols = (
113         lang    => 'Language',
114         cat     => 'Category',
115         form    => 'Translation',
116         alt     => 'Synonyms',
117         wptitle => 'Wikipedia',
118         source  => 'Image URL',
119         thumb   => 'Convert options',
120         prio    => 'Level',
121         ref     => 'Reference',
122 );
123 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
124
125 my $row;
126 if ($find) {
127         $row = $db->select(word => '*', $find)->hash
128                 or Abort("Word not found", 404);
129 }
130
131 if (exists $get{copy}) {
132         $row = {%{$row}{ qw(prio lang cat) }};
133 }
134 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
135         my $replace = $row;
136         $row = {%post{ pairkeys @wordcols }};
137         $_ = length ? $_ : undef for values %{$row};
138
139         eval {
140                 my %res = (returning => '*');
141                 my $query = $find ? $db->update(word => $row, $find, \%res) :
142                         $db->insert(word => $row, \%res);
143                 $row = $query->hash;
144         } or do {
145                 Alert("Entry could not be saved", $@);
146                 next;
147         };
148
149         my $imgpath = "data/word/org/$row->{id}.jpg";
150         if (($row->{source} // '') ne ($replace->{source} // '')) {
151                 # copy changed remote url to local file
152                 unlink $imgpath if -e $imgpath;
153                 if (my $download = $row->{source}) {
154                         require LWP::UserAgent;
155                         my $ua = LWP::UserAgent->new;
156                         $ua->agent('/');
157                         my $status = $ua->mirror($download, $imgpath);
158                         $status->is_success or Alert([
159                                 "Source image not found",
160                                 "Download from <q>$download</q> failed: ".$status->status_line,
161                         ]);
162                 }
163         }
164         elsif ($row->{thumb} ~~ $replace->{thumb}) {
165                 # image and conversion unaltered
166                 $imgpath = undef;
167         }
168
169         my $thumbpath = "data/word/eng/$row->{form}.jpg";
170         if ($imgpath) {
171                 if (-e $imgpath) {
172                         my @cmds = @{ $row->{thumb} // [] };
173                         @cmds = (
174                                 'convert',
175                                 -delete => '1--1', -background => 'white',
176                                 -gravity => @cmds ? 'northwest' : 'center',
177                                 @cmds,
178                                 -resize => '300x200^', -extent => '300x200',
179                                 '-strip', -quality => '60%', -interlace => 'plane',
180                                 $imgpath => $thumbpath
181                         );
182                         my $status = system @cmds;
183                         $status == 0 or Alert([
184                                 "Thumbnail image not generated",
185                                 "Failed to convert source image, error code ".($status >> 8),
186                         ], "@cmds");
187                 }
188                 else {
189                         unlink $thumbpath;
190                 }
191         }
192 }}
193 else {
194         $row->{prio} //= 1;
195         $row->{$_} = $get{$_} for keys %get;
196 }
197
198 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
199 :>
200 <h1>Words <:= $title :></h1>
201
202 <form action="?" method="post">
203 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
204 <dl>
205 <:
206
207 for my $col (pairs @wordcols) {
208         my $val = $row->{$col->key} // '';
209         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
210         printf '<dt><label for="%s">%s</label></dt>'
211                 . '<dd><input id="%1$s" name="%1$s" value="%s" />',
212                 $col->key, $col->value, Entity($val);
213         -e and printf ' <img src="/%s" alt="%s" />', $_, $row->{form} for
214                 $col->key eq 'source' ? "data/word/org/$row->{id}.jpg" :
215                 $col->key eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
216                 ();
217         say '</dd>';
218 }
219 :>
220 </dl>
221 <p>
222         <input type="submit" value="Save" />
223         <input type="submit" value="New" formaction="/writer?copy=cat" />
224 </p>
225 </form>
226
227 <:
228 $row->{id} or exit;
229 :>
230 <section>
231 <h2>Hierarchy</h2>
232
233 <:
234 say '<ul>';
235 my $parents = $db->select(word => '*', {id => $row->{cat}});
236 while (my $ref = $parents->hash) {
237         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
238 }
239 say "<li><strong>$row->{form}</strong></li>";
240 my $children = $db->select(word => '*', {cat => $row->{id}});
241 while (my $ref = $children->hash) {
242         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
243 }
244 :>
245 <li><form action="/writer">
246         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
247         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
248         <input type="submit" value="Add" />
249 </form></li>
250 </ul>
251 </section>