5baff8590670f6ea9669887573dded26790a8a2b
[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                                                 }
145                                         } else {
146                                                 $hash->{security} = uc unpack 'H*', $rfid->afi( $tag );
147                                         }
148                                         push @{ $json->{tags} }, $hash;
149                                 };
150                                 warn "#### ", encode_json($json);
151                                 print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
152                                         $param->{callback}, "(", encode_json($json), ")\r\n";
153                         } elsif ( $method =~ m{/program} ) {
154
155                                 my $status = 501; # Not implementd
156
157                                 foreach my $p ( keys %$param ) {
158                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
159                                         my $tag = $1;
160                                         my $content = Biblio::RFID::RFID501->from_hash({ content => $param->{$p} });
161                                         $content    = Biblio::RFID::RFID501->blank if $param->{$p} eq 'blank';
162                                         $status = 302;
163
164                                         warn "PROGRAM $tag $content\n";
165                                         $rfid->write_blocks( $tag => $content );
166                                         $rfid->write_afi(    $tag => chr( $param->{$p} =~ /^130/ ? 0xDA : 0xD7 ) );
167                                 }
168
169                                 print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
170
171                         } elsif ( $method =~ m{/secure(.js)} ) {
172
173                                 my $json = $1;
174
175                                 my $status = 501; # Not implementd
176
177                                 foreach my $p ( keys %$param ) {
178                                         next unless $p =~ m/^(E[0-9A-F]{15})$/;
179                                         my $tag = $1;
180                                         my $data = $param->{$p};
181                                         $status = 302;
182
183                                         warn "SECURE $tag $data\n";
184                                         $rfid->write_afi( $tag => chr(hex($data)) );
185                                 }
186
187                                 if ( $json ) {
188                                         print $client "HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n",
189                                                 $param->{callback}, "({ ok: 1 })\r\n";
190                                 } else {
191                                         print $client "HTTP/1.0 $status $method\r\nLocation: $server_url\r\n\r\n";
192                                 }
193
194                         } else {
195                                 print $client "HTTP/1.0 404 Unkown method\r\n\r\n";
196                         }
197                 } else {
198                         print $client "HTTP/1.0 500 No method\r\n\r\n";
199                 }
200                 close $client;
201
202             }; # end of eval
203             if ( $@ ) {
204                 warn "ERROR: $@";
205             }
206
207         }
208
209         die "server died";
210 }
211
212 sub rfid_register {
213         my $ip;
214
215         foreach ( split(/\n/, `ip addr` ) ) {
216                 if ( /^\d:\s(\w+):\s/ ) {
217                         $ip->{last} = $1;
218                 } elsif ( /^\s+inet\s((\d+)\.(\d+)\.(\d+)\.(\d+))\/(\d+)/ ) {
219                         $ip->{ $ip->{last} } = $1;
220                 } else {
221                         warn "# SKIP [$_]\n";
222                 }
223
224         }
225
226         my $ua = LWP::UserAgent->new;
227         my $url = URI->new( $rfid_url . '/register.pl');
228         $url->query_form(
229                 local_ip => $ip->{eth0},
230         );
231         warn "GET ",$url->as_string;
232         my $response = $ua->get($url);
233         if ( $response->is_success ) {
234                 warn "# ", $response->decoded_content;
235                 my $json = decode_json $response->decoded_content;
236                 warn "REGISTER: ",dump($json);
237                 return $json;
238         } else {
239                 warn "ERROR ", $response->status_line;
240         }
241 }
242
243 rfid_register;
244 http_server;
245
246 __DATA__
247 <html>
248 <head>
249 <title>RFID JSONP</title>
250 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
251 <style type="text/css">
252 .status {
253         background: #ff8;
254 }
255
256 .da {
257         background: #fcc;
258 }
259
260 .d7 {
261         background: #cfc;
262 }
263
264 label[for=pull-reader] {
265         position: absolute;
266         top: 1em;
267         right: 1em;
268         background: #eee;
269 }
270
271 </style>
272 <script type="text/javascript">
273
274 // mock console
275 if(!window.console) {
276         window.console = new function() {
277                 this.info = function(str) {};
278                 this.debug = function(str) {};
279         };
280 }
281
282
283 function got_visible_tags(data,textStatus) {
284         var html = 'No tags in range';
285         if ( data.tags ) {
286                 html = '<ul class="tags">';
287                 $.each(data.tags, function(i,tag) {
288                         console.debug( i, tag );
289                         html += '<li><tt class="' + tag.security + '">' + tag.sid;
290                         var content = tag.content || tag.borrower.cardnumber;
291
292                         if ( content ) {
293                                 html += ' <a href="http://koha.example.com:8080/cgi-bin/koha/';
294                                 if ( tag.type == 1 ) { // book
295                                         html += 'catalogue/search.pl?q=';
296                                 } else {
297                                         html += 'members/member.pl?member=';
298                                 }
299                                 html += content + '" title="lookup in Koha" target="koha-lookup">' + content + '</a>';
300                                 html += '</tt>';
301 /*
302                                 html += '<form method=get action=program style="display:inline">'
303                                         + '<input type=hidden name='+tag.sid+' value="blank">'
304                                         + '<input type=submit value="Blank" onclick="return confirm(\'Blank tag '+tag.sid+'\')">'
305                                         + '</form>'
306                                 ;
307 */
308                         } else {
309                                 html += '</tt>';
310                                 html += ' <form method=get action=program style="display:inline">'
311                                         + '<!-- <input type=checkbox name=secure value='+tag.sid+' title="secure tag"> -->'
312                                         + '<input type=text name='+tag.sid+' size=12>'
313                                         + '<input type=submit value="Program">'
314                                         + '</form>'
315                                 ;
316                         }
317                 });
318                 html += '</ul>';
319         }
320
321         var arrows = Array( 8592, 8598, 8593, 8599, 8594, 8600, 8595, 8601 );
322
323         html = '<div class=status>'
324                 + textStatus
325                 + ' &#' + arrows[ data.time % arrows.length ] + ';'
326                 + '</div>'
327                 + html
328                 ;
329         $('#tags').html( html );
330         window.setTimeout(function(){
331                 scan_tags();
332         },200); // re-scan every 200ms
333 };
334
335 function scan_tags() {
336         console.info('scan_tags');
337         if ( $('input#pull-reader').attr('checked') )
338                 $.getJSON("/scan?callback=?", got_visible_tags);
339 }
340
341 $(document).ready(function() {
342                 $('input#pull-reader').click( function() {
343                         scan_tags();
344                 });
345                 $('input#pull-reader').attr('checked', true); // force check on load
346
347                 $('div#tags').click( function() {
348                         $('input#pull-reader').attr('checked', false);
349                 } );
350
351                 scan_tags();
352 });
353 </script>
354 </head>
355 <body>
356
357 <h1>RFID tags in range</h1>
358
359 <label for=pull-reader>
360 <input id=pull-reader type=checkbox checked=1>
361 active
362 </label>
363
364 <div id="tags">
365 RFID reader not found or driver program not started.
366 </div>
367
368 </body>
369 </html>