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