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