f29c638262586f47c38991455af544e9dd7d5b7f
[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 = 1;
26 my $listen = '127.0.0.1:9000';
27 $listen = ':9000';
28 my $reader;
29 my $koha_url = 'http://ffzg.koha-dev.rot13.org:8080';
30 # internal URL so we can find local address of machine and vmware NAT
31 my $rfid_url = 'http://rfid.koha-dev.vbz.ffzg.hr';
32 my $sip2 = {
33         server   => '10.60.0.11:6002', # must be IP!
34 #       user     => 'sip2-user',
35 #       password => 'sip2-passwd',
36         user     => 'sip2user',
37         password => 'viva2koha',
38         loc      => 'FFZG',
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         'koha=s',       => \$koha_url,
52 ) || die $!;
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                 $client->autoflush(1);
158                 my $request = <$client>;
159
160                 warn "WEB << $request\n" if $debug;
161                 my $path;
162
163                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
164                         my $method = $1;
165                         my $param;
166                         if ( $method =~ s{\?(.+)}{} ) {
167                                 foreach my $p ( split(/[&;]/, $1) ) {
168                                         my ($n,$v) = split(/=/, $p, 2);
169                                         $param->{$n} = $v;
170                                 }
171                                 warn "WEB << param: ",dump( $param ) if $debug;
172                         }
173                         $path = $method;
174
175                         if ( $path eq '/' ) {
176                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
177                         } elsif ( $path =~ m{^/(examples/.+)} ) {
178                                 $path = $1; # FIXME prefix with dir for installation
179                                 my $size = -s $path;
180                                 warn "static $path $size bytes\n";
181                                 my $content_type = 'text/plain';
182                                 $content_type = 'application/javascript' if $path =~ /\.js$/;
183                                 $content_type = 'text/html' if $path =~ /\.html$/;
184                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
185                                 {
186                                         local $/ = undef;
187                                         open(my $fh, '<', $path) || die "can't open $path: $!";
188                                         while(<$fh>) {
189                                                 print $client $_;
190                                         }
191                                         close($fh);
192                                 }
193                         } elsif ( $method =~ m{/scan} ) {
194                                 my @tags = $rfid->tags;
195                                 my $json = { time => time() };
196                                 foreach my $tag ( @tags ) {
197                                         my $hash = $rfid->to_hash( $tag );
198                                         $hash->{sid}  = $tag;
199                                         if ( $hash->{tag_type} eq 'SmartX' ) {
200                                                 my $borrower = rfid_borrower $hash;
201                                                 if ( exists $borrower->{error} ) {
202                                                         warn "ERROR ", dump($borrower);
203                                                 } else {
204                                                         $hash->{borrower} = $borrower->{borrower};
205                                                 }
206                                         } else {
207                                                 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
208                                         }
209                                         push @{ $json->{tags} }, $hash;
210                                 };
211                                 warn "#### ", encode_json($json);
212                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
213                                         $param->{callback}, "(", encode_json($json), ")\r\n";
214                         } elsif ( $method =~ m{/program} ) {
215
216                                 my $status = 501; # Not implementd
217
218                                 foreach my $p ( keys %$param ) {
219                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
220                                         my $tag = $1;
221                                         my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
222                                         $content    = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
223                                         $status = 302;
224
225                                         warn "PROGRAM $tag $content\n";
226                                         $rfid->write_blocks( $tag => $content );
227                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? $afi->{secure} : $afi->{unsecure} ) );
228                                 }
229
230                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
231
232                         } elsif ( $method =~ m{/secure(.js)} ) {
233
234                                 my $json = $1;
235
236                                 my $status = 501; # Not implementd
237
238                                 foreach my $p ( keys %$param ) {
239                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
240                                         my $tag = $1;
241                                         my $data = $param->{$p};
242                                         $status = 302;
243
244                                         warn "SECURE $tag $data\n";
245                                         $rfid->write_afi( $tag => hex($data) );
246                                 }
247
248                                 if ( $json ) {
249                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
250                                                 $param->{callback}, "({ ok: 1 })\r\n";
251                                 } else {
252                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
253                                 }
254
255                         } elsif ( $method =~ m{/sip2/(\w+)/(.+)} ) {
256                                 my ( $method, $args ) = ( $1, $2 );
257                                 warn "SIP2: $method [$args]";
258
259                                 my $ts = strftime('%Y%m%d    %H%M%S', localtime());
260                                 my $loc      = $sip2->{loc} || die "missing sip->{loc}";
261                                 my $password = $sip2->{password} || die "missing sip->{password}";
262
263                                 my $hash;
264
265                                 if ( $method eq 'patron_info' ) {
266                                         my $patron = $args;
267                                         $hash = sip2_message("63000${ts}          AO$loc|AA$patron|AC$password|");
268
269                                 } elsif ( $method eq 'checkout' ) {
270                                         my ($patron,$barcode,$sid) = split(/\//, $args, 3);
271                                         $hash = sip2_message("11YN${ts}                  AO$loc|AA$patron|AB$barcode|AC$password|BON|BIN|");
272                                         if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
273                                                 $rfid->write_afi( $sid => chr( $afi->{unsecure} ) );
274                                         }
275
276                                 } elsif ( $method eq 'checkin' ) {
277                                         my ($patron,$barcode,$sid) = split(/\//, $args, 3);
278                                         $hash = sip2_message("09N${ts}${ts}AP|AO${loc}|AB$barcode|AC|BIN|");
279                                         if ( substr( $hash->{fixed}, 2, 1 ) == 1 ) {
280                                                 $rfid->write_afi( $sid => chr( $afi->{secure} ) );
281                                         }
282                                 } else {
283                                         print $client "HTTP/1.0 500 $method not implemented\r\n\r\n";
284                                 }
285
286                                 if ( $hash ) {
287                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
288                                                 encode_json( $hash );
289                                 }
290
291                         } else {
292                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
293                         }
294                 } else {
295                         print $client "HTTP/1.0 500 No method\r\n\r\n";
296                 }
297                 close $client;
298         }
299
300         die "server died";
301 }
302
303 sub rfid_register {
304         my $ip;
305
306         foreach ( split(/\n/, `ip addr` ) ) {
307                 if ( /^\d:\s(\w+):\s/ ) {
308                         $ip->{last} = $1;
309                 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
310                         $ip->{ $ip->{last} } = $1;
311                 } else {
312                         warn "# SKIP [$_]\n";
313                 }
314
315         }
316
317         my $ua = LWP::UserAgent->new;
318         my $url = URI->new( $rfid_url . '/register.pl');
319         $url->query_form(
320                 local_ip => $ip->{eth0},
321         );
322         warn "GET ",$url->as_string;
323         my $response = $ua->get($url);
324         if ( $response->is_success ) {
325                 warn "# ", $response->decoded_content;
326                 my $json = decode_json $response->decoded_content;
327                 warn "REGISTER: ",dump($json);
328                 return $json;
329         } else {
330                 warn "ERROR ", $response->status_line;
331         }
332 }
333
334 rfid_register;
335 http_server;
336
337 __DATA__
338 <html>
339 <head>
340 <title>RFID JSONP</title>
341 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
342 <style type="text/css">
343 .status {
344         background: #ff8;
345 }
346
347 .da {
348         background: #fcc;
349 }
350
351 .d7 {
352         background: #cfc;
353 }
354
355 label[for=pull-reader] {
356         position: absolute;
357         top: 1em;
358         right: 1em;
359         background: #eee;
360 }
361
362 </style>
363 <script type="text/javascript">
364
365 // mock console
366 if(!window.console) {
367         window.console = new function() {
368                 this.info = function(str) {};
369                 this.debug = function(str) {};
370         };
371 }
372
373
374 function got_visible_tags(data,textStatus) {
375         var html = 'No tags in range';
376         if ( data.tags ) {
377                 html = '<ul class="tags">';
378                 $.each(data.tags, function(i,tag) {
379                         console.debug( i, tag );
380                         html += '<li><tt class="' + tag.security + '">' + tag.sid;
381                         var content = tag.content || tag.borrower.cardnumber;
382
383                         if ( content ) {
384                                 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
385                                 if ( tag.type == 1 ) { // book
386                                         html += 'catalogue/search.pl?q=';
387                                 } else {
388                                         html += 'members/member.pl?member=';
389                                 }
390                                 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
391                                 html += '</tt>';
392 /*
393                                 html += '<form method=get action=program style="display:inline">'
394                                         + '<input type=hidden name='+tag.sid+' value="blank">'
395                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
396                                         + '</form>'
397                                 ;
398 */
399                         } else {
400                                 html += '</tt>';
401                                 html += ' <form method=get action=program style="display:inline">'
402                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
403                                         + '<input type=text name='+tag.sid+' size=12>'
404                                         + '<input type=submit value="Program">'
405                                         + '</form>'
406                                 ;
407                         }
408                 });
409                 html += '</ul>';
410         }
411
412         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
413
414         html = '<div class=status>'
415                 + textStatus
416                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
417                 + '</div>'
418                 + html
419                 ;
420         $('#tags').html( html );
421         window.setTimeout(function(){
422                 scan_tags();
423         },200); // re-scan every 200ms
424 };
425
426 function scan_tags() {
427         console.info('scan_tags');
428         if ( $('input#pull-reader').attr('checked') )
429                 $.getJSON("/scan?callback=?", got_visible_tags);
430 }
431
432 $(document).ready(function() {
433                 $('input#pull-reader').click( function() {
434                         scan_tags();
435                 });
436                 $('input#pull-reader').attr('checked', true); // force check on load
437
438                 $('div#tags').click( function() {
439                         $('input#pull-reader').attr('checked', false);
440                 } );
441
442                 scan_tags();
443 });
444 </script>
445 </head>
446 <body>
447
448 <h1>RFID tags in range</h1>
449
450 <label for=pull-reader>
451 <input id=pull-reader type=checkbox checked=1>
452 active
453 </label>
454
455 <div id="tags">
456 RFID reader not found or driver program not started.
457 </div>
458
459 </body>
460 </html>