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