slightly modified specially for ARC
[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
108 sub prefix
109 {
110         return $fp->{prefix};
111 }
112
113 # fix up the full spot data from the basic spot data
114 sub prepare
115 {
116         # $freq, $call, $t, $comment, $spotter = @_
117         my @out = @_[0..4];      # just up to the spotter
118
119         # normalise frequency
120         $_[0] = sprintf "%.1f", $_[0];
121   
122         # remove ssids and /xxx if present on spotter
123         $out[4] =~ s/-\d+$//o;
124
125         # remove leading and trailing spaces
126         $_[3] = unpad($_[3]);
127         
128         
129         # add the 'dxcc' country on the end for both spotted and spotter, then the cluster call
130         my @spd = Prefix::cty_data($out[1]);
131         push @out, $spd[0];
132         my @spt = Prefix::cty_data($out[4]);
133         push @out, $spt[0];
134         push @out, $_[5];
135         return (@out, @spd[1,2], @spt[1,2], $spd[3], $spt[3]);
136 }
137
138 sub add
139 {
140         my $buf = join('^', @_);
141         $fp->writeunix($_[2], $buf);
142         $totalspots++;
143         if ($_[0] <= 30000) {
144                 $hfspots++;
145         } else {
146                 $vhfspots++;
147         }
148         if ($_[3] =~ /(?:QSL|VIA)/i) {
149                 my $q = QSL::get($_[1]) || new QSL $_[1];
150                 $q->update($_[3], $_[2], $_[4]);
151         }
152 }
153
154 # search the spot database for records based on the field no and an expression
155 # this returns a set of references to the spots
156 #
157 # the expression is a legal perl 'if' statement with the possible fields indicated
158 # by $f<n> where :-
159 #
160 #   $f0 = frequency
161 #   $f1 = call
162 #   $f2 = date in unix format
163 #   $f3 = comment
164 #   $f4 = spotter
165 #   $f5 = spotted dxcc country
166 #   $f6 = spotter dxcc country
167 #   $f7 = origin
168 #
169 #
170 # In addition you can specify a range of days, this means that it will start searching
171 # from <n> days less than today to <m> days less than today
172 #
173 # Also you can select a range of entries so normally you would get the 0th (latest) entry
174 # back to the 5th latest, you can specify a range from the <x>th to the <y>the oldest.
175 #
176 # This routine is designed to be called as Spot::search(..)
177 #
178
179 sub search
180 {
181         my ($expr, $dayfrom, $dayto, $from, $to, $hint, $dxchan) = @_;
182         my $eval;
183         my @out;
184         my $ref;
185         my $i;
186         my $count;
187         my $today = Julian::Day->new(time());
188         my $fromdate;
189         my $todate;
190
191         $dayfrom = 0 if !$dayfrom;
192         $dayto = $maxdays unless $dayto;
193         $dayto = $dayfrom + $maxdays if $dayto < $dayfrom;
194         $fromdate = $today->sub($dayfrom);
195         $todate = $fromdate->sub($dayto);
196         $from = 0 unless $from;
197         $to = $defaultspots unless $to;
198         $hint = $hint ? "next unless $hint" : "";
199         $expr = "1" unless $expr;
200         
201         $to = $from + $maxspots if $to - $from > $maxspots || $to - $from <= 0;
202
203         $expr =~ s/\$f(\d\d?)/\$ref->[$1]/g; # swap the letter n for the correct field name
204         #  $expr =~ s/\$f(\d)/\$spots[$1]/g;               # swap the letter n for the correct field name
205   
206         my $checkfilter;
207         $checkfilter = qq (
208                       if (\@s < 9) {
209                           my \@a = (Prefix::cty_data(\$s[1]))[1..3];
210                           my \@b = (Prefix::cty_data(\$s[4]))[1..3];
211                           push \@s, \@a[0,1], \@b[0,1], \$a[2], \$a[2];  
212                       } else {
213                           \$s[12] ||= ' ';
214                           \$s[13] ||= ' ';
215                       }
216                           my (\$filter, \$hops) = \$dxchan->{spotsfilter}->it(\@s);
217                           next unless (\$filter);
218                       ) if $dxchan;
219         $checkfilter ||= ' ';
220         
221         dbg("hint='$hint', expr='$expr', spotno=$from-$to, day=$dayfrom-$dayto\n") if isdbg('search');
222   
223         # build up eval to execute
224         $eval = qq(
225                            while (<\$fh>) {
226                                    $hint;
227                                    chomp;
228                                    my \@s = split /\\^/;
229                    $checkfilter;
230                    push \@spots, \\\@s;
231                            }
232                            my \$c;
233                            my \$ref;
234                            for (\$c = \$#spots; \$c >= 0; \$c--) {
235                                         \$ref = \$spots[\$c];
236                                         if ($expr) {
237                                                 \$count++;
238                                                 next if \$count < \$from; # wait until from 
239                                                 push(\@out, \$ref);
240                                                 last if \$count >= \$to; # stop after to
241                                         }
242                                 }
243                           );
244     
245         dbg("Spot eval: $eval") if isdbg('searcheval');
246         
247
248         $fp->close;                                     # close any open files
249
250         for ($i = $count = 0; $i < $maxdays; ++$i) {    # look thru $maxdays worth of files only
251                 my $now = $fromdate->sub($i); # but you can pick which $maxdays worth
252                 last if $now->cmp($todate) <= 0;         
253         
254                 my @spots = ();
255                 my $fh = $fp->open($now); # get the next file
256                 if ($fh) {
257                         my $in;
258                         eval $eval;                     # do the search on this file
259                         last if $count >= $to; # stop after to
260                         return ("Spot search error", $@) if $@;
261                 }
262         }
263
264         return @out;
265 }
266
267 # change a freq range->regular expression
268 sub ftor
269 {
270         my ($a, $b) = @_;
271         return undef unless $a < $b;
272         $b--;
273         my $d = $b - $a;
274         my @a = split //, $a;
275         my @b = split //, $b;
276         my $out;
277         while (@b > @a) {
278                 $out .= shift @b;
279         }
280         while (@b) {
281                 my $aa = shift @a;
282                 my $bb = shift @b;
283                 if (@b < (length $d)) {
284                         $out .= '\\d';
285                 } elsif ($aa eq $bb) {
286                         $out .= $aa;
287                 } elsif ($aa < $bb) {
288                         $out .= "[$aa-$bb]";
289                 } else {
290                         $out .= "[0-$bb$aa-9]";
291                 }
292         }
293         return $out;
294 }
295
296 # format a spot for user output in list mode
297 sub formatl
298 {
299         my $t = ztime($_[2]);
300         my $d = cldate($_[2]);
301         return sprintf "%8.1f  %-11s %s %s  %-28.28s%7s>", $_[0], $_[1], $d, $t, $_[3], "<$_[4]" ;
302 }
303
304 #
305 # return all the spots from a day's file as an array of references
306 # the parameter passed is a julian day
307 sub readfile($)
308 {
309         my @spots;
310         
311         my $fh = $fp->open(shift); 
312         if ($fh) {
313                 my $in;
314                 while (<$fh>) {
315                         chomp;
316                         push @spots, [ split '\^' ];
317                 }
318         }
319         return @spots;
320 }
321
322 # enter the spot for dup checking and return true if it is already a dup
323 sub dup
324 {
325         my ($freq, $call, $d, $text, $by, $cty) = @_; 
326
327         # dump if too old
328         return 2 if $d < $main::systime - $dupage;
329         
330         # turn the time into minutes (should be already but...)
331         $d = int ($d / 60);
332         $d *= 60;
333
334         # remove SSID or area
335         $by =~ s|[-/]\d+$||;
336         
337         $freq = sprintf "%.1f", $freq;       # normalise frequency
338         $call = substr($call, 0, $maxcalllth) if length $call > $maxcalllth;
339
340         chomp $text;
341         $text =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
342         $text = uc unpad($text);
343         if ($cty && $text && length $text <= 4) {
344                 unless ($text =~ /^C?Q/ || $text =~ /^\d+$/) {
345                         my @try = Prefix::cty_data($text);
346                         $text = "" if $cty == $try[0];
347                 }
348         }
349         my $otext = $text;
350         $text = pack("C*", map {$_ & 127} unpack("C*", $text));
351         $text =~ s/\s{2,}[\dA-Z]?[A-Z]\d?$// if length $text > 24;
352         $text =~ s/[^\w]//g;
353         $text = substr($text, 0, $duplth) if length $text > $duplth; 
354         my $ldupkey = "X$freq|$call|$by|$text";
355         my $t = DXDupe::find($ldupkey);
356         return 1 if $t && $t - $main::systime > 0;
357         DXDupe::add($ldupkey, $main::systime+$dupage);
358         $otext = substr($otext, 0, $duplth) if length $otext > $duplth; 
359         $otext =~ s/\s+$//;
360         if (length $otext && $otext ne $text) {
361                 $ldupkey = "X$freq|$call|$by|$otext";
362                 $t = DXDupe::find($ldupkey);
363                 return 1 if $t && $t - $main::systime > 0;
364                 DXDupe::add($ldupkey, $main::systime+$dupage);
365         }
366         return 0;
367 }
368
369 sub listdups
370 {
371         return DXDupe::listdups('X', $dupage, @_);
372 }
373
374 sub genstats($)
375 {
376         my $date = shift;
377         my $in = $fp->open($date);
378         my $out = $statp->open($date, 'w');
379         my @freq;
380         my %list;
381         my @tot;
382         
383         if ($in && $out) {
384                 my $i = 0;
385                 @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);
386                 while (<$in>) {
387                         chomp;
388                         my ($freq, $by, $dxcc) = (split /\^/)[0,4,6];
389                         my $ref = $list{$by} || [0, $dxcc];
390                         for (@freq) {
391                                 next unless defined $_;
392                                 if ($freq >= $_->[1] && $freq <= $_->[2]) {
393                                         $$ref[$_->[0]+2]++;
394                                         $tot[$_->[0]+2]++;
395                                         $$ref[0]++;
396                                         $tot[0]++;
397                                         $list{$by} = $ref;
398                                         last;
399                                 }
400                         }
401                 }
402
403                 for ($i = 0; $i < @freq+2; $i++) {
404                         $tot[$i] ||= 0;
405                 }
406                 $statp->write($date, join('^', 'TOTALS', @tot));
407
408                 for (sort {$list{$b}->[0] <=> $list{$a}->[0]} keys %list) {
409                         my $ref = $list{$_};
410                         my $call = $_;
411                         for ($i = 0; $i < @freq+2; ++$i) {
412                                 $ref->[$i] ||= 0;
413                         }
414                         $statp->write($date, join('^', $call, @$ref));
415                 }
416                 $statp->close;
417         }
418 }
419
420 # return true if the stat file is newer than than the spot file
421 sub checkstats($)
422 {
423         my $date = shift;
424         my $in = $fp->mtime($date);
425         my $out = $statp->mtime($date);
426         return defined $out && defined $in && $out >= $in;
427 }
428
429 # daily processing
430 sub daily
431 {
432         my $date = Julian::Day->new($main::systime)->sub(1);
433         genstats($date) unless checkstats($date);
434 }
435 1;
436
437
438
439