-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcc.R
executable file
·216 lines (177 loc) · 5.2 KB
/
cc.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env Rscript
suppressPackageStartupMessages({
library(argparser, quietly = TRUE)
library(magrittr, quietly = TRUE)
})
arg_parser(
description = 'Extract metadata of a specific target based on the results of "commoncrawl.org"
Examples:
$ ./cc.R --list # list indices
$ ./cc.R --domain github.com # defaults to most recent index
$ ./cc.R --domain github.com --out /tmp/gh.json # specify an oputput file
$ ./cc.R --index CC-MAIN-2018-34 --domain github.com # specify which index'
) %>%
add_argument(
arg = "--domain",
help = "domain which will be crawled",
type = "character",
short = "-d",
default = NA_character_
) %>%
add_argument(
arg = "--out",
help = "specify an output file (default: domain.json)",
type = "character",
short = "-o",
default = NA_character_
) %>%
add_argument(
arg = "--list",
help = "list all available indexes",
short = "-l",
flag = TRUE
) %>%
add_argument(
arg = "--index",
help = "use a specific index file",
type = "character",
short = "-i",
default = NA_character_
) -> parser
opts <- parse_args(parser)
if ((is.na(opts$domain)) & (!opts$list)) {
print(parser)
quit(save="no", 1)
}
suppressPackageStartupMessages({
library(xml2, quietly = TRUE)
library(httr, quietly = TRUE)
library(rvest, quietly = TRUE)
library(lubridate, quietly = TRUE)
library(jsonlite, quietly = TRUE)
library(tidyverse, quietly = TRUE)
})
cache_dir <- path.expand("~/.cc.R")
#' Setup the cache directory
#'
#' @md
#' @return nothing
setup_cache <- function() {
if (!dir.exists(cache_dir)) dir.create(path.expand(cache_dir))
}
#' Refresh the CC crawl index cache
#'
#' Possible side-effect of writing to the cache dir
#'
#' @md
#' @return data frame (`month`/`year`/`path`)
refresh_index_cache <- function() {
pg <- xml2::read_html("http://index.commoncrawl.org/")
rvest::html_nodes(pg, xpath = ".//td[1]/*/a") %>%
rvest::html_attr("href") -> idx_paths
rvest::html_nodes(pg, xpath = ".//td[2]") %>%
rvest::html_text(trim=TRUE) %>%
str_replace(" Index", "") %>%
str_split(" ") %>%
purrr::map(set_names, c("month", "year")) %>%
map_df(as.list) %>%
mutate(path = idx_paths) -> idx
readr::write_rds(idx, file.path(cache_dir, "indexes.rds"))
}
#' Fetch cached or current CC crawl index paths
#'
#' @md
#' @return data frame (`month`/`year`/`path`)
fetch_indexes <- function() {
if (!file.exists(file.path(cache_dir, "indexes.rds"))) {
return(refresh_index_cache())
}
idx <- readr::read_rds(file.path(cache_dir, "indexes.rds"))
dplyr::filter(
idx,
month == as.character(lubridate::month(Sys.Date(), abbr=FALSE, label=TRUE)),
year == lubridate::year(Sys.Date())
) %>%
nrow() -> has_this_month
if ((!has_this_month) & (lubridate::day(Sys.Date()) > 25)) {
return(refresh_index_cache())
} else {
return(idx)
}
}
#' Retrieve domain CDX metadata from CC index
#'
#' @md
#' @param domain domain name
#' @param index CC index file
#' @param page API page #
#' @return data frame (CDX)
get_data <- function(domain, index, page) {
httr::GET(
url = file.path("http://index.commoncrawl.org", glue::glue("{index}-index")),
query = list(
url = glue::glue("*.{domain}"),
output = "json",
page = page
)
) -> res
httr::stop_for_status(res)
httr::content(res, as="raw", encoding="UTF-8") %>%
rawConnection() -> rcon
on.exit(close(rcon), add=TRUE)
out <- jsonlite::stream_in(rcon, verbose = FALSE)
out
}
#' Grab all the URL data from the CC for a given index and omain
#'
#' @md
#' @param domain domain name
#' @param index CC index file
#' @return data frame (CDX)
crawl_index <- function(domain, index) {
httr::GET(
url = file.path("http://index.commoncrawl.org", glue::glue("{index}-index")),
query = list(
url = glue::glue("*.{domain}"),
output = "json",
showNumPages = TRUE
)
) -> res
httr::stop_for_status(res)
meta <- httr::content(res, as="text", encoding="UTF-8")
meta <- jsonlite::fromJSON(meta)
purrr::map_df(
0:(meta$pages-1), get_data, domain=domain, index=index
) %>%
tbl_df() -> out
}
#' List the available CC crawl indices
#'
#' Side-effect of output to stdout
#'
#' @md
#' @return indices (invisibly)
list_indexes <- function() {
dplyr::select(fetch_indexes(), year, month, path) %>%
data.frame() -> tmp
print(tmp[nrow(tmp):1,], row.names = FALSE, quote = FALSE)
invisible(tmp)
}
setup_cache()
if (opts$list) { # just list the indexes (will prime, cache and auto-update)
list_indexes()
} else if (!is.na(opts$index)) { # use a specific index
idx <- fetch_indexes()
if (!(gsub("^/", "", opts$index) %in% gsub("^/", "", idx$path))) {
stop("Index does not exist", call.=FALSE)
}
out <- crawl_index(opts$domain, opts$index)
where <- if (is.na(opts$out)) stdout() else file(path.expand(opts$out))
jsonlite::stream_out(out, where, verbose=FALSE)
} else { # use latest index
idx <- fetch_indexes()
out <- crawl_index(opts$domain, idx$path[1])
where <- if (is.na(opts$out)) stdout() else file(path.expand(opts$out))
jsonlite::stream_out(out, where, verbose=FALSE)
}
quit(save="no", status=0)