]> gitweb.factorcode.org Git - factor.git/blob - extra/geo-ip/geo-ip.factor
Merge branch 'master' into new_ui
[factor.git] / extra / geo-ip / geo-ip.factor
1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences io.files io.files.temp io.launcher
4 io.pathnames io.encodings.ascii io.streams.string http.client
5 generalizations combinators math.parser math.vectors
6 math.intervals interval-maps memoize csv accessors assocs
7 strings math splitting grouping arrays ;
8 IN: geo-ip
9
10 : db-path ( -- path ) "IpToCountry.csv" temp-file ;
11
12 : db-url ( -- url ) "http://software77.net/cgi-bin/ip-country/geo-ip.pl?action=download" ;
13
14 : download-db ( -- path )
15     db-path dup exists? [
16         db-url over ".gz" append download-to
17         { "gunzip" } over ".gz" append (normalize-path) suffix try-process
18     ] unless ;
19
20 TUPLE: ip-entry from to registry assigned city cntry country ;
21
22 : parse-ip-entry ( row -- ip-entry )
23     7 firstn {
24         [ string>number ]
25         [ string>number ]
26         [ ]
27         [ ]
28         [ ]
29         [ ]
30         [ ]
31     } spread ip-entry boa ;
32
33 MEMO: ip-db ( -- seq )
34     download-db ascii file-lines
35     [ "#" head? not ] filter "\n" join <string-reader> csv
36     [ parse-ip-entry ] map ;
37
38 : filter-overlaps ( alist -- alist' )
39     2 clump
40     [ first2 [ first second ] [ first first ] bi* < ] filter
41     [ first ] map ;
42
43 MEMO: ip-intervals ( -- interval-map )
44     ip-db [ [ [ from>> ] [ to>> ] bi 2array ] keep ] { } map>assoc
45     filter-overlaps <interval-map> ;
46
47 GENERIC: lookup-ip ( ip -- ip-entry )
48
49 M: string lookup-ip
50     "." split [ string>number ] map
51     { HEX: 1000000 HEX: 10000 HEX: 100 HEX: 1 } v.
52     lookup-ip ;
53
54 M: integer lookup-ip ip-intervals interval-at ;