File: http.R

package info (click to toggle)
r-cran-rtweet 2.0.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,068 kB
  • sloc: sh: 13; makefile: 2
file content (555 lines) | stat: -rw-r--r-- 17,678 bytes parent folder | download
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
TWIT_get <- function(token, api, params = NULL, ..., host = "api.twitter.com") {
  resp <- TWIT_method("GET",
                      token = token,
                      api = api,
                      params = params,
                      ...,
                      host = host
  )

  from_js(resp)
}

TWIT_post <- function(token, api, params = NULL, body = NULL, ..., host = "api.twitter.com") {
  TWIT_method("POST",
              token = token,
              api = api,
              params = params,
              body = body,
              ...,
              host = host
  )
}

TWIT_method <- function(method, token, api,
                        params = NULL,
                        host = "api.twitter.com",
                        retryonratelimit = NULL,
                        verbose = TRUE,
                        ...) {
  lifecycle::deprecate_warn("2.0.0", function_caller(),
                            details = c("This function might work until your bot/app/user is blocked or fail randomly!",
                                        "!" = "The API has been deprecated and the new API v2.2 requires subscriptions for most endpoints.",
                                        i = "See updates of function and API: help('rtweet-deprecated', 'rtweet' )"
                                        ),
                            always = TRUE)
  # need scipen to ensure large IDs are not displayed in scientific notation
  # need ut8-encoding for the comma separated IDs
  withr::local_options(scipen = 14, encoding = "UTF-8")

  token <- check_token(token)
  url <- paste0("https://", host, api, ".json")

  resp <- switch(method,
                 GET = httr::GET(url, query = params, token, ...),
                 POST = httr::POST(url, query = params, token, ...),
                 stop("Unsupported method", call. = FALSE)
  )

  switch(resp_type(resp),
         ok = NULL,
         rate_limit = handle_rate_limit(
           resp, api,
           retryonratelimit = retryonratelimit,
           verbose = verbose
         ),
         error = handle_error(resp, params)
  )

  resp
}

#' Pagination
#'
#' @description
#' `r lifecycle::badge("experimental")`
#' These are internal functions used for pagination inside of rtweet.
#'
#' @keywords internal
#' @param token Use this to override authentication for
#'   a single API call. In many cases you are better off changing the
#'   default for all calls. See [auth_as()] for details.
#' @param n Desired number of results to return. Results are downloaded
#'   in pages when `n` is large; the default value will download a single
#'   page. Set `n = Inf` to download as many results as possible.
#'
#'   The Twitter API rate limits the number of requests you can perform
#'   in each 15 minute period. The easiest way to download more than that is
#'   to use `retryonratelimit = TRUE`.
#'
#'   You are not guaranteed to get exactly `n` results back. You will get
#'   fewer results when tweets have been deleted or if you hit a rate limit.
#'   You will get more results if you ask for a number of tweets that's not
#'   a multiple of page size, e.g. if you request `n = 150` and the page
#'   size is 200, you'll get 200 results back.
#' @param get_id A single argument function that returns a vector of ids given
#'   the JSON response. The defaults are chosen to cover the most common cases,
#'   but you'll need to double check whenever implementing pagination for
#'   a new endpoint.
#' @param max_id Supply a vector of ids or a data frame of previous results to
#'   find tweets **older** than `max_id`.
#' @param since_id Supply a vector of ids or a data frame of previous results to
#'   find tweets **newer** than `since_id`.
#' @param retryonratelimit If `TRUE`, and a rate limit is exhausted, will wait
#'   until it refreshes. Most Twitter rate limits refresh every 15 minutes.
#'   If `FALSE`, and the rate limit is exceeded, the function will terminate
#'   early with a warning; you'll still get back all results received up to
#'   that point. The default value, `NULL`, consults the option
#'   `rtweet.retryonratelimit` so that you can globally set it to `TRUE`,
#'   if desired.
#'
#'   If you expect a query to take hours or days to perform, you should not
#'   rely solely on `retryonratelimit` because it does not handle other common
#'   failure modes like temporarily losing your internet connection.
#' @param verbose Show progress bars and other messages indicating current
#'   progress?
#' @returns A list with the json output of the API.
TWIT_paginate_max_id <- function(token, api, params,
                                 get_id = function(x) x$id_str,
                                 n = 1000,
                                 page_size = 200,
                                 since_id = NULL,
                                 max_id = NULL,
                                 count_param = "count",
                                 retryonratelimit = NULL,
                                 verbose = TRUE) {
  if (!is.null(max_id)) {
    max_id <- rtweet::max_id(max_id)
  }
  if (!is.null(since_id)) {
    since_id <- rtweet::since_id(since_id)
  }

  params$since_id <- since_id
  params[[count_param]] <- page_size
  pages <- if (is.infinite(n)) page_size else max(c(n %/% page_size), 1)
  results <- vector("list", pages)

  if (verbose)  {
    pb <- progress::progress_bar$new(
      format = "Downloading multiple pages :bar",
      total = pages
    )
    withr::defer(pb$terminate())
  }

  i <- 0
  while (i < pages) {
    i <- i + 1
    params$max_id <- max_id
    if (i == pages) {
      params[[count_param]] <- n - (pages - 1) * page_size
    }

    json <- catch_rate_limit(
      TWIT_get(
        token, api, params,
        retryonratelimit = retryonratelimit,
        verbose = verbose
      )
    )
    if (is_rate_limit(json)) {
      warn_early_term(json,
                      hint = paste0("Set `max_id = '", max_id, "' to continue."),
                      hint_if = !is.null(max_id)
      )
      break
    }

    id <- get_id(json)
    # no more tweets to return
    if (length(id) == 0) {
      break
    }
    if(i > length(results)) {
      # double length per https://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost
      length(results) <- 2 * length(results)
    }

    max_id <- max_id(id)
    results[[i]] <- json

    if (verbose) {
      pb$tick()
    }
  }
  results
}

