24c5599635e0a19ca13cbe6dde820368cae7a9ee
[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 </style>
32
33 <script>
34 document.addEventListener('DOMContentLoaded', () => {
35         var wpinput = document.getElementById('wptitle');
36         var wpbutton = wpinput.parentNode.appendChild(document.createElement('button'));
37         wpbutton.type = 'button';
38         wpbutton.append('Copy');
39         wpbutton.onclick = () => {
40                 let wptitle = wpinput.value || document.getElementById('form').value;
41                 let wppage = 'https://en.wikipedia.org/w/api.php?action=parse&format=json&origin=*&prop=text&page='+wptitle;
42                 fetch(wppage).then(res => res.json()).then(json => {
43                         if (json.error) throw `error returned: ${json.error.info}`;
44                         wpinput.value = json.parse.title;
45                         let imginput = document.getElementById('source');
46                         if (imginput.value) return;
47                         let wpimages = json.parse.text['*'].match(/<img\s[^>]+/g);
48                         imginput.value = wpimages[0].match(/\ssrc="([^"]+)"/)[1]
49                                 .replace(/^(?=\/\/)/, 'https:')
50                                 .replace(/\/thumb(\/.+)\/[^\/]+$/, '$1');
51                 }).catch(error => alert(error));
52                 return false;
53         };
54 });
55 </script>
56 EOT
57 });
58
59 use List::Util qw( pairs pairkeys );
60
61 my $db = eval {
62         my @dbinfo = (
63                 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
64         ) or die "database not configured\n";
65         require DBIx::Simple;
66         DBIx::Simple->new(@dbinfo[0..2], {
67                 RaiseError => 1,
68                 pg_enable_utf8 => 1,
69         });
70 } or Abort('Database error', 501, $@);
71
72 my @wordcols = (
73         form    => 'Translation',
74         wptitle => 'Wikipedia',
75         ref     => 'Reference',
76         cat     => 'Category',
77         lang    => 'Language',
78         source  => 'Image URL',
79         thumb   => 'Convert options',
80 );
81 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
82
83 my $row;
84 if (exists $get{copy}) {
85         $row = {%fields{ qw(lang cat) }};
86 }
87 elsif ($ENV{REQUEST_METHOD} eq 'POST') {
88         $row = {%post{ pairkeys @wordcols }};
89         $_ = length ? $_ : undef for values %{$row};
90         eval {
91                 my %res = (returning => '*');
92                 my $query = $find ? $db->update(word => $row, $find, \%res) :
93                         $db->insert(word => $row, \%res);
94                 $row = $query->hash;
95         } or Alert("Entry could not be saved", $@);
96
97         my $imgpath = "data/word/org/$row->{id}.jpg";
98         if (my $download = $row->{source} and !-e $imgpath) {
99                 require LWP::UserAgent;
100                 my $ua = LWP::UserAgent->new;
101                 $ua->agent('/');
102                 my $status = $ua->mirror($download, $imgpath);
103                 $status->is_success or Alert([
104                         "Source image not found",
105                         "Download from <q>$download</q> failed: ".$status->status_line,
106                 ]);
107         }
108
109         my $thumbpath = "data/word/eng/$row->{form}.jpg";
110         if (-e $imgpath) {
111                 my @cmds = @{ $row->{thumb} // [] };
112                 unshift @cmds, -gravity => @cmds ? 'northwest' : 'center';
113                 unshift @cmds, 'convert';
114                 push @cmds, -resize => '300x200^', -extent => '300x200';
115                 push @cmds, '-strip', -quality => '60%', -interlace => 'plane';
116                 push @cmds, $imgpath, $thumbpath;
117                 my $status = system @cmds;
118                 $status == 0 or Alert([
119                         "Thumbnail image not generated",
120                         "Failed to convert source image, error code ".($status >> 8),
121                 ], "@cmds");
122         }
123 }
124 elsif ($find) {
125         $row = $db->select(word => '*', $find)->hash
126                 or Abort("Word not found", 404);
127 }
128
129 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
130 :>
131 <h1>Words <:= $title :></h1>
132
133 <form action="?" method="post">
134 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
135 <dl>
136 <:
137
138 for my $col (pairs @wordcols) {
139         my $val = $row->{$col->key} // '';
140         $val = '{'.join(',', map {s/,/\\,/gr} @{$val}).'}' if ref $val eq 'ARRAY';
141         printf '<dt><label for="%s">%s</label></dt>'
142                 . '<dd><input id="%1$s" name="%1$s" value="%s" />',
143                 $col->key, $col->value, Entity($val);
144         -e and printf ' <img src="/%s" alt="%s" />', $_, $row->{form} for
145                 $col->key eq 'source' ? "data/word/org/$row->{id}.jpg" :
146                 $col->key eq 'thumb'  ? "data/word/eng/$row->{form}.jpg" :
147                 ();
148         say '</dd>';
149 }
150 :>
151 </dl>
152 <p>
153         <input type="submit" value="Save" />
154         <input type="submit" value="New" formaction="/writer?copy=cat" />
155 </p>
156 </form>