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