288891a5030688489ae47bcff3c1a7347f0d0411
[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 wppage = 'https://en.wikipedia.org/w/api.php?action=parse&format=json&origin=*&prop=text&page='+wptitle;
69                 fetch(wppage).then(res => res.json()).then(json => {
70                         if (json.error) throw `error returned: ${json.error.info}`;
71                         wpinput.value = json.parse.title;
72                         let imginput = document.getElementById('source');
73                         if (imginput.value) return;
74                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+>/g);
75                         let wpselect = wpinput.parentNode.appendChild(document.createElement('ul'));
76                         wpselect.className = 'popup';
77                         wpimages.forEach(img => {
78                                 let selectitem = wpselect.appendChild(document.createElement('li'));
79                                 selectitem.insertAdjacentHTML('beforeend', img);
80                                 selectitem.onclick = e => {
81                                         let imgsrc = e.target.src
82                                                 .replace(/^(?=\/\/)/, 'https:')
83                                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
84                                         imginput.value = imgsrc;
85                                         wpselect.remove();
86                                         return false;
87                                 };
88                         });
89                 }).catch(error => alert(error));
90                 return false;
91         };
92 });
93 </script>
94 EOT
95 });
96
97 use List::Util qw( pairs pairkeys );
98
99 my $db = eval {
100         my @dbinfo = (
101                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
102         ) or die "database not configured\n";
103         require DBIx::Simple;
104         DBIx::Simple->new(@dbinfo[0..2], {
105                 RaiseError => 1,
106                 pg_enable_utf8 => 1,
107         });
108 } or Abort('Database error', 501, $@);
109
110 my @wordcols = (
111         form    => 'Translation',
112         wptitle => 'Wikipedia',
113         ref     => 'Reference',
114         cat     => 'Category',
115         lang    => 'Language',
116         source  => 'Image URL',
117         thumb   => 'Convert options',
118 );
119 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
120
121 my $row;
122 if ($find) {
123         $row = $db->select(word => '*', $find)->hash
124                 or Abort("Word not found", 404);
125 }
126
127 if (exists $get{copy}) {
128         $row = {%{$row}{ qw(lang cat) }};
129 }
130 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
131         my $replace = $row;
132         $row = {%post{ pairkeys @wordcols }};
133         $_ = length ? $_ : undef for values %{$row};
134
135         eval {
136                 my %res = (returning => '*');
137                 my $query = $find ? $db->update(word => $row, $find, \%res) :
138                         $db->insert(word => $row, \%res);
139                 $row = $query->hash;
140         } or do {
141                 Alert("Entry could not be saved", $@);
142                 next;
143         };
144
145         my $imgpath = "data/word/org/$row->{id}.jpg";
146         if (($row->{source} // '') ne ($replace->{source} // '')) {
147                 # copy changed remote url to local file
148                 unlink $imgpath if -e $imgpath;
149                 if (my $download = $row->{source}) {
150                         require LWP::UserAgent;
151                         my $ua = LWP::UserAgent->new;
152                         $ua->agent('/');
153                         my $status = $ua->mirror($download, $imgpath);
154                         $status->is_success or Alert([
155                                 "Source image not found",
156                                 "Download from <q>$download</q> failed: ".$status->status_line,
157                         ]);
158                 }
159         }
160         elsif ($row->{thumb} ~~ $replace->{thumb}) {
161                 # image and conversion unaltered
162                 $imgpath = undef;
163         }
164
165         my $thumbpath = "data/word/eng/$row->{form}.jpg";
166         if ($imgpath) {
167                 if (-e $imgpath) {
168                         my @cmds = @{ $row->{thumb} // [] };
169                         @cmds = (
170                                 'convert',
171                                 -delete => '1--1', -background => 'white',
172                                 -gravity => @cmds ? 'northwest' : 'center',
173                                 @cmds,
174                                 -resize => '300x200^', -extent => '300x200',
175                                 '-strip', -quality => '60%', -interlace => 'plane',
176                                 $imgpath => $thumbpath
177                         );
178                         my $status = system @cmds;
179                         $status == 0 or Alert([
180                                 "Thumbnail image not generated",
181                                 "Failed to convert source image, error code ".($status >> 8),
182                         ], "@cmds");
183                 }
184                 else {
185                         unlink $thumbpath;
186                 }
187         }
188 }}
189 else {
190         $row->{$_} = $get{$_} for keys %get;
191 }
192
193 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
194 :>
195 <h1>Words <:= $title :></h1>
196
197 <form action="?" method="post">
198 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
199 <dl>
200 <:
201
202 for my $col (pairs @wordcols) {
203         my $val = $row->{$col->key} // '';
204         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
205         printf '<dt><label for="%s">%s</label></dt>'
206                 . '<dd><input id="%1$s" name="%1$s" value="%s" />',
207                 $col->key, $col->value, Entity($val);
208         -e and printf ' <img src="/%s" alt="%s" />', $_, $row->{form} for
209                 $col->key eq 'source' ? "data/word/org/$row->{id}.jpg" :
210                 $col->key eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
211                 ();
212         say '</dd>';
213 }
214 :>
215 </dl>
216 <p>
217         <input type="submit" value="Save" />
218         <input type="submit" value="New" formaction="/writer?copy=cat" />
219 </p>
220 </form>
221
222 <:
223 $row->{id} or exit;
224 :>
225 <section>
226 <h2>Hierarchy</h2>
227
228 <:
229 say '<ul>';
230 my $parents = $db->select(word => '*', {id => $row->{cat}});
231 while (my $ref = $parents->hash) {
232         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
233 }
234 say "<li><strong>$row->{form}</strong></li>";
235 my $children = $db->select(word => '*', {cat => $row->{id}});
236 while (my $ref = $children->hash) {
237         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
238 }
239 :>
240 <li><form action="/writer">
241         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
242         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
243         <input type="submit" value="Add" />
244 </form></li>
245 </ul>
246 </section>