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