You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

161 line
4.5KB

  1. #' @export
  2. save_tweets <- function(
  3. tweets,
  4. file = getOption("gathertweet.file", "tweets.rds"),
  5. save_fun = saveRDS,
  6. read_fun = read_tweets,
  7. lck = NULL
  8. ) {
  9. if (nrow(tweets) < 1) return(tweets)
  10. fs::dir_create(fs::path_dir(file))
  11. if (is.null(lck)) {
  12. lck <- exclusive_lock(file)
  13. on.exit(unlock(lck))
  14. }
  15. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  16. if (fs::file_exists(file)) {
  17. # Don't drop or lose old tweets
  18. tweets_prev <- read_fun(file, lck = lck)
  19. if (!is.null(tweets_prev)) {
  20. tweets_not_new <- anti_join(tweets_prev, tweets, by = "status_id")
  21. if (nrow(tweets_not_new)) {
  22. tweets <- bind_rows(tweets, tweets_not_new)
  23. }
  24. if (length(setdiff(tweets_prev$status_id, tweets$status_id)) != 0) {
  25. log_fatal("An error occurred that would have lost stored tweets")
  26. }
  27. }
  28. }
  29. save_fun(tweets, file)
  30. tweets
  31. }
  32. #' @export
  33. last_seen_tweet <- function(
  34. tweets = NULL,
  35. file = getOption("gathertweet.file", "tweets.rds")
  36. ) {
  37. if (is.null(tweets)) tweets <- read_tweets(file)
  38. if (is.null(tweets)) return(NULL)
  39. tweets$status_id %>%
  40. as.numeric() %>%
  41. max() %>%
  42. as.character()
  43. }
  44. #' @export
  45. read_tweets <- function(
  46. file = getOption("gathertweet.file", "tweets.rds"),
  47. lck = NULL
  48. ) {
  49. if (!file_exists(file)) return(NULL)
  50. if (is.null(lck)) {
  51. lck <- shared_lock(file)
  52. on.exit(unlock(lck))
  53. }
  54. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  55. readRDS(file)
  56. }
  57. #' @export
  58. backup_tweets <- function(
  59. file = getOption("gathertweet.file", "tweets.rds"),
  60. backup_dir = "backups",
  61. lck = NULL
  62. ) {
  63. if (!file_exists(file)) return()
  64. if (is.null(lck)) {
  65. lck <- shared_lock(file)
  66. on.exit(unlock(lck))
  67. }
  68. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  69. file_backup <- path(fs::path_dir(file), backup_dir, fs::path_file(file))
  70. file_backup <- path_add(file_backup)
  71. fs::dir_create(fs::path_dir(file_backup))
  72. log_info("Backing up tweet file to {file_backup}")
  73. fs::file_copy(file, file_backup)
  74. }
  75. #' @export
  76. update_tweets <- function(
  77. tweets = NULL,
  78. file = getOption("tweets.file", "tweets.rds"),
  79. ...
  80. ) {
  81. if (is.null(tweets)) tweets <- read_tweets(file)
  82. lookup_status_ratelimit(tweets$status_id, ...)
  83. }
  84. lookup_status_ratelimit <- function(status_id, ...) {
  85. tweets <- NULL
  86. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  87. fetch_count <- 0
  88. n_status <- length(status_id)
  89. n_status_large <- n_status > 90000
  90. for (idx_group in seq(1, ceiling(n_status/90000))) {
  91. # Rate limit ----
  92. # Track rate limit and wait it out if needed
  93. if (Sys.time() > rate_limit$reset_at) {
  94. log_debug("Updating out-of-date rate limit")
  95. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  96. }
  97. if (rate_limit$remaining - fetch_count < 1) {
  98. # wait until rate limit resets
  99. wait_s <- difftime(Sys.time(), rate_limit$reset_at, units = "sec")
  100. log_info("Waiting for rate limit to reset at {rate_limit$reset_at}")
  101. Sys.sleep(ceiling(as.numeric(wait_s)))
  102. }
  103. if (fetch_count > 0 && fetch_count %% 50 == 0) {
  104. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  105. }
  106. # Get Statuses ----
  107. if (n_status_large) {
  108. idx_start <- (idx_group - 1) * 90000 + 1
  109. idx_end <- min(idx_group * 90000, n_status)
  110. log_info("Getting tweets {idx_start} to {idx_end} of {n_status}")
  111. } else {
  112. idx_start <- 1
  113. idx_end <- n_status
  114. log_info("Getting {n_status} tweets")
  115. }
  116. tweets <- bind_rows(
  117. tweets,
  118. rtweet::lookup_statuses(status_id[idx_start:idx_end], ...)
  119. )
  120. }
  121. tweets
  122. }
  123. path_lock <- function(file) {
  124. path(path_add(file, NULL, prepend = "."), ext = "lock")
  125. }
  126. path_add <- function(file, append = strftime(Sys.time(), "_%F_%H%M%S"), prepend = NULL) {
  127. if (is.null(append)) append <- ""
  128. if (is.null(prepend)) prepend <- ""
  129. file_base <- fs::path_ext_remove(fs::path_file(file))
  130. file_ext <- fs::path_ext(file)
  131. file_dir <- fs::path_dir(file)
  132. path(file_dir,
  133. glue::glue("{prepend}{file_base}{append}"),
  134. ext = file_ext)
  135. }
  136. stopifnot_locked <- function(lck = NULL, message = "Unable to aquire lock") {
  137. if (!is.null(lck)) return(invisible(TRUE))
  138. log_error(message, envir = sys.frame(1))
  139. }
  140. shared_lock <- function(file, timeout = 1 * 60 * 1000) {
  141. lock(path_lock(file), exclusive = FALSE, timeout = timeout)
  142. }
  143. exclusive_lock <- function(file, timeout = 1 * 60 * 1000) {
  144. lock(path_lock(file), exclusive = TRUE, timeout = timeout)
  145. }