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