ebc5d92c18279db5e0d7ecdf7ae9405567f05872
[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                         while ($now->cmp($today) <= 0) {
115                                 my $fh = $fp->open($now);
116                                 if ($fh) {
117 #                                       $main::dbh->{RaiseError} = 0;
118                                         $main::dbh->begin_work;
119                                         my $count = 0;
120                                         while (<$fh>) {
121                                                 chomp;
122                                                 my @s = split /\^/;
123                                                 if (@s < 14) {
124                                                         my @a = (Prefix::cty_data($s[1]))[1..3];
125                                                         my @b = (Prefix::cty_data($s[4]))[1..3];
126                                                         push @s, $b[1] if @s < 7;
127                                                         push @s, '' if @s < 8;
128                                                         push @s, @a[0,1], @b[0,1] if @s < 12;
129                                                         push @s,  $a[2], $b[2] if @s < 14;
130                                                 } 
131                                                 $main::dbh->spot_insert(\@s, $sth);
132                                                 $count++;
133                                         }
134                                         $main::dbh->commit;
135                                         dbg("inserted $count spots from $now->[0] $now->[1]");
136                                         $fh->close;
137                                         $total += $count;
138                                 }
139                                 $now = $now->add(1);
140                         }
141                         $main::dbh->begin_work;
142                         $main::dbh->spot_add_indexes;
143                         $main::dbh->commit;
144 #                       $main::dbh->{RaiseError} = 1;
145                         $t = time - $t;
146                         my $min = int($t / 60);
147                         my $sec = $t % 60;
148                         dbg("$total spots converted in $min:$sec");
149                 }
150                 unless ($main::dbh->has_ipaddr) {
151                         $main::dbh->add_ipaddr;
152                         dbg("added ipaddr field to spot table");
153                 }
154         }
155 }
156
157 sub prefix
158 {
159         return $fp->{prefix};
160 }
161
162 # fix up the full spot data from the basic spot data
163 sub prepare
164 {
165         # $freq, $call, $t, $comment, $spotter, node, ip address = @_
166         my @out = @_[0..4];      # just up to the spotter
167
168         # normalise frequency
169         $out[0] = sprintf "%.1f", $out[0];
170   
171         # remove ssids and /xxx if present on spotter
172         $out[4] =~ s/-\d+$//o;
173
174         # remove leading and trailing spaces
175         $out[3] = unpad($out[3]);
176         
177         
178         # add the 'dxcc' country on the end for both spotted and spotter, then the cluster call
179         my @spd = Prefix::cty_data($out[1]);
180         push @out, $spd[0];
181         my @spt = Prefix::cty_data($out[4]);
182         push @out, $spt[0];
183         push @out, $_[5];
184         push @out, @spd[1,2], @spt[1,2], $spd[3], $spt[3];
185         push @out, $_[6] if $_[6] && is_ipaddr($_[6]);
186
187         # thus we now have:
188         # 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
189         return @out;
190 }
191
192 sub add
193 {
194         my $buf = join('^', @_);
195         $fp->writeunix($_[2], $buf);
196         if ($main::dbh) {
197                 $main::dbh->begin_work;
198                 $main::dbh->spot_insert(\@_);
199                 $main::dbh->commit;
200         }
201         $totalspots++;
202         if ($_[0] <= 30000) {
203                 $hfspots++;
204         } else {
205                 $vhfspots++;
206         }
207         if ($_[3] =~ /(?:QSL|VIA)/i) {
208                 my $q = QSL::get($_[1]) || new QSL $_[1];
209                 $q->update($_[3], $_[2], $_[4]);
210         }
211 }
212
213 # search the spot database for records based on the field no and an expression
214 # this returns a set of references to the spots
215 #
216 # the expression is a legal perl 'if' statement with the possible fields indicated
217 # by $f<n> where :-
218 #
219 #   $f0 = frequency
220 #   $f1 = call
221 #   $f2 = date in unix format
222 #   $f3 = comment
223 #   $f4 = spotter
224 #   $f5 = spotted dxcc country
225 #   $f6 = spotter dxcc country
226 #   $f7 = origin
227 #
228 #
229 # In addition you can specify a range of days, this means that it will start searching
230 # from <n> days less than today to <m> days less than today
231 #
232 # Also you can select a range of entries so normally you would get the 0th (latest) entry
233 # back to the 5th latest, you can specify a range from the <x>th to the <y>the oldest.
234 #
235 # This routine is designed to be called as Spot::search(..)
236 #
237
238 sub search
239 {
240         my ($expr, $dayfrom, $dayto, $from, $to, $hint, $dxchan) = @_;
241         my $eval;
242         my @out;
243         my $ref;
244         my $i;
245         my $count;
246         my $today = Julian::Day->new(time());
247         my $fromdate;
248         my $todate;
249
250         $dayfrom = 0 if !$dayfrom;
251         $dayto = $maxdays unless $dayto;
252         $dayto = $dayfrom + $maxdays if $dayto < $dayfrom;
253         $fromdate = $today->sub($dayfrom);
254         $todate = $fromdate->sub($dayto);
255         $from = 0 unless $from;
256         $to = $defaultspots unless $to;
257         $hint = $hint ? "next unless $hint" : "";
258         $expr = "1" unless $expr;
259         
260         $to = $from + $maxspots if $to - $from > $maxspots || $to - $from <= 0;
261
262         if ($main::dbh && $use_db_for_search) {
263                 return $main::dbh->spot_search($expr, $dayfrom, $dayto, $to-$from, $dxchan);
264         }
265
266         $expr =~ s/\$f(\d\d?)/\$ref->[$1]/g; # swap the letter n for the correct field name
267         #  $expr =~ s/\$f(\d)/\$spots[$1]/g;               # swap the letter n for the correct field name
268   
269         my $checkfilter;
270         $checkfilter = qq (
271                       if (\@s < 9) {
272                           my \@a = (Prefix::cty_data(\$s[1]))[1..3];
273                           my \@b = (Prefix::cty_data(\$s[4]))[1..3];
274                           push \@s, \@a[0,1], \@b[0,1], \$a[2], \$a[2];  
275                       } else {
276                           \$s[12] ||= ' ';
277                           \$s[13] ||= ' ';
278                       }
279                           my (\$filter, \$hops) = \$dxchan->{spotsfilter}->it(\@s);
280                           next unless (\$filter);
281                       ) if $dxchan;
282         $checkfilter ||= ' ';
283         
284         dbg("hint='$hint', expr='$expr', spotno=$from-$to, day=$dayfrom-$dayto\n") if isdbg('search');
285   
286         # build up eval to execute
287         $eval = qq(
288                            while (<\$fh>) {
289                                    $hint;
290                                    chomp;
291                                    my \@s = split /\\^/;
292                    $checkfilter;
293                    push \@spots, \\\@s;
294                            }
295                            my \$c;
296                            my \$ref;
297                            for (\$c = \$#spots; \$c >= 0; \$c--) {
298                                         \$ref = \$spots[\$c];
299                                         if ($expr) {
300                                                 \$count++;
301                                                 next if \$count < \$from; # wait until from 
302                                                 push(\@out, \$ref);
303                                                 last if \$count >= \$to; # stop after to
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 $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