chiark / gitweb /
Can actually update the database
[ypp-sc-tools.web-live.git] / pctb / commod-email-processor
1 #!/usr/bin/perl -w
2 #
3 # This script is invoked to process an email sent by the
4 # commod-update-receiver Perl script.
5
6 # This is part of ypp-sc-tools, a set of third-party tools for assisting
7 # players of Yohoho Puzzle Pirates.
8 #
9 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
10 #
11 # This program is free software: you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation, either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
25 # are used without permission.  This program is not endorsed or
26 # sponsored by Three Rings.
27
28 # Emails are:
29 #  multipart/mixed, containing
30 #   text/plain; name="metadata"; charset="utf-8"
31 #   Content-Disposition: inline; filename="metadata"
32 #     ocean\t<ocean>            canonical mixed case
33 #     island\t<island>          canonical mixed case
34 #     timestamp\t<digits>       time_t (non-leap secs since start of 1970 UTC)
35 #     clientname\t<cname>       may contain spaces
36 #     clientversion\t<cversion> may contain spaces
37 #     clientfixes\t<cfixes>     space-delimited list
38 #     clientspec\t<cspec>       <cname>\t<cversion>\t<cfixes>
39 #     servername\t<sname>       may contain spaces
40 #     serverversion\t<sversion> may contain spaces
41 #     serverfixes\t<sfixes>     space-delimited list
42 #     serverspec\t<sspec>       <sname>\t<serverversion>\t<serverfixes>
43 #   application/octet-stream; name="deduped.tsv.gz"
44 #   Content-Disposition: attachment; filename="deduped.tsv.gz"
45 #     <base64>
46
47 use strict (qw(vars));
48
49 use POSIX;
50 use MIME::Parser;
51
52 use Commods;
53 use CommodsDatabase;
54
55 setlocale(LC_CTYPE, "en_GB.UTF-8");
56 my $parser= new MIME::Parser;
57 our $entity;
58
59 $|=1;
60
61 sub find_part ($$$) {
62     my ($filename, $type, $accepter) = @_;
63     foreach my $part ($entity->parts()) {
64         my $h= $part->head();
65         next unless $h->recommended_filename() eq $filename;
66         next unless $h->mime_type()            eq $type;
67         next unless $part->effective_type()    eq $type;
68         next if defined $accepter and !&$accepter($h);
69         return $part;
70     }
71     die "no appropriate part with name $filename and type $type";
72 }
73
74 sub bad_data_fail ($) { die $_[0]; }
75
76 sub main () {
77     $parser->extract_nested_messages(0);
78     $parser->ignore_errors(0);
79
80     $entity= $parser->parse(\*STDIN);
81     my $eff_type= $entity->effective_type();
82     die "effective type $eff_type\n" unless $eff_type eq 'multipart/mixed';
83
84     my $mdpart= find_part('metadata', 'text/plain', sub {
85         my $charset= $_[0]->mime_attr('content-type.charset');
86         return 1 if grep { $_ eq $charset } qw(utf-8 us-ascii);
87     });
88
89     my $mdh= $mdpart->open('r') or die "failed to open metadata $!\n";
90     my %md;
91     while (defined($_= $mdh->getline())) {
92         m/^([a-z]+)\t(.*)$/ or next;
93         $md{$1}= $2;
94     }
95
96     foreach my $needed (qw(ocean island timestamp clientspec serverspec)) {
97         defined $md{$needed} or die "missing metadata $needed\n";
98     }
99
100     my $mid= $entity->head()->get('message-id');
101     defined $mid or die "missing Message-ID\n";
102     chomp($mid);
103     $mid !~ m/[^ -~]/ or die "Message-ID has strange character(s)\n";
104
105     my $tsvpart= find_part('deduped.tsv.gz', 'application/octet-stream',
106                            undef);
107     my $tsv= pipethrough_prep();
108     $tsvpart->bodyhandle()->print($tsv);
109     my $pt= pipethrough_run_along($tsv,undef, 'gunzip','gunzip');
110
111     db_setocean($md{'ocean'});
112     my $dbfn= db_filename();
113     (stat $dbfn) or die "stat database $dbfn failed $!\n";
114     db_connect();
115
116     my ($islandid) = $dbh->selectrow_array(
117               "SELECT islands.islandid
118                       FROM islands
119                       WHERE islandname == ?;
120               ", {}, $md{'island'});
121
122     die "unknown island\n" unless defined $islandid;
123
124     db_doall("DELETE FROM uploads WHERE islandid == $islandid;
125               DELETE FROM buy     WHERE islandid == $islandid;
126               DELETE FROM sell    WHERE islandid == $islandid;
127              ");
128     
129     $dbh->do("INSERT INTO uploads
130                      (islandid, message,
131                       timestamp, clientspec, serverspec)
132                      VALUES (?,?,?,?,?);
133              ", {},
134              $islandid, $mid,
135              map { $md{$_} } (qw(timestamp clientspec serverspec)));
136
137     my $sth_stall= $dbh->prepare(
138                 "INSERT OR IGNORE
139                         INTO stalls
140                         (islandid, stallname) VALUES (?, ?)
141                 ");
142
143     my @v;
144
145     my %sub_bs;
146     foreach my $bs (qw(buy sell)) {
147         my $sth= $dbh->prepare(
148                "INSERT INTO $bs
149                        (commodid, stallid, islandid, price, qty)
150                        VALUES (
151                          (SELECT commodid FROM commods WHERE commodname = ?),
152                          (SELECT stallid  FROM stalls  WHERE stallname =  ?),
153                          ?, ?, ?
154                        )
155                ");
156         $sub_bs{$bs}= sub {
157             my ($priceix) = @_;
158             my $price= $v[$priceix];  return if !length $price;
159             my $qty= $v[$priceix+1];
160             $qty++ if $qty =~ s/^\>//;
161             $sth->execute(@v[0..1],$islandid,$price,$qty);
162         }           
163     }
164
165     while (<$pt>) {
166         @v= check_tsv_line($_, \&bad_data_fail);
167
168         $sth_stall->execute($islandid, $v[1]);
169
170         &{$sub_bs{'buy'}}(2);
171         &{$sub_bs{'sell'}}(4);
172
173 #       print ".";
174     }
175
176     pipethrough_run_finish($pt, 'gunzip <$deduped_tsv.gz');
177
178     print "\n";
179     $dbh->commit();
180
181     # select * from ((buy natural join commods) natural join stalls) natural join islands;
182     # select * from ((sell natural join commods) natural join stalls) natural join islands;
183
184 }
185
186 my $ok= eval {
187     main();
188     1;
189 };
190 my $err= $@;
191
192 $parser->filer->purge();
193
194 if (!$ok) {
195     print STDERR "PROCESSING FAILED\n $@\n";
196     exit 1;
197 }