-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathCDPRemote.R
319 lines (312 loc) · 10.4 KB
/
CDPRemote.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#' @include utils.R
#' @include http_methods.R
#' @include CDPSession.R
#' @include hold.R
#' @importFrom assertthat assert_that is.scalar is.number
NULL
#' Declare a remote application implementing the Chrome Debugging Protocol
#'
#' This class aims to declare an application implementing the Chrome Debugging
#' Protocol. It possesses methods to manage connections.
#'
#' @section Usage:
#' ```
#' remote <- CDPRemote$new(host = "localhost", debug_port = 9222, secure = FALSE,
#' local = FALSE, retry_delay = 0.2, max_attempts = 15L)
#'
#' remote$connect(callback = NULL)
#' remote$listConnections()
#' remote$closeConnections(callback = NULL)
#' remote$version()
#' remote$user_agent
#' ```
#'
#' @section Arguments:
#' * `remote`: an object representing a remote application implementing the
#' Chrome Debugging Protocol.
#' * `host`: Character scalar, the host name of the application.
#' * `debug_port`: Integer scalar, the remote debugging port.
#' * `secure`: Logical scalar, indicating whether the https/wss protocols
#' shall be used for connecting to the remote application.
#' * `local`: Logical scalar, indicating whether the local version of the
#' protocol (embedded in `crrri`) must be used or the protocol must be
#' fetched _remotely_.
#' * `retry_delay`: Number, delay in seconds between two successive tries to
#' connect to the remote application.
#' * `max_attempts`: Integer scalar, number of tries to connect to headless
#' Chromium/Chrome.
#' * `callback`: Function with one argument.
#'
#' @section Details:
#' `$new()` declares a new remote application.
#'
#' `$connect(callback = NULL)` connects the R session to the remote application.
#' The returned value depends on the value of the `callback` argument. When
#' `callback` is a function, the returned value is a connection object. When
#' `callback` is `NULL` the returned value is a promise which fulfills once R
#' is connected to the remote application. Once fulfilled, the value of this
#' promise is the connection object.
#'
#' `$listConnections()` returns a list of the connection objects succesfully
#' created using the `$connect()` method.
#'
#' `$closeConnections(callback = NULL)` closes all the connections created using
#' the `$connect()` method. If `callback` is `NULL`, it returns a promise which
#' fulfills when all the connections are closed: once fulfilled, its value is the
#' remote object.
#' If `callback` is not `NULL`, it returns the remote object. In this case,
#' `callback` is called when all the connections are closed and the remote object is
#' passed to this function as the argument.
#'
#' `$version()` executes the DevTools `Version` method. It returns a list of
#' informations available at `http://<host>:<debug_port>/json/version`.
#'
#' `$user_agent` returns a character scalar with the User Agent of the
#' remote application.
#'
#' `$listTargets()` returns a list with information about targets (or tabs).
#'
#' @name CDPRemote
#' @examples
#' \dontrun{
#' # Assuming that an application is already running at http://localhost:9222
#' # For instance, you can execute:
#' # chrome <- Chrome$new()
#'
#' remote <- CDPRemote$new()
#'
#' remote$connect() %...>% (function(client) {
#' Page <- client$Page
#' Runtime <- client$Runtime
#'
#' Page$enable() %...>% {
#' Page$navigate(url = 'http://r-project.org')
#' } %...>% {
#' Page$loadEventFired()
#' } %...>% {
#' Runtime$evaluate(
#' expression = 'document.documentElement.outerHTML'
#' )
#' } %...>% (function(result) {
#' cat(result$result$value, "\n")
#' }) %...!% {
#' cat("Error:", .$message, "\n")
#' } %>%
#' promises::finally(~ client$disconnect())
#' }) %...!% {
#' cat("Error:", .$message, "\n")
#' }
#' }
#'
NULL
#' @export
CDPRemote <- R6::R6Class(
"CDPRemote",
public = list(
initialize = function(
host = "localhost", debug_port = 9222, secure = FALSE, local = FALSE,
retry_delay = 0.2, max_attempts = 15L
) {
assert_that(is_scalar_character(host))
assert_that(is.number(debug_port))
assert_that(is.scalar(secure), is.logical(secure))
assert_that(is.scalar(local), is.logical(local))
assert_that(is.number(retry_delay))
assert_that(is_scalar_integerish(max_attempts))
private$.port <- debug_port
private$.secure <- secure
private$.local_protocol <- isTRUE(local)
private$.retry_delay <- retry_delay
private$.max_attempts <- max_attempts
remote_reachable <- is_remote_reachable(host, debug_port, secure, retry_delay, max_attempts)
if(!remote_reachable && host == "localhost") {
host <- "127.0.0.1"
remote_reachable <- is_remote_reachable(host, debug_port, secure, retry_delay, max_attempts)
}
if(!remote_reachable) {
warning("Cannot access to remote host...")
private$.reachable <- FALSE
}
private$.host <- host
self$version() # run once to store version
},
connect = function(callback = NULL, .target_id = "default") {
async <- is.null(callback)
if(!is.null(callback)) {
callback <- rlang::as_function(callback)
assertthat::assert_that(
length(rlang::fn_fmls(callback)) > 0,
msg = "The callback function must have one argument."
)
}
private$.check_remote()
if(!private$.reachable) {
return(stop_or_reject(
"Cannot access to remote host.",
async = async
))
}
if(identical(.target_id, "default")) {
# test if there is an available target
if(length(self$listTargets()) == 0L) {
return(self$connectToNewTab(callback = callback))
}
ws_url <- chr_get_ws_addr(private$.host, private$.port, private$.secure)
} else {
targets <- self$listTargets()
# extracts targets identifiers:
ids <- purrr::map_chr(self$listTargets(), "id")
# find the position of .target_id in this character vector
pos <- purrr::detect_index(ids, ~ identical(.x, .target_id))
# if .target_id is not in the list, its position is 0
if(pos == 0) {
return(stop_or_reject(
"unable to connect: wrong target ID.",
async = async
))
}
# retrieve the websocket address associated with target_id:
ws_url <- purrr::pluck(targets, pos, "webSocketDebuggerUrl")
}
con <- CDPSession(
host = private$.host,
port = private$.port,
secure = private$.secure,
ws_url = ws_url,
local = private$.local_protocol,
callback = callback
)
if(promises::is.promise(con)) {
promises::then(
con,
onFulfilled = function(value) {
private$.clients <- c(private$.clients, list(value))
},
onRejected = function(err) {
warning(err$message, call. = FALSE, immediate. = TRUE)
}
)
} else {
private$.clients <- c(private$.clients, list(con))
}
con
},
listConnections = function() {
private$.clients
},
closeConnections = function(callback = NULL) {
if(!is.null(callback)) {
callback <- rlang::as_function(callback)
}
async <- is.null(callback)
if(async) {
# CDPSession disconnect() method returns a promise
disconnected <- promises::promise_all(
.list = purrr::map(private$.clients, function(client) {
client$disconnect()
})
)
# when connections are closed, remove them from the list of clients
# and return the remote object (i.e. self)
cleaned <- promises::then(
disconnected,
onFulfilled = function(value) {
private$.clients <- list()
invisible(self)
}
)
return(cleaned)
} else {
token <- new.env()
token$done <- FALSE
client_callback <- function(client) {
if(private$.are_clients_closed() && !token$done) {
private$.clients <- list()
token$done <- TRUE
callback(self)
}
}
if(identical(length(private$.clients), 0L)) {
on.exit(callback(self), add = TRUE)
}
purrr::walk(private$.clients, ~ .x$disconnect(callback = client_callback))
return(invisible(self))
}
},
version = function() {
private$.check_remote()
if(private$.reachable) {
# if remote is opened, update the private field .version
private$.version <- fetch_version(private$.host, private$.port, private$.secure)
}
private$.version
},
listTargets = function() {
private$.check_remote()
if(private$.reachable) {
list_targets(private$.host, private$.port, private$.secure)
} else {
warning("cannot access to remote host.")
}
},
connectToNewTab = function(url = NULL, callback = NULL) {
target <- new_tab(private$.host, private$.port, private$.secure, url)
if(is.null(target$id)) {
return(
stop_or_reject(
"Unable to create a new tab.",
async = is.null(callback)
)
)
}
self$connect(callback = callback, .target_id = target$id)
},
print = function() {
version <- self$version()
cat(sep = "",
"<", version$Browser, ">\n",
' url: ', build_http_url(private$.host, private$.port, private$.secure), "\n",
' user-agent:\n',
' "', version$`User-Agent`, '"\n'
)
}
),
active = list(
user_agent = function() {
self$version()$`User-Agent`
}
),
private = list(
.host = NULL,
.port = NULL,
.secure = FALSE,
.local_protocol = FALSE,
.retry_delay = 0.2,
.max_attempts = 15L,
.reachable = TRUE,
.version = list(),
.clients = list(),
.check_remote = function() {
if(private$.reachable) {
private$.reachable <- is_remote_reachable(
private$.host,
private$.port,
private$.secure,
private$.retry_delay,
private$.max_attempts
)
}
},
.are_clients_closed = function() {
all(purrr::map_lgl(private$.clients, ~ .x$readyState() == 3L))
},
finalize = function() {
# since we are in finalize, we can use hold() safely
hold(
self$closeConnections(),
timeout = 10,
msg = "The WebSocket connections have not been properly closed."
)
}
)
)