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