"working" version of spot cache
[spider.git] / perl / Spot.pm
1 #
2 # the dx spot handler
3 #
4 # Copyright (c) - 1998 Dirk Koopman G1TLH
5 #
6 #
7 #
8
9 package Spot;
10
11 use IO::File;
12 use DXVars;
13 use DXDebug;
14 use DXUtil;
15 use DXLog;
16 use Julian;
17 use Prefix;
18 use DXDupe;
19 use Data::Dumper;
20 use QSL;
21 use DXSql;
22 use Time::HiRes qw(gettimeofday tv_interval);
23
24
25 use strict;
26
27 use vars qw($fp $statp $maxspots $defaultspots $maxdays $dirprefix $duplth $dupage $filterdef
28                         $totalspots $hfspots $vhfspots $maxcalllth $can_encode $use_db_for_search);
29
30 $fp = undef;
31 $statp = undef;
32 $maxspots = 100;                                        # maximum spots to return
33 $defaultspots = 10;                             # normal number of spots to return
34 $maxdays = 100;                         # normal maximum no of days to go back
35 $dirprefix = "spots";
36 $duplth = 20;                                   # the length of text to use in the deduping
37 $dupage = 1*3600;               # the length of time to hold spot dups
38 $maxcalllth = 12;                               # the max length of call to take into account for dupes
39 $filterdef = bless ([
40                                          # tag, sort, field, priv, special parser 
41                                          ['freq', 'r', 0, 0, \&decodefreq],
42                                          ['on', 'r', 0, 0, \&decodefreq],
43                                          ['call', 'c', 1],
44                                          ['info', 't', 3],
45                                          ['spotter', 'c', 4],
46                                          ['by', 'c', 4],
47                                          ['dxcc', 'nc', 5],
48                                          ['call_dxcc', 'nc', 5],
49                                          ['by_dxcc', 'nc', 6],
50                                          ['origin', 'c', 7, 9],
51                                          ['call_itu', 'ni', 8],
52                                          ['itu', 'ni', 8],
53                                          ['call_zone', 'nz', 9],
54                                          ['cq', 'nz', 9],
55                                          ['zone', 'nz', 9],
56                                          ['by_itu', 'ni', 10],
57                                          ['byitu', 'ni', 10],
58                                          ['by_zone', 'nz', 11],
59                                          ['byzone', 'nz', 11],
60                                          ['bycq', 'nz', 11],
61                                          ['call_state', 'ns', 12],
62                                          ['state', 'ns', 12],
63                                          ['by_state', 'ns', 13],
64                                          ['bystate', 'ns', 13],
65                                          ['ip', 'c', 14],
66 #                                        ['channel', 'c', 15],
67 #                                        ['rbn', 'a', 4, 0, \&filterrbnspot],
68                                         ], 'Filter::Cmd');
69 $totalspots = $hfspots = $vhfspots = 0;
70 $use_db_for_search = 0;
71
72 our %spotcache;                                 # the cache of data within the last $spotcachedays 0 or 2+ days
73 our $spotcachedays = 0;
74
75
76 our $readback = 1;
77
78 if ($readback) {
79         $readback = `which tac`;
80         chomp $readback;
81 }
82
83 # create a Spot Object
84 sub new
85 {
86         my $class = shift;
87         my $self = [ @_ ];
88         return bless $self, $class;
89 }
90
91 sub decodefreq
92 {
93         my $dxchan = shift;
94         my $l = shift;
95         my @f = split /,/, $l;
96         my @out;
97         my $f;
98         
99         foreach $f (@f) {
100                 my ($a, $b); 
101                 if ($f =~ m{^\d+/\d+$}) {
102                         push @out, $f;
103                 } elsif (($a, $b) = $f =~ m{^(\w+)(?:/(\w+))?$}) {
104                         $b = lc $b if $b;
105                         my @fr = Bands::get_freq(lc $a, $b);
106                         if (@fr) {
107                                 while (@fr) {
108                                         $a = shift @fr;
109                                         $b = shift @fr;
110                                         push @out, "$a/$b";  # add them as ranges
111                                 }
112                         } else {
113                                 return ('dfreq', $dxchan->msg('dfreq1', $f));
114                         }
115                 } else {
116                         return ('dfreq', $dxchan->msg('e20', $f));
117                 }
118         }
119         return (0, join(',', @out));                     
120 }
121
122 # filter setup for rbn spot so return the regex to detect it
123 sub filterrbnspot
124 {
125         my $dxchan = shift;
126         return ('-#$');
127 }
128
129 sub init
130 {
131         mkdir "$dirprefix", 0777 if !-e "$dirprefix";
132         $fp = DXLog::new($dirprefix, "dat", 'd');
133         $statp = DXLog::new($dirprefix, "dys", 'd');
134         my $today = Julian::Day->new(time);
135
136         # load up any old spots 
137         if ($main::dbh) {
138                 unless (grep $_ eq 'spot', $main::dbh->show_tables) {
139                         dbg('initialising spot tables');
140                         my $t = time;
141                         my $total;
142                         $main::dbh->spot_create_table;
143                         
144                         my $now = Julian::Day->alloc(1995, 0);
145                         my $sth = $main::dbh->spot_insert_prepare;
146                         while ($now->cmp($today) <= 0) {
147                                 my $fh = $fp->open($now);
148                                 if ($fh) {
149 #                                       $main::dbh->{RaiseError} = 0;
150                                         $main::dbh->begin_work;
151                                         my $count = 0;
152                                         while (<$fh>) {
153                                                 chomp;
154                                                 my @s = split /\^/;
155                                                 if (@s < 14) {
156                                                         my @a = (Prefix::cty_data($s[1]))[1..3];
157                                                         my @b = (Prefix::cty_data($s[4]))[1..3];
158                                                         push @s, $b[1] if @s < 7;
159                                                         push @s, '' if @s < 8;
160                                                         push @s, @a[0,1], @b[0,1] if @s < 12;
161                                                         push @s,  $a[2], $b[2] if @s < 14;
162                                                 } 
163                                                 $main::dbh->spot_insert(\@s, $sth);
164                                                 $count++;
165                                         }
166                                         $main::dbh->commit;
167                                         dbg("inserted $count spots from $now->[0] $now->[1]");
168                                         $fh->close;
169                                         $total += $count;
170                                 }
171                                 $now = $now->add(1);
172                         }
173                         $main::dbh->begin_work;
174                         $main::dbh->spot_add_indexes;
175                         $main::dbh->commit;
176 #                       $main::dbh->{RaiseError} = 1;
177                         $t = time - $t;
178                         my $min = int($t / 60);
179                         my $sec = $t % 60;
180                         dbg("$total spots converted in $min:$sec");
181                 }
182                 unless ($main::dbh->has_ipaddr) {
183                         $main::dbh->add_ipaddr;
184                         dbg("added ipaddr field to spot table");
185                 }
186         }
187
188         # initialise the cache if required
189         if ($spotcachedays) {
190                 my $t0 = [gettimeofday];
191                 $spotcachedays = 2 if $spotcachedays < 2;
192                 dbg "Spot::init - reading in $spotcachedays days of spots into cache"; 
193                 for (my $i = 0; $i < $spotcachedays; ++$i) {
194                         my $now = $today->sub($i);
195                         my $fh = $fp->open($now);
196                         if ($fh) {
197                                 my @in;
198                                 my $rec;
199                                 for ($rec = 0; <$fh>; ++$rec) {
200                                         chomp;
201                                         my @s = split /\^/;
202                                         if (@s < 14) {
203                                                 my @a = (Prefix::cty_data($s[1]))[1..3];
204                                                 my @b = (Prefix::cty_data($s[4]))[1..3];
205                                                 push @s, $b[1] if @s < 7;
206                                                 push @s, '' if @s < 8;
207                                                 push @s, @a[0,1], @b[0,1] if @s < 12;
208                                                 push @s,  $a[2], $b[2] if @s < 14;
209                                         }
210                                         unshift @in, \@s; 
211                                 }
212                                 $fh->close;
213                                 dbg("Spot::init read $rec spots from " . _cachek($now));
214                                 $spotcache{_cachek($now)} = \@in;
215                         }
216                         $now->add(1);
217                 }
218                 dbg("Spot::init $spotcachedays files of spots read into cache in " . _diffms($t0) . "mS")
219         }
220 }
221
222 sub prefix
223 {
224         return $fp->{prefix};
225 }
226
227 # fix up the full spot data from the basic spot data
228 # input is
229 # freq, call, time, comment, spotter, origin[, ip_address]
230 sub prepare
231 {
232         # $freq, $call, $t, $comment, $spotter, node, ip address = @_
233         my @out = @_[0..4];      # just up to the spotter
234
235         # normalise frequency
236         $out[0] = sprintf "%.1f", $out[0];
237   
238         # remove ssids and /xxx if present on spotter
239         $out[4] =~ s/-\d+$//o;
240
241         # remove leading and trailing spaces
242         $out[3] = unpad($out[3]);
243         
244         
245         # add the 'dxcc' country on the end for both spotted and spotter, then the cluster call
246         my @spd = Prefix::cty_data($out[1]);
247         push @out, $spd[0];
248         my @spt = Prefix::cty_data($out[4]);
249         push @out, $spt[0];
250         push @out, $_[5];
251         push @out, @spd[1,2], @spt[1,2], $spd[3], $spt[3];
252         push @out, $_[6] if $_[6] && is_ipaddr($_[6]);
253
254         # thus we now have:
255         # freq, call, time, comment, spotter, call country code, spotter country code, origin, call itu, call cqzone, spotter itu, spotter cqzone, call state, spotter state, spotter ip address
256         return @out;
257 }
258
259 sub add
260 {
261         my $buf = join('^', @_);
262         $fp->writeunix($_[2], $buf);
263         if ($spotcachedays) {
264                 my $now = Julian::Day->new($_[2]);
265                 my $day = _cachek($now);
266                 my $r = (exists $spotcache{$day}) ? $spotcache{$day} : ($spotcache{$day} = []);
267                 unshift @$r, \@_;
268
269                 # remove old days
270                 while (keys %spotcache > $spotcachedays+1) {
271                         while (sort keys %spotcache > $spotcachedays+1) {
272                                 delete $spotcache{$_};
273                         }
274                 }
275         }
276         if ($main::dbh) {
277                 $main::dbh->begin_work;
278                 $main::dbh->spot_insert(\@_);
279                 $main::dbh->commit;
280         }
281         $totalspots++;
282         if ($_[0] <= 30000) {
283                 $hfspots++;
284         } else {
285                 $vhfspots++;
286         }
287         if ($_[3] =~ /(?:QSL|VIA)/i) {
288                 my $q = QSL::get($_[1]) || new QSL $_[1];
289                 $q->update($_[3], $_[2], $_[4]);
290         }
291 }
292
293 # search the spot database for records based on the field no and an expression
294 # this returns a set of references to the spots
295 #
296 # the expression is a legal perl 'if' statement with the possible fields indicated
297 # by $f<n> where :-
298 #
299 #   $f0 = frequency
300 #   $f1 = call
301 #   $f2 = date in unix format
302 #   $f3 = comment
303 #   $f4 = spotter
304 #   $f5 = spotted dxcc country
305 #   $f6 = spotter dxcc country
306 #   $f7 = origin
307 #   $f8 = spotted itu
308 #   $f9 = spotted cq zone
309 #   $f10 = spotter itu
310 #   $f11 = spotter cq zone
311 #   $f12 = spotted us state
312 #   $f13 = spotter us state
313 #   $f14 = ip address
314 #
315 # In addition you can specify a range of days, this means that it will start searching
316 # from <n> days less than today to <m> days less than today
317 #
318 # Also you can select a range of entries so normally you would get the 0th (latest) entry
319 # back to the 5th latest, you can specify a range from the <x>th to the <y>the oldest.
320 #
321 # This routine is designed to be called as Spot::search(..)
322 #
323
324 sub search
325 {
326         my ($expr, $dayfrom, $dayto, $from, $to, $hint, $dofilter, $dxchan) = @_;
327         my @out;
328         my $ref;
329         my $i;
330         my $count;
331         my $today = Julian::Day->new(time());
332         my $fromdate;
333         my $todate;
334
335         $dayfrom = 0 if !$dayfrom;
336         $dayto = $maxdays unless $dayto;
337         $dayto = $dayfrom + $maxdays if $dayto < $dayfrom;
338         $fromdate = $today->sub($dayfrom);
339         $todate = $fromdate->sub($dayto);
340         $from = 0 unless $from;
341         $to = $defaultspots unless $to;
342         $hint = $hint ? "next unless $hint" : "";
343         $expr = "1" unless $expr;
344         
345         $to = $from + $maxspots if $to - $from > $maxspots || $to - $from <= 0;
346
347         if ($main::dbh && $use_db_for_search) {
348                 return $main::dbh->spot_search($expr, $dayfrom, $dayto, $from, $to, $hint, $dofilter, $dxchan);
349         }
350
351         #       $expr =~ s/\$f(\d\d?)/\$ref->[$1]/g; # swap the letter n for the correct field name
352         #  $expr =~ s/\$f(\d)/\$spots[$1]/g;               # swap the letter n for the correct field name
353   
354
355         dbg("Spot::search hint='$hint', expr='$expr', spotno=$from-$to, day=$dayfrom-$dayto\n") if isdbg('search');
356   
357         # build up eval to execute
358         dbg("Spot::search Spot eval: $expr") if isdbg('searcheval');
359         $expr =~ s/\$r/\$_[0]/g;
360         my $eval = qq{ sub { return $expr; } };
361         dbg("Spot::search Spot eval: $eval") if isdbg('searcheval');
362         my $ecode = eval $eval;
363         return ("Spot search error", $@) if $@;
364         
365         
366         my $fh;
367         my $now = $fromdate;
368         my $today = Julian::Day->new($main::systime);
369         
370         for ($i = $count = 0; $count < $to && $i < $maxdays; ++$i) { # look thru $maxdays worth of files only
371                 last if $now->cmp($todate) <= 0;
372
373
374                 my $this = $now->sub($i);
375                 my $fn = $fp->fn($this);
376                 my $cachekey = _cachek($this); 
377                 my $rec = 0;
378
379                 if ($spotcachedays && $spotcache{$cachekey}) {
380                         foreach my $r (@{$spotcache{$cachekey}}) {
381                                 ++$rec;
382                                 if ($dofilter && $dxchan && $dxchan->{spotsfilter}) {
383                                         my ($gotone, undef) = $dxchan->{spotsfilter}->it(@$r);
384                                         next unless $gotone;
385                                 }
386                                 if (&$ecode($r)) {
387                                         ++$count;
388                                         next if $count < $from;
389                                         push @out, $r;
390                                         last if $count >= $to;
391                                 }
392                         }
393                         dbg("Spot::search cache recs read: $rec") if isdbg('search');
394                 } else {
395                         if ($readback) {
396                                 dbg("Spot::search search using tac fn: $fn $i") if isdbg('search');
397                                 $fh = IO::File->new("$readback $fn |");
398                         }
399                         else {
400                                 dbg("Spot::search search fn: $fp->{fn} $i") if isdbg('search');
401                                 $fh = $fp->open($now->sub($i)); # get the next file
402                         }
403                         if ($fh) {
404                                 my $in;
405                                 while (<$fh>) {
406                                         chomp;
407                                         my @r = split /\^/;
408                                         ++$rec;
409                                         if ($dofilter && $dxchan && $dxchan->{spotsfilter}) {
410                                                 my ($gotone, undef) = $dxchan->{spotsfilter}->it(@r);
411                                                 next unless $gotone;
412                                         }
413                                         if (&$ecode(\@r)) {
414                                                 ++$count;
415                                                 next if $count < $from;
416                                                 if ($readback) {
417                                                         push @out, \@r;
418                                                         last if $count >= $to;
419                                                 } else {
420                                                         push @out, \@r;
421                                                         shift @out if $count >= $to;
422                                                 }
423                                         }
424                                 }
425                                 dbg("Spot::search file recs read: $rec") if isdbg('search');
426                                 last if $count >= $to; # stop after to
427                         }
428                 }
429         }
430         return ("Spot search error", $@) if $@;
431
432         @out = sort {$b->[2] <=> $a->[2]} @out if @out;
433         return @out;
434 }
435
436 # change a freq range->regular expression
437 sub ftor
438 {
439         my ($a, $b) = @_;
440         return undef unless $a < $b;
441         $b--;
442         my $d = $b - $a;
443         my @a = split //, $a;
444         my @b = split //, $b;
445         my $out;
446         while (@b > @a) {
447                 $out .= shift @b;
448         }
449         while (@b) {
450                 my $aa = shift @a;
451                 my $bb = shift @b;
452                 if (@b < (length $d)) {
453                         $out .= '\\d';
454                 } elsif ($aa eq $bb) {
455                         $out .= $aa;
456                 } elsif ($aa < $bb) {
457                         $out .= "[$aa-$bb]";
458                 } else {
459                         $out .= "[0-$bb$aa-9]";
460                 }
461         }
462         return $out;
463 }
464
465 # format a spot for user output in list mode
466 sub formatl
467 {
468         my $t = ztime($_[2]);
469         my $d = cldate($_[2]);
470         return sprintf "%8.1f  %-11s %s %s  %-28.28s%7s>", $_[0], $_[1], $d, $t, ($_[3]||''), "<$_[4]" ;
471 }
472
473 # enter the spot for dup checking and return true if it is already a dup
474 sub dup
475 {
476         my ($freq, $call, $d, $text, $by, $cty) = @_; 
477
478         # dump if too old
479         return 2 if $d < $main::systime - $dupage;
480         
481         # turn the time into minutes (should be already but...)
482         $d = int ($d / 60);
483         $d *= 60;
484
485         # remove SSID or area
486         $by =~ s|[-/]\d+$||;
487         
488 #       $freq = sprintf "%.1f", $freq;       # normalise frequency
489         $freq = int $freq;       # normalise frequency
490         $call = substr($call, 0, $maxcalllth) if length $call > $maxcalllth;
491
492         chomp $text;
493         $text =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
494         $text = uc unpad($text);
495         if ($cty && $text && length $text <= 4) {
496                 unless ($text =~ /^C?Q/ || $text =~ /^[\d\W]+$/) {
497                         my @try = Prefix::cty_data($text);
498                         $text = "" if $cty == $try[0];
499                 }
500         }
501         my $otext = $text;
502 #       $text = Encode::encode("iso-8859-1", $text) if $main::can_encode && Encode::is_utf8($text, 1);
503         $text =~ s/^\+\w+\s*//;                 # remove leading LoTW callsign
504         $text =~ s/\s{2,}[\dA-Z]?[A-Z]\d?$// if length $text > 24;
505         $text =~ s/[\W\x00-\x2F\x7B-\xFF]//g; # tautology, just to make quite sure!
506         $text = substr($text, 0, $duplth) if length $text > $duplth; 
507         my $ldupkey = "X$freq|$call|$by|$text";
508         my $t = DXDupe::find($ldupkey);
509         return 1 if $t && $t - $main::systime > 0;
510         DXDupe::add($ldupkey, $main::systime+$dupage);
511         $otext = substr($otext, 0, $duplth) if length $otext > $duplth; 
512         $otext =~ s/\s+$//;
513         if (length $otext && $otext ne $text) {
514                 $ldupkey = "X$freq|$call|$by|$otext";
515                 $t = DXDupe::find($ldupkey);
516                 return 1 if $t && $t - $main::systime > 0;
517                 DXDupe::add($ldupkey, $main::systime+$dupage);
518         }
519         return 0;
520 }
521
522 sub listdups
523 {
524         return DXDupe::listdups('X', $dupage, @_);
525 }
526
527 sub genstats($)
528 {
529         my $date = shift;
530         my $in = $fp->open($date);
531         my $out = $statp->open($date, 'w');
532         my @freq;
533         my %list;
534         my @tot;
535         
536         if ($in && $out) {
537                 my $i = 0;
538                 @freq = map {[$i++, Bands::get_freq($_)]} qw(136khz 160m 80m 60m 40m 30m 20m 17m 15m 12m 10m 6m 4m 2m 220 70cm 23cm 13cm 9cm 6cm 3cm 12mm 6mm);
539                 while (<$in>) {
540                         chomp;
541                         my ($freq, $by, $dxcc) = (split /\^/)[0,4,6];
542                         my $ref = $list{$by} || [0, $dxcc];
543                         for (@freq) {
544                                 next unless defined $_;
545                                 if ($freq >= $_->[1] && $freq <= $_->[2]) {
546                                         $$ref[$_->[0]+2]++;
547                                         $tot[$_->[0]+2]++;
548                                         $$ref[0]++;
549                                         $tot[0]++;
550                                         $list{$by} = $ref;
551                                         last;
552                                 }
553                         }
554                 }
555
556                 for ($i = 0; $i < @freq+2; $i++) {
557                         $tot[$i] ||= 0;
558                 }
559                 $statp->write($date, join('^', 'TOTALS', @tot));
560
561                 for (sort {$list{$b}->[0] <=> $list{$a}->[0]} keys %list) {
562                         my $ref = $list{$_};
563                         my $call = $_;
564                         for ($i = 0; $i < @freq+2; ++$i) {
565                                 $ref->[$i] ||= 0;
566                         }
567                         $statp->write($date, join('^', $call, @$ref));
568                 }
569                 $statp->close;
570         }
571 }
572
573 # return true if the stat file is newer than than the spot file
574 sub checkstats($)
575 {
576         my $date = shift;
577         my $in = $fp->mtime($date);
578         my $out = $statp->mtime($date);
579         return defined $out && defined $in && $out >= $in;
580 }
581
582 # daily processing
583 sub daily
584 {
585         my $date = Julian::Day->new($main::systime)->sub(1);
586         genstats($date) unless checkstats($date);
587 }
588
589 sub _cachek
590 {
591         return "$_[0]->[0]|$_[0]->[1]";
592 }
593 1;
594
595
596
597