44cb5728142df950fef391f8a31239fb8580c7b9
[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 );
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 = 3*3600;               # the length of time to hold spot dups
40 $filterdef = bless ([
41                           # tag, sort, field, priv, special parser 
42                           ['freq', 'r', 0, 0, \&decodefreq],
43                           ['on', 'r', 0, 0, \&decodefreq],
44                           ['call', 'c', 1],
45                           ['info', 't', 3],
46                           ['by', 'c', 4],
47                           ['call_dxcc', 'nc', 5],
48                           ['by_dxcc', 'nc', 6],
49                           ['origin', 'c', 7, 9],
50                           ['call_itu', 'ni', 8],
51                           ['call_zone', 'nz', 9],
52                           ['by_itu', 'ni', 10],
53                           ['by_zone', 'nz', 11],
54                           ['call_state', 'ns', 12],
55                           ['by_state', 'ns', 13],
56                           ['channel', 'c', 14],
57                                          
58                          ], 'Filter::Cmd');
59 $totalspots = $hfspots = $vhfspots = 0;
60
61 # create a Spot Object
62 sub new
63 {
64         my $class = shift;
65         my $self = [ @_ ];
66         return bless $self, $class;
67 }
68
69 sub decodefreq
70 {
71         my $dxchan = shift;
72         my $l = shift;
73         my @f = split /,/, $l;
74         my @out;
75         my $f;
76         
77         foreach $f (@f) {
78                 my ($a, $b); 
79                 if (m{^\d+/\d+$}) {
80                         push @out, $f;
81                 } elsif (($a, $b) = $f =~ m{^(\w+)(?:/(\w+))?$}) {
82                         $b = lc $b if $b;
83                         my @fr = Bands::get_freq(lc $a, $b);
84                         if (@fr) {
85                                 while (@fr) {
86                                         $a = shift @fr;
87                                         $b = shift @fr;
88                                         push @out, "$a/$b";  # add them as ranges
89                                 }
90                         } else {
91                                 return ('dfreq', $dxchan->msg('dfreq1', $f));
92                         }
93                 } else {
94                         return ('dfreq', $dxchan->msg('e20', $f));
95                 }
96         }
97         return (0, join(',', @out));                     
98 }
99
100 sub init
101 {
102         mkdir "$dirprefix", 0777 if !-e "$dirprefix";
103         $fp = DXLog::new($dirprefix, "dat", 'd');
104         $statp = DXLog::new($dirprefix, "dys", 'd');
105         my $rm = $main::is_win ? 'del' : 'rm -f';
106         system("$rm $main::data/$dirprefix/*/*.bys");
107         system("$rm $main::data/$dirprefix/*/*.cys");
108 }
109
110 sub prefix
111 {
112         return $fp->{prefix};
113 }
114
115 # fix up the full spot data from the basic spot data
116 sub prepare
117 {
118         # $freq, $call, $t, $comment, $spotter = @_
119         my @out = @_[0..4];      # just up to the spotter
120
121         # normalise frequency
122         $_[0] = sprintf "%.1f", $_[0];
123   
124         # remove ssids and /xxx if present on spotter
125         $out[4] =~ s/-\d+$//o;
126         $out[4] =~ s|/\w+$||o;
127
128         # remove leading and trailing spaces
129         $_[3] = unpad($_[3]);
130         
131         
132         # add the 'dxcc' country on the end for both spotted and spotter, then the cluster call
133         my @spd = Prefix::cty_data($out[1]);
134         push @out, $spd[0];
135         my @spt = Prefix::cty_data($out[4]);
136         push @out, $spt[0];
137         push @out, $_[5];
138         return (@out, @spd[1,2], @spt[1,2], $spd[3], $spt[3]);
139 }
140
141 sub add
142 {
143         my $buf = join("\^", @_);
144         $fp->writeunix($_[2], $buf);
145         $totalspots++;
146         if ($_[0] <= 30000) {
147                 $hfspots++;
148         } else {
149                 $vhfspots++;
150         }
151         if ($_[3] =~ /(?:QSL|VIA)/i) {
152                 my $q = QSL::get($_[1]) || new QSL $_[1];
153                 $q->update($_[3], $_[2], $_[4]);
154         }
155 }
156
157 # search the spot database for records based on the field no and an expression
158 # this returns a set of references to the spots
159 #
160 # the expression is a legal perl 'if' statement with the possible fields indicated
161 # by $f<n> where :-
162 #
163 #   $f0 = frequency
164 #   $f1 = call
165 #   $f2 = date in unix format
166 #   $f3 = comment
167 #   $f4 = spotter
168 #   $f5 = spotted dxcc country
169 #   $f6 = spotter dxcc country
170 #   $f7 = origin
171 #
172 #
173 # In addition you can specify a range of days, this means that it will start searching
174 # from <n> days less than today to <m> days less than today
175 #
176 # Also you can select a range of entries so normally you would get the 0th (latest) entry
177 # back to the 5th latest, you can specify a range from the <x>th to the <y>the oldest.
178 #
179 # This routine is designed to be called as Spot::search(..)
180 #
181
182 sub search
183 {
184         my ($expr, $dayfrom, $dayto, $from, $to, $hint, $dxchan) = @_;
185         my $eval;
186         my @out;
187         my $ref;
188         my $i;
189         my $count;
190         my $today = Julian::Day->new(time());
191         my $fromdate;
192         my $todate;
193
194         $dayfrom = 0 if !$dayfrom;
195         $dayto = $maxdays unless $dayto;
196         $dayto = $dayfrom + $maxdays if $dayto < $dayfrom;
197         $fromdate = $today->sub($dayfrom);
198         $todate = $fromdate->sub($dayto);
199         $from = 0 unless $from;
200         $to = $defaultspots unless $to;
201         $hint = $hint ? "next unless $hint" : "";
202         $expr = "1" unless $expr;
203         
204         $to = $from + $maxspots if $to - $from > $maxspots || $to - $from <= 0;
205
206         $expr =~ s/\$f(\d\d?)/\$ref->[$1]/g; # swap the letter n for the correct field name
207         #  $expr =~ s/\$f(\d)/\$spots[$1]/g;               # swap the letter n for the correct field name
208   
209         my $checkfilter;
210         $checkfilter = qq (
211                       if (\@s < 9) {
212                           my \@a = (Prefix::cty_data(\$s[1]))[1..3];
213                           my \@b = (Prefix::cty_data(\$s[4]))[1..3];
214                           push \@s, \@a[0,1], \@b[0,1], \$a[2], \$a[2];  
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) = @_; 
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         $freq = sprintf "%.1f", $freq;       # normalise frequency
335         $call = substr($call, 0, 12) if length $call > 12;
336
337         # quick test now for simple case
338         my $sdupkey = "X$freq|$call|$d|$by";
339         return 1 if DXDupe::find($sdupkey);
340         
341         chomp $text;
342         $text =~ s/\%([0-9A-F][0-9A-F])/chr(hex($1))/eg;
343         $text = substr($text, 0, $duplth) if length $text > $duplth; 
344         unpad($text);
345         $text = pack("C*", map {$_ & 127} unpack("C*", $text));
346         $text =~ s/[^a-zA-Z0-9]//g;
347         for (-60, -120, -180, -240, 0, 60, 120, 180, 240, 300) {
348                 my $dt = $d - $_;
349                 my $ldupkey = "X$freq|$call|$dt|\L$text";
350                 my $sdupkey = "X$freq|$call|$dt|$by";
351                 return 1 if DXDupe::find($ldupkey) || DXDupe::find($sdupkey);
352         }
353         my $ldupkey = "X$freq|$call|$d|\L$text";
354         $sdupkey = "X$freq|$call|$d|$by";
355         DXDupe::add($ldupkey, $main::systime+$dupage);
356         DXDupe::add($sdupkey, $main::systime+$dupage);
357         return 0;
358 }
359
360 sub listdups
361 {
362         return DXDupe::listdups('X', $dupage, @_);
363 }
364
365 sub genstats($)
366 {
367         my $date = shift;
368         my $in = $fp->open($date);
369         my $out = $statp->open($date, 'w');
370         my @freq;
371         my %list;
372         my @tot;
373         
374         if ($in && $out) {
375                 my $i = 0;
376                 @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);
377                 while (<$in>) {
378                         chomp;
379                         my ($freq, $by, $dxcc) = (split /\^/)[0,4,6];
380                         my $ref = $list{$by} || [0, $dxcc];
381                         for (@freq) {
382                                 next unless defined $_;
383                                 if ($freq >= $_->[1] && $freq <= $_->[2]) {
384                                         $$ref[$_->[0]+2]++;
385                                         $tot[$_->[0]+2]++;
386                                         $$ref[0]++;
387                                         $tot[0]++;
388                                         $list{$by} = $ref;
389                                         last;
390                                 }
391                         }
392                 }
393
394                 for ($i = 0; $i < @freq+2; $i++) {
395                         $tot[$i] ||= 0;
396                 }
397                 $statp->write($date, join('^', 'TOTALS', @tot));
398
399                 for (sort {$list{$b}->[0] <=> $list{$a}->[0]} keys %list) {
400                         my $ref = $list{$_};
401                         my $call = $_;
402                         for ($i = 0; $i < @freq+2; ++$i) {
403                                 $ref->[$i] ||= 0;
404                         }
405                         $statp->write($date, join('^', $call, @$ref));
406                 }
407                 $statp->close;
408         }
409 }
410
411 # return true if the stat file is newer than than the spot file
412 sub checkstats($)
413 {
414         my $date = shift;
415         my $in = $fp->mtime($date);
416         my $out = $statp->mtime($date);
417         return defined $out && defined $in && $out >= $in;
418 }
419
420 # daily processing
421 sub daily
422 {
423         my $date = Julian::Day->new($main::systime)->sub(1);
424         genstats($date) unless checkstats($date);
425 }
426 1;
427
428
429
430