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