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