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