Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

205 lines
5.8KB

  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. key_var = "status_id"
  9. ) {
  10. if (nrow(tweets) < 1) return(tweets)
  11. fs::dir_create(fs::path_dir(file))
  12. if (is.null(lck)) {
  13. lck <- exclusive_lock(file)
  14. on.exit(unlock(lck))
  15. }
  16. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  17. if (fs::file_exists(file)) {
  18. # Don't drop or lose old tweets
  19. tweets_prev <- read_fun(file, lck = lck)
  20. if (!is.null(tweets_prev)) {
  21. tweets_not_new <- anti_join(tweets_prev, tweets, by = key_var)
  22. if (nrow(tweets_not_new)) {
  23. tweets <- bind_rows(tweets, tweets_not_new)
  24. }
  25. if (length(setdiff(tweets_prev[[key_var]], tweets[[key_var]])) != 0) {
  26. log_fatal("An error occurred that would have lost stored tweets")
  27. }
  28. }
  29. }
  30. save_fun(tweets, file)
  31. tweets
  32. }
  33. #' @export
  34. last_seen_tweet <- function(
  35. tweets = NULL,
  36. file = getOption("gathertweet.file", "tweets.rds")
  37. ) {
  38. if (is.null(tweets)) tweets <- read_tweets(file)
  39. if (is.null(tweets)) return(NULL)
  40. tweets$status_id %>%
  41. as.numeric() %>%
  42. max() %>%
  43. as.character()
  44. }
  45. #' @export
  46. read_tweets <- function(
  47. file = getOption("gathertweet.file", "tweets.rds"),
  48. lck = NULL
  49. ) {
  50. if (!file_exists(file)) return(NULL)
  51. if (is.null(lck)) {
  52. lck <- shared_lock(file)
  53. on.exit(unlock(lck))
  54. }
  55. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  56. readRDS(file)
  57. }
  58. #' @export
  59. backup_tweets <- function(
  60. file = getOption("gathertweet.file", "tweets.rds"),
  61. backup_dir = "backups",
  62. lck = NULL
  63. ) {
  64. if (!file_exists(file)) return()
  65. if (is.null(lck)) {
  66. lck <- shared_lock(file)
  67. on.exit(unlock(lck))
  68. }
  69. stopifnot_locked(lck, message = "Unable to acquire lock on {file}")
  70. file_backup <- path(fs::path_dir(file), backup_dir, fs::path_file(file))
  71. file_backup <- path_add(file_backup)
  72. fs::dir_create(fs::path_dir(file_backup))
  73. log_info("Backing up tweet file to {file_backup}")
  74. fs::file_copy(file, file_backup)
  75. }
  76. #' @export
  77. update_tweets <- function(
  78. tweets = NULL,
  79. file = getOption("tweets.file", "tweets.rds"),
  80. ...
  81. ) {
  82. if (is.null(tweets)) tweets <- read_tweets(file)
  83. lookup_status_ratelimit(tweets$status_id, ...)
  84. }
  85. lookup_status_ratelimit <- function(status_id, ...) {
  86. tweets <- NULL
  87. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  88. fetch_count <- 0
  89. n_status <- length(status_id)
  90. n_status_large <- n_status > 90000
  91. for (idx_group in seq(1, ceiling(n_status/90000))) {
  92. # Rate limit ----
  93. # Track rate limit and wait it out if needed
  94. if (Sys.time() > rate_limit$reset_at) {
  95. log_debug("Updating out-of-date rate limit")
  96. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  97. }
  98. if (rate_limit$remaining - fetch_count < 1) {
  99. # wait until rate limit resets
  100. wait_s <- difftime(Sys.time(), rate_limit$reset_at, units = "sec")
  101. log_info("Waiting for rate limit to reset at {rate_limit$reset_at}")
  102. Sys.sleep(ceiling(as.numeric(wait_s)))
  103. }
  104. if (fetch_count > 0 && fetch_count %% 50 == 0) {
  105. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  106. }
  107. # Get Statuses ----
  108. if (n_status_large) {
  109. idx_start <- (idx_group - 1) * 90000 + 1
  110. idx_end <- min(idx_group * 90000, n_status)
  111. log_info("Getting tweets {idx_start} to {idx_end} of {n_status}")
  112. } else {
  113. idx_start <- 1
  114. idx_end <- n_status
  115. log_info("Getting {n_status} tweets")
  116. }
  117. tweets <- bind_rows(
  118. tweets,
  119. rtweet::lookup_statuses(status_id[idx_start:idx_end], ...)
  120. )
  121. }
  122. tweets
  123. }
  124. path_lock <- function(file) {
  125. path(path_add(file, NULL, prepend = "."), ext = "lock")
  126. }
  127. path_add <- function(file, append = strftime(Sys.time(), "_%F_%H%M%S"), prepend = NULL) {
  128. if (is.null(append)) append <- ""
  129. if (is.null(prepend)) prepend <- ""
  130. file_base <- fs::path_ext_remove(fs::path_file(file))
  131. file_ext <- fs::path_ext(file)
  132. file_dir <- fs::path_dir(file)
  133. path(file_dir,
  134. glue::glue("{prepend}{file_base}{append}"),
  135. ext = file_ext)
  136. }
  137. stopifnot_locked <- function(lck = NULL, message = "Unable to aquire lock") {
  138. if (!is.null(lck)) return(invisible(TRUE))
  139. log_error(message, envir = sys.frame(1))
  140. }
  141. shared_lock <- function(file, timeout = 1 * 60 * 1000) {
  142. lock(path_lock(file), exclusive = FALSE, timeout = timeout)
  143. }
  144. exclusive_lock <- function(file, timeout = 1 * 60 * 1000) {
  145. lock(path_lock(file), exclusive = TRUE, timeout = timeout)
  146. }
  147. #' @title Get user info
  148. #' @param file The file where tweets are located. The text `_users` is
  149. #' automatically appended to this file name.
  150. #' @export
  151. get_user_info <- function(
  152. tweets = NULL,
  153. file = getOption("gathertweet.file", "tweets.rds"),
  154. dir_profile_images = NULL
  155. ) {
  156. if (is.null(tweets)) read_tweets(file)
  157. user_file <- path_add(file, append = "_users")
  158. users <- tweets %>%
  159. rtweet::users_data() %>%
  160. dplyr::distinct()
  161. users <- save_tweets(users, user_file, key_var = "user_id")
  162. if (!is.null(dir_profile_images)) {
  163. rs <- lapply(users$profile_image_url, download_profile_images, output_dir = dir_profile_images)
  164. }
  165. return(users)
  166. }
  167. download_profile_images <- function(profile_image_url, ..., output_dir = "data") {
  168. output_file <- sub("^.+?profile", "profile", profile_image_url)
  169. output_file <- fs::path(output_dir, output_file)
  170. fs::dir_create(fs::path_dir(output_file), recursive = TRUE)
  171. download_file(profile_image_url, output_file)
  172. }
  173. download_file <- function(url, dest) {
  174. if (fs::file_exists(dest)) return(dest)
  175. x <- list(result = NULL, error = NULL)
  176. x$result <- tryCatch({
  177. download.file(url, dest)
  178. dest
  179. }, error = function(e) x$error <<- e$message)
  180. if (!is.null(x$error)) {
  181. log_warn("Error downloading {dest}: {x$error}")
  182. } else x$result