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