added from_reader to get reader source for tag
[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
23 my $debug = 1;
24 my $listen = '127.0.0.1:9000';
25 $listen = ':9000';
26 my $reader;
27 my $koha_url = 'http://ffzg.koha-dev.rot13.org:8080';
28 # internal URL so we can find local address of machine and vmware NAT
29 my $rfid_url = 'http://rfid.koha-dev.vbz.ffzg.hr';
30
31 use Getopt::Long;
32
33 GetOptions(
34         'debug!'    => \$debug,
35         'listen=s', => \$listen,
36         'reader=s', => \$reader,
37         'koha=s',       => \$koha_url,
38 ) || die $!;
39
40 our $rfid_sid_cache;
41
42 sub rfid_borrower {
43         my $hash = shift;
44         if ( my $json = $rfid_sid_cache->{ $hash->{sid} } ) {
45                 return $json;
46         }
47         my $ua = LWP::UserAgent->new;
48         my $url = URI->new( $koha_url . '/cgi-bin/koha/ffzg/rfid/borrower.pl');
49         $url->query_form(
50                   RFID_SID => $hash->{sid}
51                 , OIB => $hash->{OIB}
52                 , JMBAG => $hash->{JMBAG}
53         );
54         warn "GET ",$url->as_string;
55         my $response = $ua->get($url);
56         if ( $response->is_success ) {
57                 my $json = decode_json $response->decoded_content;
58                 $rfid_sid_cache->{ $hash->{sid} } = $json;
59                 return $json;
60         } else {
61                 warn "ERROR ", $response->status_line;
62         }
63 }
64
65 use lib 'lib';
66 use Biblio::RFID::RFID501;
67 use Biblio::RFID::Reader;
68 my $rfid = Biblio::RFID::Reader->new( shift @ARGV );
69
70 my $index_html;
71 {
72         local $/ = undef;
73         $index_html = <DATA>;
74         $index_html =~ s{http://koha.example.com:8080}{$koha_url}sg;
75 }
76
77 my $server_url;
78
79 sub http_server {
80
81         my $server = IO::Socket::INET->new(
82                 Proto     => 'tcp',
83                 LocalAddr => $listen,
84                 Listen    => SOMAXCONN,
85                 Reuse     => 1
86         );
87                                                                   
88         die "can't setup server: $!" unless $server;
89
90         $server_url = 'http://' . $listen;
91         print "Server $0 ready at $server_url\n";
92
93         while (my $client = $server->accept()) {
94
95             eval { # don't die inside here!
96
97                 $client->autoflush(1);
98                 my $request = <$client>;
99
100                 warn "WEB << $request\n" if $debug;
101                 my $path;
102
103                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
104                         my $method = $1;
105                         my $param;
106                         if ( $method =~ s{\?(.+)}{} ) {
107                                 foreach my $p ( split(/[&;]/, $1) ) {
108                                         my ($n,$v) = split(/=/, $p, 2);
109                                         $param->{$n} = $v;
110                                 }
111                                 warn "WEB << param: ",dump( $param ) if $debug;
112                         }
113                         $path = $method;
114
115                         if ( $path eq '/' ) {
116                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n$index_html";
117                         } elsif ( $path =~ m{^/(examples/.+)} ) {
118                                 $path = $1; # FIXME prefix with dir for installation
119                                 my $size = -s $path;
120                                 warn "static $path $size bytes\n";
121                                 my $content_type = 'text/plain';
122                                 $content_type = 'application/javascript' if $path =~ /\.js/;
123                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: $content_type\r\nContent-Length: $size\r\n\r\n";
124                                 {
125                                         local $/ = undef;
126                                         open(my $fh, '<', $path) || die "can't open $path: $!";
127                                         while(<$fh>) {
128                                                 print $client $_;
129                                         }
130                                         close($fh);
131                                 }
132                         } elsif ( $method =~ m{/scan} ) {
133                                 my @tags = $rfid->tags;
134                                 my $json = { time => time() };
135                                 foreach my $tag ( @tags ) {
136                                         my $hash = $rfid->to_hash( $tag );
137                                         $hash->{sid}  = $tag;
138                                         if ( $hash->{tag_type} eq 'SmartX' ) {
139                                                 my $borrower = rfid_borrower $hash;
140                                                 if ( exists $borrower->{error} ) {
141                                                         warn "ERROR ", dump($borrower);
142                                                 } else {
143                                                         $hash->{borrower} = $borrower->{borrower};
144                                                         $hash->{content}  = $borrower->{borrower}->{cardnumber}; # compatibile with 3M tags
145                                                 }
146                                         } else {
147                                                 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
148                                         }
149                                         push @{ $json->{tags} }, $hash;
150                                 };
151                                 warn "#### ", encode_json($json);
152                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
153                                         $param->{callback}, "(", encode_json($json), ")\r\n";
154                         } elsif ( $method =~ m{/program} ) {
155
156                                 my $status = 501; # Not implementd
157
158                                 foreach my $p ( keys %$param ) {
159                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
160                                         my $tag = $1;
161                                         my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
162                                         $content    = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
163                                         $status = 302;
164
165                                         warn "PROGRAM $tag $content\n";
166                                         $rfid->write_blocks( $tag => $content );
167                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? 0xDA : 0xD7 ) );
168                                 }
169
170                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
171
172                         } elsif ( $method =~ m{/secure(.js)} ) {
173
174                                 my $json = $1;
175
176                                 my $status = 501; # Not implementd
177
178                                 foreach my $p ( keys %$param ) {
179                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
180                                         my $tag = $1;
181                                         my $data = $param->{$p};
182                                         $status = 302;
183
184                                         warn "SECURE $tag $data\n";
185                                         $rfid->write_afi( $tag => chr(hex($data)) );
186                                 }
187
188                                 if ( $json ) {
189                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
190                                                 $param->{callback}, "({ ok: 1 })\r\n";
191                                 } else {
192                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
193                                 }
194
195                         } else {
196                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
197                         }
198                 } else {
199                         print $client "HTTP/1.0 500 No method\r\n\r\n";
200                 }
201                 close $client;
202
203             }; # end of eval
204             if ( $@ ) {
205                 warn "ERROR: $@";
206             }
207
208         }
209
210         die "server died";
211 }
212
213 sub rfid_register {
214         my $ip;
215
216         foreach ( split(/\n/, `ip addr` ) ) {
217                 if ( /^\d:\s(\w+):\s/ ) {
218                         $ip->{last} = $1;
219                 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
220                         $ip->{ $ip->{last} } = $1;
221                 } else {
222                         warn "# SKIP [$_]\n";
223                 }
224
225         }
226
227         my $ua = LWP::UserAgent->new;
228         my $url = URI->new( $rfid_url . '/register.pl');
229         $url->query_form(
230                 local_ip => $ip->{eth0},
231         );
232         warn "GET ",$url->as_string;
233         my $response = $ua->get($url);
234         if ( $response->is_success ) {
235                 warn "# ", $response->decoded_content;
236                 my $json = decode_json $response->decoded_content;
237                 warn "REGISTER: ",dump($json);
238                 return $json;
239         } else {
240                 warn "ERROR ", $response->status_line;
241         }
242 }
243
244 rfid_register;
245 http_server;
246
247 __DATA__
248 <html>
249 <head>
250 <title>RFID JSONP</title>
251 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
252 <style type="text/css">
253 .status {
254         background: #ff8;
255 }
256
257 .da {
258         background: #fcc;
259 }
260
261 .d7 {
262         background: #cfc;
263 }
264
265 label[for=pull-reader] {
266         position: absolute;
267         top: 1em;
268         right: 1em;
269         background: #eee;
270 }
271
272 </style>
273 <script type="text/javascript">
274
275 // mock console
276 if(!window.console) {
277         window.console = new function() {
278                 this.info = function(str) {};
279                 this.debug = function(str) {};
280         };
281 }
282
283
284 function got_visible_tags(data,textStatus) {
285         var html = 'No tags in range';
286         if ( data.tags ) {
287                 html = '<ul class="tags">';
288                 $.each(data.tags, function(i,tag) {
289                         console.debug( i, tag );
290                         html += '<li><tt class="' + tag.security + '">' + tag.sid;
291                         var content = tag.content || tag.borrower.cardnumber;
292
293                         if ( content ) {
294                                 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
295                                 if ( tag.type == 1 ) { // book
296                                         html += 'catalogue/search.pl?q=';
297                                 } else {
298                                         html += 'members/member.pl?member=';
299                                 }
300                                 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
301                                 html += '</tt>';
302 /*
303                                 html += '<form method=get action=program style="display:inline">'
304                                         + '<input type=hidden name='+tag.sid+' value="blank">'
305                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
306                                         + '</form>'
307                                 ;
308 */
309                         } else {
310                                 html += '</tt>';
311                                 html += ' <form method=get action=program style="display:inline">'
312                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
313                                         + '<input type=text name='+tag.sid+' size=12>'
314                                         + '<input type=submit value="Program">'
315                                         + '</form>'
316                                 ;
317                         }
318                 });
319                 html += '</ul>';
320         }
321
322         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
323
324         html = '<div class=status>'
325                 + textStatus
326                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
327                 + '</div>'
328                 + html
329                 ;
330         $('#tags').html( html );
331         window.setTimeout(function(){
332                 scan_tags();
333         },200); // re-scan every 200ms
334 };
335
336 function scan_tags() {
337         console.info('scan_tags');
338         if ( $('input#pull-reader').attr('checked') )
339                 $.getJSON("/scan?callback=?", got_visible_tags);
340 }
341
342 $(document).ready(function() {
343                 $('input#pull-reader').click( function() {
344                         scan_tags();
345                 });
346                 $('input#pull-reader').attr('checked', true); // force check on load
347
348                 $('div#tags').click( function() {
349                         $('input#pull-reader').attr('checked', false);
350                 } );
351
352                 scan_tags();
353 });
354 </script>
355 </head>
356 <body>
357
358 <h1>RFID tags in range</h1>
359
360 <label for=pull-reader>
361 <input id=pull-reader type=checkbox checked=1>
362 active
363 </label>
364
365 <div id="tags">
366 RFID reader not found or driver program not started.
367 </div>
368
369 </body>
370 </html>