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