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