factor/extra/geo-ip/geo-ip.factor

56 lines
1.5 KiB
Factor
Raw Normal View History

! Copyright (C) 2008 Slava Pestov.
! See http://factorcode.org/license.txt for BSD license.
2013-03-15 11:26:01 -04: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 kernel math
math.parser math.vectors memoize sequences splitting strings ;
2008-05-05 19:07:18 -04:00
IN: geo-ip
: 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
{ "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
2013-03-15 11:26:01 -04:00
[ "#" head? not ] filter "\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 )
M: string lookup-ip
"." split [ string>number ] map
2011-11-23 21:49:33 -05:00
{ 0x1000000 0x10000 0x100 0x1 } v.
2008-05-05 19:07:18 -04:00
lookup-ip ;
M: integer lookup-ip ip-intervals interval-at ;