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