# https://developer.twitter.com/en/docs/pagination
#' @rdname TWIT_paginate_max_id
#'
#' @param cursor Which page of results to return. The default will return
#'   the first page; you can supply the result from a previous call to
#'   continue pagination from where it left off.
TWIT_paginate_cursor <- function(token, api, params,
                                 n = 5000,
                                 page_size = 5000,
                                 cursor = "-1",
                                 get_id = function(x) x$ids,
                                 retryonratelimit = NULL,
                                 verbose = TRUE) {
  params$count <- page_size
  cursor <- next_cursor(cursor)
  if (identical(cursor, "0")) {
    # Last request retrieved all available results
    return(list())
  }

  # TODO: consider if its worth using fastmap::faststack() here
  pages <- if (is.infinite(n)) page_size else max(c(n %/% page_size), 1)
  results <- vector("list", pages)
  i <- 1
  n_seen <- 0

  if (verbose) {
    pb <- progress::progress_bar$new(
      format = "Downloading multiple pages :bar",
      total = length(results)
    )
    withr::defer(pb$terminate())
  }

  repeat({
    params$cursor <- cursor
    json <- catch_rate_limit(
      TWIT_get(
        token, api, params,
        retryonratelimit = retryonratelimit,
        verbose = verbose
      )
    )

    # Rate limit hit, repeat call to continue
    error_limit <- "errors" %in% names(json)
    continue_limit <- !is.null(retryonratelimit) && retryonratelimit
    if (error_limit && continue_limit) {
      json <- catch_rate_limit(
        TWIT_get(
          token, api, params,
          retryonratelimit = retryonratelimit,
          verbose = verbose
        ))
    }

    if (is_rate_limit(json)) {
      if (!is.null(retryonratelimit)){
        warn_early_term(json,
                        hint = paste0("Set `cursor = '", cursor, "' to continue."),
                        hint_if = !identical(cursor, "-1")
        )
      }
      next
    }
    if (i > length(results)) {
      # double length per https://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost
      length(results) <- 2 * length(results)
    }
    if (any(grepl("next_cursor", names(json)))) {
      cursor <- ifelse(!is.null(json$next_cursor_str),
                       json$next_cursor_str,
                       json$next_cursor)
    } else {
      # If next_cursor is missing there are no message within the last 30 days
      cursor <- "0"
    }
    results[[i]] <- json
    n_seen <- n_seen + length(get_id(json))
    i <- i + 1
    empty_response <- !is.null(json$events) && length(json$events) == 0
    if (identical(cursor, "0") || n_seen >= n || empty_response) {
      break
    }

    if (verbose) {
      pb$update(n_seen / n)
    }
  })

  structure(results, rtweet_cursor = cursor)
}

