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