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