#' @rdname TWIT_paginate_max_id
#' @keywords internal
TWIT_paginate_chunked <- function(token, api, params_list,
                                  retryonratelimit = NULL,
                                  verbose = TRUE) {


  pages <- length(params_list)
  results <- vector("list", pages)

  if (verbose)  {
    pb <- progress::progress_bar$new(
      format = "Downloading multiple pages :bar",
      total = pages
    )
    withr::defer(pb$terminate())
  }

  for (i in seq_along(params_list)) {
    params <- params_list[[i]]
    json <- catch_rate_limit(
      TWIT_get(
        token, api, params,
        retryonratelimit = retryonratelimit,
        verbose = verbose
      )
    )
    # Rate limit hit, repeat call to continue
    error_limit <- "errors" %in% names(json)
    continue_limit <- !is.null(retryonratelimit) && retryonratelimit
    if (error_limit && continue_limit) {
      json <- catch_rate_limit(
        TWIT_get(
          token, api, params,
          retryonratelimit = retryonratelimit,
          verbose = verbose
        ))
    }
    if (is_rate_limit(json)) {
      warn_early_term(json, hint_if = FALSE)
      break
    }

    results[[i]] <- json

    if (verbose) {
      pb$tick()
    }
  }

  results
}

#' @rdname TWIT_paginate_max_id
TWIT_paginate_premium <- function(token, api, params,
                                  n = 100,
                                  page_size = 100,
                                  cursor = "next",
                                  retryonratelimit = NULL,
                                  verbose = TRUE) {
  if (identical(cursor, "next")) {
    # Last request retrieved all available results
    cursor <- NULL
  } else {
    cursor <- next_cursor(cursor)
  }
  params[["next"]] <- cursor

  # TODO: consider if its worth using fastmap::faststack() here
  pages <- if (is.infinite(n)) page_size else max(c(n %/% page_size), 1)
  results <- vector("list", pages)
  i <- 1
  n_seen <- 0

  if (length(results) > 1) {
    params[["maxResults"]] <- page_size
  }

  if (verbose) {
    pb <- progress::progress_bar$new(
      format = "Downloading multiple pages :bar",
      total = length(results))
    withr::defer(pb$terminate())
  }
  # Time to sleep avoid hitting the lowest rate limits
  min_sleep <- 0.9
  if (page_size == 500) {
    min_sleep <- min_sleep * 2
  }
  repeat({

    Sys.sleep(min_sleep)
    params[["next"]] <- cursor
    json <- catch_rate_limit(
      TWIT_get(
        token, api, params,
        retryonratelimit = retryonratelimit,
        verbose = verbose
      )
    )

    if (is_rate_limit(json)) {
      if (!is.null(retryonratelimit)){
        warn_early_term(json,
                        hint = paste0("Set `continue = '", cursor, "' to continue."),
                        hint_if = !identical(cursor, "next")
        )
      }
      break
    }

    # Rate limit hit, repeat call to continue
    error_limit <- "errors" %in% names(json)
    continue_limit <- !is.null(retryonratelimit) && retryonratelimit
    if (error_limit && continue_limit) {
      json <- catch_rate_limit(
        TWIT_get(
          token, api, params,
          retryonratelimit = retryonratelimit,
          verbose = verbose
        ))
    }

    if (i > length(results)) {
      # double length per https://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost
      length(results) <- 2 * length(results)
    }
    results[[i]] <- json$results
    if (any(grepl("next", names(json)))) {
      cursor <- if (!is.null(json[["next"]])) json[["next"]]
    }
    n_seen <- n_seen + nrow(json$results)
    i <- i + 1
    empty_response <- !is.null(json$results) && length(json$results) == 0
    if ( length(n_seen) == 0 || n_seen >= n || empty_response) {
      break
    }

    if (verbose) {
      pb$update(n_seen / n)
    }
  })

  structure(results, "next" = cursor)
}


# helpers -----------------------------------------------------------------

from_js <- function(resp) {
  if (is.null(resp$headers[["content-type"]]) || !grepl("application/json", resp$headers[["content-type"]])) {
    stop("API did not return json", call. = FALSE)
  }
  resp <- httr::content(resp, as = "text", encoding = "UTF-8")
  jsonlite::fromJSON(resp)
}

