]> gitweb.factorcode.org Git - factor.git/blob - extra/google/search/search.factor
ba1d396119d2af2c071743e0c2779ca41190fef4
[factor.git] / extra / google / search / search.factor
1 ! Copyright (C) 2011 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
4 USING: accessors assocs.extras classes.tuple colors combinators
5 formatting http.client io io.styles json.reader kernel sequences
6 urls wrap.strings ;
7
8 IN: google.search
9
10 <PRIVATE
11
12 : search-url ( query -- url )
13     URL" http://ajax.googleapis.com/ajax/services/search/web" clone
14         "1.0" "v" set-query-param
15         swap "q" set-query-param
16         "8" "rsz" set-query-param
17         "0" "start" set-query-param ;
18
19 TUPLE: search-result cacheUrl GsearchResultClass visibleUrl
20 title content unescapedUrl url titleNoFormatting fileFormat ;
21
22 PRIVATE>
23
24 : google-search ( query -- results )
25     search-url http-get nip json>
26     { "responseData" "results" } deep-at
27     [ \ search-result from-slots ] map ;
28
29 <PRIVATE
30
31 : write-heading ( str -- )
32     H{
33         { font-size 14 }
34         { background COLOR: light-gray }
35     } format nl ;
36
37 : write-title ( str -- )
38     H{
39         { foreground COLOR: blue }
40     } format nl ;
41
42 : write-content ( str -- )
43     60 wrap-string print ;
44
45 : write-url ( str -- )
46     dup >url H{
47         { font-name "monospace" }
48         { foreground COLOR: dark-green }
49     } [ write-object ] with-style nl ;
50
51 PRIVATE>
52
53 : google-search. ( query -- )
54     [ "Search results for '%s'" sprintf write-heading nl ]
55     [ google-search ] bi [
56         {
57             [ titleNoFormatting>> write-title ]
58             [ content>> write-content ]
59             [ unescapedUrl>> write-url ]
60         } cleave nl
61     ] each ;