1 USING: kernel sequences io.files io.launcher io.encodings.ascii
2 io.streams.string http.client sequences.lib combinators
3 math.parser math.vectors math.intervals interval-maps memoize
4 csv accessors assocs strings math splitting grouping arrays ;
7 : db-path ( -- path ) "IpToCountry.csv" temp-file ;
9 : db-url ( -- url ) "http://software77.net/cgi-bin/ip-country/geo-ip.pl?action=download" ;
11 : download-db ( -- path )
13 db-url over ".gz" append download-to
14 { "gunzip" } over ".gz" append (normalize-path) suffix try-process
17 TUPLE: ip-entry from to registry assigned city cntry country ;
19 : parse-ip-entry ( row -- ip-entry )
28 } spread ip-entry boa ;
30 MEMO: ip-db ( -- seq )
31 download-db ascii file-lines
32 [ "#" head? not ] filter "\n" join <string-reader> csv
33 [ parse-ip-entry ] map ;
35 : filter-overlaps ( alist -- alist' )
37 [ first2 [ first second ] [ first first ] bi* < ] filter
40 MEMO: ip-intervals ( -- interval-map )
41 ip-db [ [ [ from>> ] [ to>> ] bi 2array ] keep ] { } map>assoc
42 filter-overlaps <interval-map> ;
44 GENERIC: lookup-ip ( ip -- ip-entry )
47 "." split [ string>number ] map
48 { HEX: 1000000 HEX: 10000 HEX: 100 HEX: 1 } v.
51 M: integer lookup-ip ip-intervals interval-at ;