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