1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences io.files io.launcher io.encodings.ascii
4 io.streams.string http.client generalizations combinators
5 math.parser math.vectors math.intervals interval-maps memoize
6 csv accessors assocs strings math splitting grouping arrays ;
9 : db-path ( -- path ) "IpToCountry.csv" temp-file ;
11 : db-url ( -- url ) "http://software77.net/cgi-bin/ip-country/geo-ip.pl?action=download" ;
13 : download-db ( -- path )
15 db-url over ".gz" append download-to
16 { "gunzip" } over ".gz" append (normalize-path) suffix try-process
19 TUPLE: ip-entry from to registry assigned city cntry country ;
21 : parse-ip-entry ( row -- ip-entry )
30 } spread ip-entry boa ;
32 MEMO: ip-db ( -- seq )
33 download-db ascii file-lines
34 [ "#" head? not ] filter "\n" join <string-reader> csv
35 [ parse-ip-entry ] map ;
37 : filter-overlaps ( alist -- alist' )
39 [ first2 [ first second ] [ first first ] bi* < ] filter
42 MEMO: ip-intervals ( -- interval-map )
43 ip-db [ [ [ from>> ] [ to>> ] bi 2array ] keep ] { } map>assoc
44 filter-overlaps <interval-map> ;
46 GENERIC: lookup-ip ( ip -- ip-entry )
49 "." split [ string>number ] map
50 { HEX: 1000000 HEX: 10000 HEX: 100 HEX: 1 } v.
53 M: integer lookup-ip ip-intervals interval-at ;