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