]> dxcluster.org Git - spider.git/blob - perl/Spot.pm
bda988f8657bd684975c406db3b7a423b73c9435
[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 = 2;                 # default 2 days worth
74 our $minselfspotqrg = 1240000;  # minimum freq above which self spotting is allowed
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 > 0) {
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 from comment field
242         $out[3] = unpad($out[3]);
243         
244         # add the 'dxcc' country on the end for both spotted and spotter, then the cluster call
245         my @spd = Prefix::cty_data($out[1]);
246         push @out, $spd[0];
247         my @spt = Prefix::cty_data($out[4]);
248         push @out, $spt[0];
249         push @out, $_[5];
250         push @out, @spd[1,2], @spt[1,2], $spd[3], $spt[3];
251         push @out, $_[6] if $_[6] && is_ipaddr($_[6]);
252
253         # thus we now have:
254         # 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
255         return @out;
256 }
257
258 sub add
259 {
260         my $buf = join('^', @_);
261         $fp->writeunix($_[2], $buf);
262         if ($spotcachedays > 0) {
263                 my $now = Julian::Day->new($_[2]);
264                 my $day = _cachek($now);
265                 my $r = (exists $spotcache{$day}) ? $spotcache{$day} : ($spotcache{$day} = []);
266                 unshift @$r, \@_;
267         }
268         if ($main::dbh) {
269                 $main::dbh->begin_work;
270                 $main::dbh->spot_insert(\@_);
271                 $main::dbh->commit;
272         }
273         $totalspots++;
274         if ($_[0] <= 30000) {
275                 $hfspots++;
276         } else {
277                 $vhfspots++;
278         }
279         if ($_[3] =~ /(?:QSL|VIA)/i) {
280                 my $q = QSL::get($_[1]) || new QSL $_[1];
281                 $q->update($_[3], $_[2], $_[4]);
282         }
283 }
284
285 # search the spot database for records based on the field no and an expression
286 # this returns a set of references to the spots
287 #
288 # the expression is a legal perl 'if' statement with the possible fields indicated
289 # by $f<n> where :-
290 #
291 #   $f0 = frequency
292 #   $f1 = call
293 #   $f2 = date in unix format
294 #   $f3 = comment
295 #   $f4 = spotter
296 #   $f5 = spotted dxcc country
297 #   $f6 = spotter dxcc country
298 #   $f7 = origin
299 #   $f8 = spotted itu
300 #   $f9 = spotted cq zone
301 #   $f10 = spotter itu
302 #   $f11 = spotter cq zone
303 #   $f12 = spotted us state
304 #   $f13 = spotter us state
305 #   $f14 = ip address
306 #
307 # In addition you can specify a range of days, this means that it will start searching
308 # from <n> days less than today to <m> days less than today
309 #
310 # Also you can select a range of entries so normally you would get the 0th (latest) entry
311 # back to the 5th latest, you can specify a range from the <x>th to the <y>the oldest.
312 #
313 # This routine is designed to be called as Spot::search(..)
314 #
315
316 sub search
317 {
318         my ($expr, $dayfrom, $dayto, $from, $to, $hint, $dofilter, $dxchan) = @_;
319         my @out;
320         my $ref;
321         my $i;
322         my $count;
323         my $today = Julian::Day->new(time());
324         my $fromdate;
325         my $todate;
326
327         $dayfrom = 0 if !$dayfrom;
328         $dayto = $maxdays unless $dayto;
329         $dayto = $dayfrom + $maxdays if $dayto < $dayfrom;
330         $fromdate = $today->sub($dayfrom);
331         $todate = $fromdate->sub($dayto);
332         $from = 0 unless $from;
333         $to = $defaultspots unless $to;
334         $hint = $hint ? "next unless $hint" : "";
335         $expr = "1" unless $expr;
336         
337         $to = $from + $maxspots if $to - $from > $maxspots || $to - $from <= 0;
338
339         if ($main::dbh && $use_db_for_search) {
340                 return $main::dbh->spot_search($expr, $dayfrom, $dayto, $from, $to, $hint, $dofilter, $dxchan);
341         }
342
343         #       $expr =~ s/\$f(\d\d?)/\$ref->[$1]/g; # swap the letter n for the correct field name
344         #  $expr =~ s/\$f(\d)/\$spots[$1]/g;               # swap the letter n for the correct field name
345   
346
347         dbg("Spot::search hint='$hint', expr='$expr', spotno=$from-$to, day=$dayfrom-$dayto\n") if isdbg('search');
348   
349         # build up eval to execute
350
351         dbg("Spot::search Spot eval: $expr") if isdbg('searcheval');
352         $expr =~ s/\$r/\$_[0]/g;
353         my $eval = qq{ sub { return $expr; } };
354         dbg("Spot::search Spot eval: $eval") if isdbg('searcheval');
355         my $ecode = eval $eval;
356         return ("Spot search error", $@) if $@;
357         
358         my $fh;
359         my $now = $fromdate;
360         my $today = Julian::Day->new($main::systime);
361         
362         for ($i = $count = 0; $count < $to && $i < $maxdays; ++$i) { # look thru $maxdays worth of files only
363                 last if $now->cmp($todate) <= 0;
364
365
366                 my $this = $now->sub($i);
367                 my $fn = $fp->fn($this);
368                 my $cachekey = _cachek($this); 
369                 my $rec = 0;
370
371                 if ($spotcachedays > 0 && $spotcache{$cachekey}) {
372                         foreach my $r (@{$spotcache{$cachekey}}) {
373                                 ++$rec;
374                                 if ($dofilter && $dxchan && $dxchan->{spotsfilter}) {
375                                         my ($gotone, undef) = $dxchan->{spotsfilter}->it(@$r);
376                                         next unless $gotone;
377                                 }
378                                 if (&$ecode($r)) {
379                                         ++$count;
380                                         next if $count < $from;
381                                         push @out, $r;
382                                         last if $count >= $to;
383                                 }
384                         }
385                         dbg("Spot::search cache recs read: $rec") if isdbg('search');
386                 } else {
387                         if ($readback) {
388                                 dbg("Spot::search search using tac fn: $fn $i") if isdbg('search');
389                                 $fh = IO::File->new("$readback $fn |");
390                         }
391                         else {
392                                 dbg("Spot::search search fn: $fp->{fn} $i") if isdbg('search');
393                                 $fh = $fp->open($now->sub($i)); # get the next file
394                         }
395                         if ($fh) {
396                                 my $in;
397                                 while (<$fh>) {
398                                         chomp;
399                                         my @r = split /\^/;
400                                         ++$rec;
401                                         if ($dofilter && $dxchan && $dxchan->{spotsfilter}) {
402                                                 my ($gotone, undef) = $dxchan->{spotsfilter}->it(@r);
403                                                 next unless $gotone;
404                                         }
405                                         if (&$ecode(\@r)) {
406                                                 ++$count;
407                                                 next if $count < $from;
408                                                 if ($readback) {
409                                                         push @out, \@r;
410                                                         last if $count >= $to;
411                                                 } else {
412                                                         push @out, \@r;
413                                                         shift @out if $count >= $to;
414                                                 }
415                                         }
416                                 }
417                                 dbg("Spot::search file recs read: $rec") if isdbg('search');
418                                 last if $count >= $to; # stop after to
419                         }
420                 }
421         }
422         return ("Spot search error", $@) if $@;
423
424         @out = sort {$b->[2] <=> $a->[2]} @out if @out;
425         return @out;
426 }
427
428 # change a freq range->regular expression
429 sub ftor
430 {
431         my ($a, $b) = @_;
432         return undef unless $a < $b;
433         $b--;
434         my $d = $b - $a;
435         my @a = split //, $a;
436         my @b = split //, $b;
437         my $out;
438         while (@b > @a) {
439                 $out .= shift @b;
440         }
441         while (@b) {
442                 my $aa = shift @a;
443                 my $bb = shift @b;
444                 if (@b < (length $d)) {
445                         $out .= '\\d';
446                 } elsif ($aa eq $bb) {
447                         $out .= $aa;
448                 } elsif ($aa < $bb) {
449                         $out .= "[$aa-$bb]";
450                 } else {
451                         $out .= "[0-$bb$aa-9]";
452                 }
453         }
454         return $out;
455 }
456
457 # format a spot for user output in list mode
458 sub formatl
459 {
460         my $t = ztime($_[3]);
461         my $d = cldate($_[3]);
462         my $spotter = "<$_[5]>";
463         my $comment = $_[4] || '';
464         $comment =~ s/\t+/ /g;
465         my $cl = length $comment;
466         my $s = sprintf "%9.1f %-11s %s %s", $_[1], $_[2], $d, $t;
467         my $width = ($_[0] ? $_[0] : 80) - length($spotter) - length($s) - 4;
468         
469         $comment = substr $comment, 0, $width if $cl > $width;
470         $comment .= ' ' x ($width-$cl) if $cl < $width;
471
472 #       return sprintf "%8.1f  %-11s %s %s  %-28.28s%7s>", $_[0], $_[1], $d, $t, ($_[3]||''), "<$_[4]" ;
473         return "$s $comment$spotter";
474 }
475
476 # enter the spot for dup checking and return true if it is already a dup
477 sub dup
478 {
479         my ($freq, $call, $d, $text, $by, $node) = @_; 
480
481         # dump if too old
482         return 2 if $d < $main::systime - $dupage;
483         
484         # turn the time into minutes (should be already but...)
485         $d = int ($d / 60);
486         $d *= 60;
487
488         # remove SSID or area
489         $by =~ s|[-/]\d+$||;
490         
491 #       $freq = sprintf "%.1f", $freq;       # normalise frequency
492         $freq = int $freq;       # normalise frequency
493         $call = substr($call, 0, $maxcalllth) if length $call > $maxcalllth;
494
495         chomp $text;
496         $text =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
497         $text = uc unpad($text);
498         my $otext = $text;
499 #       $text = Encode::encode("iso-8859-1", $text) if $main::can_encode && Encode::is_utf8($text, 1);
500         $text =~ s/^\+\w+\s*//;                 # remove leading LoTW callsign
501         $text =~ s/\s{2,}[\dA-Z]?[A-Z]\d?$// if length $text > 24;
502         $text =~ s/[\W\x00-\x2F\x7B-\xFF]//g; # tautology, just to make quite sure!
503         $text = substr($text, 0, $duplth) if length $text > $duplth; 
504         my $ldupkey = "X$|$call|$by|$node|$freq|$d|$text";
505         my $t = DXDupe::find($ldupkey);
506         return 1 if $t && $t - $main::systime > 0;
507         
508         DXDupe::add($ldupkey, $main::systime+$dupage);
509         $otext = substr($otext, 0, $duplth) if length $otext > $duplth; 
510         $otext =~ s/\s+$//;
511         if (length $otext && $otext ne $text) {
512                 $ldupkey = "X$freq|$call|$by|$otext";
513                 $t = DXDupe::find($ldupkey);
514                 return 1 if $t && $t - $main::systime > 0;
515                 DXDupe::add($ldupkey, $main::systime+$dupage);
516         }
517         return undef;
518 }
519
520 sub listdups
521 {
522         return DXDupe::listdups('X', $dupage, @_);
523 }
524
525 sub genstats
526 {
527         my $date = shift;
528         my $in = $fp->open($date) or dbg("Spot::genstats: Cannot open " . $fp->fn($date) . " $!");
529         my $out = $statp->open($date, 'w') or dbg("Spot::genstats: Cannot open " . $statp->fn($date) . " $!");
530         my @freq;
531         my %list;
532         my @tot;
533         
534         if ($in && $out) {
535                 my $i = 0;
536                 @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);
537                 while (<$in>) {
538                         chomp;
539                         my ($freq, $by, $dxcc) = (split /\^/)[0,4,6];
540                         my $ref = $list{$by} || [0, $dxcc];
541                         for (@freq) {
542                                 next unless defined $_;
543                                 if ($freq >= $_->[1] && $freq <= $_->[2]) {
544                                         $$ref[$_->[0]+2]++;
545                                         $tot[$_->[0]+2]++;
546                                         $$ref[0]++;
547                                         $tot[0]++;
548                                         $list{$by} = $ref;
549                                         last;
550                                 }
551                         }
552                 }
553
554                 for ($i = 0; $i < @freq+2; $i++) {
555                         $tot[$i] ||= 0;
556                 }
557                 $statp->write($date, join('^', 'TOTALS', @tot));
558
559                 for (sort {$list{$b}->[0] <=> $list{$a}->[0]} keys %list) {
560                         my $ref = $list{$_};
561                         my $call = $_;
562                         for ($i = 0; $i < @freq+2; ++$i) {
563                                 $ref->[$i] ||= 0;
564                         }
565                         $statp->write($date, join('^', $call, @$ref));
566                 }
567                 $statp->close;
568         }
569 }
570
571 # return true if the stat file is newer than than the spot file
572 sub checkstats
573 {
574         my $date = shift;
575         my $in = $fp->mtime($date);
576         my $out = $statp->mtime($date);
577         return defined $out && defined $in && $out >= $in;
578 }
579
580 # daily processing
581 sub daily
582 {
583         my $date = Julian::Day->new($main::systime)->sub(1);
584         genstats($date) unless checkstats($date);
585         clean_cache();
586 }
587
588 sub _cachek
589 {
590         return "$_[0]->[0]|$_[0]->[1]";
591 }
592
593 sub clean_cache
594 {
595         if ($spotcachedays > 0) {
596                 my $now = Julian::Day->new($main::systime);
597                 for (my $i = $spotcachedays; $i < $spotcachedays + 5; ++$i ) {
598                         my $k = _cachek($now->sub($i));
599                         if (exists $spotcache{$k}) {
600                                 dbg("Spot::spotcache deleting day $k, more than $spotcachedays days old");
601                                 delete $spotcache{$k};
602                         }
603                 }
604         }
605 }
606 1;
607
608
609
610