4bec23e44d4a0cd995776b23113f6f49fcc43fff
[Biblio-RFID.git] / scripts / RFID-JSONP-server.pl
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 RFID-JSONP-server - simpliest possible JSONP server which provides local web interface to RFID readers
6
7 =head1 USAGE
8
9   ./scripts/RFID-JSONP-server.pl [--debug] [--listen=127.0.0.1:9000] [--reader=filter]
10
11 =cut
12
13 use strict;
14 use warnings;
15
16 use Data::Dump qw/dump/;
17
18 use JSON::XS;
19 use IO::Socket::INET;
20 use LWP::UserAgent;
21 use URI;
22 use URI::Escape;
23 use POSIX qw(strftime);
24 use Encode;
25
26 my $debug = 0;
27 my $listen = '127.0.0.1:9000';
28 $listen = ':9000';
29 my $reader;
30 my $koha_url = $ENV{KOHA_URL};
31 warn "$koha_url";
32 # internal URL so we can find local address of machine and vmware NAT
33 my $rfid_url = $ENV{RFID_URL};
34 my $sip2 = {
35         server   => $ENV{SIP2_SERVER}, # '10.60.0.11:6002' must be IP!
36         user     => $ENV{SIP2_USER},
37         password => $ENV{SIP2_PASSWORD},
38         loc      => $ENV{SIP2_LOC},
39 };
40 my $afi = {
41         secure   => 0xDA,
42         unsecure => 0xD7,
43 };
44
45 use Getopt::Long;
46
47 GetOptions(
48         'debug!'    => \$debug,
49         'listen=s', => \$listen,
50         'reader=s', => \$reader,
51 ) || die $!;
52
53 die "need KOHA_URL, eg. http://ffzg.koha-dev.rot13.org:8080" unless $koha_url;
54
55 our $rfid_sid_cache;
56
57 sub rfid_borrower {
58         my $hash = shift;
59         if ( my $json = $rfid_sid_cache->{ $hash->{sid} } ) {
60                 return $json;
61         }
62         my $ua = LWP::UserAgent->new;
63         my $url = URI->new( $koha_url . '/cgi-bin/koha/ffzg/rfid/borrower.pl');
64         $url->query_form(
65                   RFID_SID => $hash->{sid}
66                 , OIB => $hash->{OIB}
67                 , JMBAG => $hash->{JMBAG}
68         );
69         warn "GET ",$url->as_string;
70         my $response = $ua->get($url);
71         if ( $response->is_success ) {
72                 my $json = decode_json $response->decoded_content;
73                 $rfid_sid_cache->{ $hash->{sid} } = $json;
74                 return $json;
75         } else {
76                 warn "ERROR ", $response->status_line;
77         }
78 }
79
80
81 sub sip2_message {
82         my $send = shift;
83
84         my $sock = $sip2->{sock} || die "no sip2 socket";
85
86         local $/ = "\r";
87
88         $send .= "\r" unless $send =~ m/\r$/;
89         warn "SIP2 >>>> ",dump($send), "\n";
90         print $sock $send;
91         $sock->flush;
92         
93         my $expect = substr($send,0,2) | 0x01;
94
95         my $in = <$sock>;
96         $in =~ s/^\n//;
97         warn "SIP2 <<<< ",dump($in), "\n";
98
99         die "expected $expect" unless substr($in,0,2) != $expect;
100
101         $in =~ s/\r$//;
102
103         my $hash;
104         if ( $in =~ s/^([0-9\s]+)// ) {
105                 $hash->{fixed} = $1;
106         }
107         foreach ( split(/\|/, $in ) ) {
108                 my ( $f, $v ) = ( $1, $2 ) if m/([A-Z]{2})(.+)/;
109                 $hash->{$f} = decode('utf-8',$v);
110         }
111
112         warn "# sip2 hash response ",dump($hash);
113
114         return $hash;
115 }
116
117 if ( my $server = $sip2->{server} ) {
118         my $sock = $sip2->{sock} = IO::Socket::INET->new( $server ) || die "can't connect to $server: $!";
119         warn "SIP2 server ", $sock->peerhost, ":", $sock->peerport, "\n";
120
121         # login
122         if ( sip2_message("9300CN$sip2->{user}|CO$sip2->{password}|")->{fixed} !~ m/^941/ ) {
123                 die "SIP2 login failed";
124         }
125
126 }
127
128 use lib 'lib';
129 use Biblio::RFID::RFID501;
130 use Biblio::RFID::Reader;
131 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
132 $rfid->debug( $debug );
133
134 my $index_html;
135 {
136         local $/ = undef;
137         $index_html = <DATA>;
138         $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
139 }
140
141 my $server_url;
142
143 sub http_server {
144
145         my $server = IO::Socket::INET->new(
146                 Proto     => 'tcp',
147                 LocalAddr => $listen,
148                 Listen    => SOMAXCONN,
149                 Reuse     => 1
150         );
151                                                                   
152         die "can't setup server: $!" unless $server;
153
154         $server_url = 'http://' . $listen;
155         print "Server $0 ready at $server_url\n";
156
157         while (my $client = $server->accept()) {
158
159             eval { # don't die inside here!
160
161                 $client->autoflush(1);
162                 my $request = <$client>;
163
164                 warn "WEB << $request\n" if $debug;
165                 my $path;
166
167                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
168                         my $method = $1;
169                         my $param;
170                         if ( $method =~ s{\?(.+)}{} ) {
171                                 foreach my $p ( split(/[&;]/, $1) ) {
172                                         my ($n,$v) = split(/=/, $p, 2);
173                                         $param->{$n} = $v;
174                                 }
175                                 warn "WEB << param: ",dump( $param ) if $debug;
176                         }
177                         $path = $method;
178
179                         if ( $path eq '/' ) {
180                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
181                         } elsif ( $path =~ m{^/(examples/.+)} ) {
182                                 $path = $1; # FIXME prefix with dir for installation
183                                 my $size = -s $path;
184                                 warn "static $path $size bytes\n";
185                                 my $content_type = 'text/plain';
186                                 $content_type = 'application/javascript' if $path =~ /\.js$/;
187                                 $content_type = 'text/html' if $path =~ /\.html$/;
188                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
189                                 {
190                                         local $/ = undef;
191                                         open(my $fh, '<', $path) || die "can't open $path: $!";
192                                         while(<$fh>) {
193                                                 print $client $_;
194                                         }
195                                         close($fh);
196                                 }
197                         } elsif ( $method =~ m{/scan(/only/(.+))?} ) {
198                                 my $only = $2;
199                                 my @tags = $rfid->tags( reader => sub {
200                                         my $reader = shift;
201                                         return 1 unless $only;
202                                         if ( ref($reader) =~ m/$only/i ) {
203                                                 return 1;
204                                         }
205                                         return 0;
206                                 });
207                                 my $json = { time => time() };
208                                 foreach my $tag ( @tags ) {
209                                         my $hash = $rfid->to_hash( $tag );
210                                         $hash->{sid}  = $tag;
211                                         $hash->{reader} = $rfid->from_reader( $tag );
212                                         if ( $hash->{tag_type} eq 'SmartX' ) {
213                                                 my $borrower = rfid_borrower $hash;
214                                                 if ( exists $borrower->{error} ) {
215                                                         warn "ERROR ", dump($borrower);
216                                                 } else {
217                                                         $hash->{borrower} = $borrower->{borrower};
218                                                         $hash->{content}  = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
219                                                 }
220                                         } else {
221                                                 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
222                                         }
223                                         push @{ $json->{tags} }, $hash;
224                                 };
225                                 warn "#### ", encode_json($json);
226                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
227                                         $param->{callback}, "(", encode_json($json), ")\r\n";
228                         } elsif ( $method =~ m{/program} ) {
229
230                                 my $status = 501; # Not implementd
231
232                                 foreach my $p ( keys %$param ) {
233                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
234                                         my $tag = $1;
235                                         my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
236                                         $content    = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
237                                         $status = 302;
238
239                                         warn "PROGRAM $tag $content\n";
240                                         $rfid->write_blocks( $tag => $content );
241                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
242                                 }
243
244                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
245
246                         } elsif ( $method =~ m{/secure(.js)} ) {
247
248                                 my $json = $1;
249
250                                 my $status = 501; # Not implementd
251
252                                 foreach my $p ( keys %$param ) {
253                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
254                                         my $tag = $1;
255                                         my $data = $param->{$p};
256                                         $status = 302;
257
258                                         warn "SECURE $tag $data\n";
259                                         $rfid->write_afi( $tag => chr(hex($data)) );
260                                 }
261
262                                 if ( $json ) {
263                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
264                                                 $param->{callback}, "({ ok: 1 })\r\n";
265                                 } else {
266                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
267                                 }
268
269                         } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
270                                 my ( $method, $args ) = ( $1, $2 );
271                                 warn "SIP2: $method [$args]";
272
273                                 my $ts = strftime('%Y%m%d    %H%M%S', localtime());
274                                 my $loc      = $sip2->{loc} || die "missing sip->{loc}";
275                                 my $password = $sip2->{password} || die "missing sip->{password}";
276
277                                 my $hash;
278
279                                 if ( $method eq 'patron_info' ) {
280                                         my $patron = $args;
281                                         $hash = sip2_message("63000${ts}          AO$loc|AA$patron|AC$password|");
282
283                                 } elsif ( $method eq 'checkout' ) {
284                                         my ($patron,$barcode,$sid) = split(/\//, $args, 3);
285                                         $hash = sip2_message("11YN${ts}                  AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
286                                         if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
287                                                 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
288                                         }
289
290                                 } elsif ( $method eq 'checkin' ) {
291                                         my ($patron,$barcode,$sid) = split(/\//, $args, 3);
292                                         $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
293                                         if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
294                                                 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
295                                         }
296                                 } else {
297                                         print $client "HTTP/1.0 501 $method not implemented\r\n\r\n";
298                                         warn "ERROR 501 $request\n";
299                                 }
300
301                                 if ( $hash ) {
302                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
303                                                 encode_json( $hash );
304                                 }
305
306                         } elsif ( $method =~ m{/beep/(.*)} ) {
307                                 my $error = uri_unescape($1);
308                                 system "beep -f 800 -r 2 -l 100";
309                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{ beep: '$error' }\n";
310                                 print "BEEP $error\n";
311                         } else {
312                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
313                                 warn "ERROR 404 $request\n";
314                         }
315                 } else {
316                         print $client "HTTP/1.0 500 No method\r\n\r\n";
317                         warn "ERROR 500 $request\n";
318                 }
319                 close $client;
320
321             }; # end of eval
322             if ( $@ ) {
323                 print $client "HTTP/1.0 500 Error\r\n\r\nContent-Type: text/plain\r\n$@";
324                 warn "ERROR: $@";
325             }
326
327         }
328
329         die "server died";
330 }
331
332 sub rfid_register {
333         my $ip;
334
335         foreach ( split(/\n/, `ip addr` ) ) {
336                 if ( /^\d:\s(\w+):\s/ ) {
337                         $ip->{_last} = $1;
338                 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
339                         $ip->{ $ip->{_last} } = $1;
340                 } else {
341                         #warn "# SKIP [$_]\n";
342                 }
343         }
344
345         warn dump($ip);
346
347         my $ua = LWP::UserAgent->new;
348         my $url = URI->new( $rfid_url . '/register.pl');
349         $url->query_form(
350                 local_ip => $ip->{eth0} || $ip->{ (keys %$ip)[0] },
351         );
352         warn "GET ",$url->as_string;
353         my $response = $ua->get($url);
354         if ( $response->is_success ) {
355                 warn "# ", $response->decoded_content;
356                 my $json = decode_json $response->decoded_content;
357                 warn "REGISTER: ",dump($json);
358                 return $json;
359         } else {
360                 warn "ERROR ", $response->status_line;
361         }
362 }
363
364 rfid_register if $rfid_url;
365 http_server;
366
367 __DATA__
368 <html>
369 <head>
370 <title>RFID JSONP</title>
371 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
372 <style type="text/css">
373 .status {
374         background: #ff8;
375 }
376
377 .da {
378         background: #fcc;
379 }
380
381 .d7 {
382         background: #cfc;
383 }
384
385 label[for=pull-reader] {
386         position: absolute;
387         top: 1em;
388         right: 1em;
389         background: #eee;
390 }
391
392 </style>
393 <script type="text/javascript">
394
395 // mock console
396 if(!window.console) {
397         window.console = new function() {
398                 this.info = function(str) {};
399                 this.debug = function(str) {};
400         };
401 }
402
403
404 function got_visible_tags(data,textStatus) {
405         var html = 'No tags in range';
406         if ( data.tags ) {
407                 html = '<ul class="tags">';
408                 $.each(data.tags, function(i,tag) {
409                         console.debug( i, tag );
410                         html += '<li><tt class="' + tag.security + '">' + tag.sid;
411                         var content = tag.content || tag.borrower.cardnumber;
412
413                         if ( content ) {
414                                 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
415                                 if ( tag.type == 1 ) { // book
416                                         html += 'catalogue/search.pl?q=';
417                                 } else {
418                                         html += 'members/member.pl?member=';
419                                 }
420                                 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
421                                 html += '</tt>';
422 /*
423                                 html += '<form method=get action=program style="display:inline">'
424                                         + '<input type=hidden name='+tag.sid+' value="blank">'
425                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
426                                         + '</form>'
427                                 ;
428 */
429                         } else {
430                                 html += '</tt>';
431                                 html += ' <form method=get action=program style="display:inline">'
432                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
433                                         + '<input type=text name='+tag.sid+' size=12>'
434                                         + '<input type=submit value="Program">'
435                                         + '</form>'
436                                 ;
437                         }
438                 });
439                 html += '</ul>';
440         }
441
442         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
443
444         html = '<div class=status>'
445                 + textStatus
446                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
447                 + '</div>'
448                 + html
449                 ;
450         $('#tags').html( html );
451         window.setTimeout(function(){
452                 scan_tags();
453         },200); // re-scan every 200ms
454 };
455
456 function scan_tags() {
457         console.info('scan_tags');
458         if ( $('input#pull-reader').attr('checked') )
459                 $.getJSON("/scan?callback=?", got_visible_tags);
460 }
461
462 $(document).ready(function() {
463                 $('input#pull-reader').click( function() {
464                         scan_tags();
465                 });
466                 $('input#pull-reader').attr('checked', true); // force check on load
467
468                 $('div#tags').click( function() {
469                         $('input#pull-reader').attr('checked', false);
470                 } );
471
472                 scan_tags();
473 });
474 </script>
475 </head>
476 <body>
477
478 <h1>RFID tags in range</h1>
479
480 <label for=pull-reader>
481 <input id=pull-reader type=checkbox checked=1>
482 active
483 </label>
484
485 <div id="tags">
486 RFID reader not found or driver program not started.
487 </div>
488
489 </body>
490 </html>