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