resp_type <- function(resp) {
  status <- httr::status_code(resp)
  if (status == 429) {
    "rate_limit"
  } else if (status >= 400) {
    "error"
  } else {
    "ok"
  }
}

# Three possible exits:
# * skip, if testing
# * return, if retryonratelimit is TRUE
# * error, otherwise
handle_rate_limit <- function(x, api, retryonratelimit = NULL, verbose = TRUE) {
  if (is_testing()) {
    testthat::skip("Rate limit exceeded")
  }

  headers <- httr::headers(x)
  n <- headers$`x-rate-limit-limit`
  when <- .POSIXct(as.numeric(headers$`x-rate-limit-reset`))

  retryonratelimit <- retryonratelimit %||% getOption("rtweet.retryonratelimit", FALSE)

  if (retryonratelimit) {
    wait_until(when, api, verbose = verbose)
  } else {
    message <- c(
      paste0("Rate limit exceeded for Twitter endpoint '", api, "'"),
      paste0("Will receive ", n, " more requests at ", format(when, "%H:%M"))
    )
    abort(message, class = "rtweet_rate_limit", when = when)
  }
}

# Function for responses that might be errors
# Depending on the internal error code it is provided to the users as a warning or error
handle_codes <- function(x) {
  if ("errors" %in% names(httr::content(x))) {
    errors <- httr::content(x)$errors[[1]]
    for (e in seq_len(max(lengths(errors)))) {
      funct <- switch(as.character(errors$code[e]),
                      "89" = stop,
                      warning)
      funct(paste0(errors$message[e], " (", errors$code[e], ")"),
            call. = FALSE)

    }
  }
}

# https://developer.twitter.com/en/support/twitter-api/error-troubleshooting
handle_error <- function(x, params) {
  chk_message <- "Check error message at https://developer.twitter.com/en/support/twitter-api/error-troubleshooting"
  if (is.null(x$headers[["content-type"]])) {
    abort(paste0("Twitter API failed [", x$status_code, "]\n", chk_message),
          call = caller_call())
  }
  json <- from_js(x)
  error <- if (!is.null(json[["error"]])) json[["error"]] else json[["errors"]]
  if (x$status_code %in% c("401", "403") && is_developing()) {
    testthat::skip("API v1.1 no longer works")
    if (length(error) == 1) {
      if (any(c("screen_name", "user_id") %in% names(params))) {
        account <- params$screen_name
        if (is.null(account))
          account <- params$user_id
        warn(paste0("Skipping unauthorized account: ", account))
      } else {
        warn(paste0("Something went wrong with the authentication:\n\t", error))
      }
    } else if (length(error) == 2) {
      abort(c(paste0("Twitter API failed [", x$status_code, "]:"),
              paste0(error$message, " (", error$code, ")")),
            call. = caller_call())
    } else {
      if (is_testing()) {
        testthat::skip("Something went wrong with the requests")
      }
      warn("Something went wrong with the requests")
    }
  }
}

# I don't love this interface because it returns either a httr response object
# or a condition object, but it's easy to understand and avoids having to do
# anything exotic to break from the correct frame.
catch_rate_limit <- function(code) {
  tryCatch(code, rtweet_rate_limit = function(e) e)
}

is_rate_limit <- function(x) inherits(x, "rtweet_rate_limit")

warn_early_term <- function(cnd, hint, hint_if) {
  warn(c(
    "Terminating paginate early due to rate limit.",
    cnd$message,
    i = if (hint_if) hint,
    i = "Set `retryonratelimit = TRUE` to automatically wait for reset"
  ))
}

check_status <- function(x, api) {
  switch(resp_type(x),
         ok = NULL,
         rate_limit = ,
         error = handle_error(x)
  )
}

check_token <- function(token = NULL) {
  token <- token %||% auth_get()

  if (inherits(token, "Token1.0")) {
    token
  } else if (auth_is_bearer(token)) {
    httr::add_headers(Authorization = paste0("Bearer ", token$token))
  } else if (auth_is_pkce(token)) {
    abort(c("This OAuth 2.0 `token` is not a valid access token",
            "i" = "Please use a bearer token via `rtweet_app()`."),
          call = caller_call())
  } else {
    abort("`token` is not a valid access token", call = caller_call())
  }
}