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