2008-07-13 20:50:37 -04:00
|
|
|
! Copyright (C) 2008 Slava Pestov.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2014-02-09 14:00:38 -05:00
|
|
|
USING: accessors arrays assocs combinators combinators.smart csv
|
|
|
|
grouping http.client interval-maps io.encodings.ascii io.files
|
|
|
|
io.files.temp io.launcher io.pathnames ip-parser kernel math
|
|
|
|
math.parser memoize sequences strings ;
|
2008-05-05 19:07:18 -04:00
|
|
|
IN: geo-ip
|
|
|
|
|
2012-03-31 17:49:43 -04:00
|
|
|
: db-path ( -- path ) "IpToCountry.csv" cache-file ;
|
2008-05-05 19:07:18 -04:00
|
|
|
|
2010-09-06 19:47:12 -04:00
|
|
|
CONSTANT: db-url "http://software77.net/geo-ip/?DL=1"
|
2008-05-05 19:07:18 -04:00
|
|
|
|
|
|
|
: download-db ( -- path )
|
|
|
|
db-path dup exists? [
|
|
|
|
db-url over ".gz" append download-to
|
2009-10-28 18:25:50 -04:00
|
|
|
{ "gunzip" } over ".gz" append absolute-path suffix try-process
|
2008-05-05 19:07:18 -04:00
|
|
|
] unless ;
|
|
|
|
|
|
|
|
TUPLE: ip-entry from to registry assigned city cntry country ;
|
|
|
|
|
|
|
|
: parse-ip-entry ( row -- ip-entry )
|
2009-01-08 18:53:48 -05:00
|
|
|
[
|
|
|
|
{
|
|
|
|
[ string>number ]
|
|
|
|
[ string>number ]
|
|
|
|
[ ]
|
|
|
|
[ ]
|
|
|
|
[ ]
|
|
|
|
[ ]
|
|
|
|
[ ]
|
|
|
|
} spread
|
|
|
|
] input<sequence ip-entry boa ;
|
2008-05-05 19:07:18 -04:00
|
|
|
|
|
|
|
MEMO: ip-db ( -- seq )
|
|
|
|
download-db ascii file-lines
|
2015-05-12 21:50:34 -04:00
|
|
|
[ "#" head? ] reject "\n" join string>csv
|
2008-05-05 19:07:18 -04:00
|
|
|
[ parse-ip-entry ] map ;
|
|
|
|
|
2008-06-11 19:54:03 -04:00
|
|
|
: filter-overlaps ( alist -- alist' )
|
|
|
|
2 clump
|
|
|
|
[ first2 [ first second ] [ first first ] bi* < ] filter
|
2010-05-17 23:20:46 -04:00
|
|
|
keys ;
|
2008-06-11 19:54:03 -04:00
|
|
|
|
2008-05-05 19:07:18 -04:00
|
|
|
MEMO: ip-intervals ( -- interval-map )
|
2008-06-11 19:54:03 -04:00
|
|
|
ip-db [ [ [ from>> ] [ to>> ] bi 2array ] keep ] { } map>assoc
|
|
|
|
filter-overlaps <interval-map> ;
|
2008-05-05 19:07:18 -04:00
|
|
|
|
|
|
|
GENERIC: lookup-ip ( ip -- ip-entry )
|
|
|
|
|
2014-02-09 14:00:38 -05:00
|
|
|
M: string lookup-ip ipv4-aton lookup-ip ;
|
2008-05-05 19:07:18 -04:00
|
|
|
|
|
|
|
M: integer lookup-ip ip-intervals interval-at ;
|