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