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