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