Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

240 lines
6.4KB

  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. simplify_tweets <- function(
  78. tweets = NULL,
  79. file = getOption("gathertweet.file", "tweets.rds"),
  80. ...,
  81. .fields = NULL
  82. ) {
  83. if (is.null(tweets)) tweets <- read_tweets(file)
  84. if (is.null(tweets)) return(NULL)
  85. .fields <- c(list(...), .fields)
  86. if (length(.fields)) {
  87. tweets %>% dplyr::select(!!!.fields)
  88. } else {
  89. dplyr::select(
  90. tweets,
  91. created_at,
  92. status_id,
  93. user_id,
  94. screen_name,
  95. text,
  96. favorite_count,
  97. retweet_count,
  98. hashtags,
  99. profile_url,
  100. profile_image_url,
  101. urls_expanded_url,
  102. mentions_screen_name,
  103. is_quote,
  104. media_url,
  105. urls_url
  106. )
  107. }
  108. }
  109. #' @export
  110. update_tweets <- function(
  111. tweets = NULL,
  112. file = getOption("tweets.file", "tweets.rds"),
  113. ...
  114. ) {
  115. if (is.null(tweets)) tweets <- read_tweets(file)
  116. lookup_status_ratelimit(tweets$status_id, ...)
  117. }
  118. lookup_status_ratelimit <- function(status_id, ...) {
  119. tweets <- NULL
  120. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  121. fetch_count <- 0
  122. n_status <- length(status_id)
  123. n_status_large <- n_status > 90000
  124. for (idx_group in seq(1, ceiling(n_status/90000))) {
  125. # Rate limit ----
  126. # Track rate limit and wait it out if needed
  127. if (Sys.time() > rate_limit$reset_at) {
  128. log_debug("Updating out-of-date rate limit")
  129. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  130. }
  131. if (rate_limit$remaining - fetch_count < 1) {
  132. # wait until rate limit resets
  133. wait_s <- difftime(Sys.time(), rate_limit$reset_at, units = "sec")
  134. log_info("Waiting for rate limit to reset at {rate_limit$reset_at}")
  135. Sys.sleep(ceiling(as.numeric(wait_s)))
  136. }
  137. if (fetch_count > 0 && fetch_count %% 50 == 0) {
  138. rate_limit <- rtweet::rate_limits(query = "statuses/lookup")
  139. }
  140. # Get Statuses ----
  141. if (n_status_large) {
  142. idx_start <- (idx_group - 1) * 90000 + 1
  143. idx_end <- min(idx_group * 90000, n_status)
  144. log_info("Getting tweets {idx_start} to {idx_end} of {n_status}")
  145. } else {
  146. idx_start <- 1
  147. idx_end <- n_status
  148. log_info("Getting {n_status} tweets")
  149. }
  150. tweets <- bind_rows(
  151. tweets,
  152. rtweet::lookup_statuses(status_id[idx_start:idx_end], ...)
  153. )
  154. }
  155. tweets
  156. }
  157. path_lock <- function(file) {
  158. path(path_add(file, NULL, prepend = "."), ext = "lock")
  159. }
  160. path_add <- function(file, append = strftime(Sys.time(), "_%F_%H%M%S"), prepend = NULL) {
  161. if (is.null(append)) append <- ""
  162. if (is.null(prepend)) prepend <- ""
  163. file_base <- fs::path_ext_remove(fs::path_file(file))
  164. file_ext <- fs::path_ext(file)
  165. file_dir <- fs::path_dir(file)
  166. path(file_dir,
  167. glue::glue("{prepend}{file_base}{append}"),
  168. ext = file_ext)
  169. }
  170. stopifnot_locked <- function(lck = NULL, message = "Unable to aquire lock") {
  171. if (!is.null(lck)) return(invisible(TRUE))
  172. log_error(message, envir = sys.frame(1))
  173. }
  174. shared_lock <- function(file, timeout = 1 * 60 * 1000) {
  175. lock(path_lock(file), exclusive = FALSE, timeout = timeout)
  176. }
  177. exclusive_lock <- function(file, timeout = 1 * 60 * 1000) {
  178. lock(path_lock(file), exclusive = TRUE, timeout = timeout)
  179. }
  180. #' @title Get user info
  181. #' @param file The file where tweets are located. The text `_users` is
  182. #' automatically appended to this file name.
  183. #' @export
  184. get_user_info <- function(
  185. tweets = NULL,
  186. file = getOption("gathertweet.file", "tweets.rds"),
  187. dir_profile_images = NULL
  188. ) {
  189. if (is.null(tweets)) read_tweets(file)
  190. user_file <- path_add(file, append = "_users")
  191. users <- tweets %>%
  192. rtweet::users_data() %>%
  193. dplyr::distinct()
  194. users <- save_tweets(users, user_file, key_var = "user_id")
  195. if (!is.null(dir_profile_images)) {
  196. rs <- lapply(users$profile_image_url, download_profile_images, output_dir = dir_profile_images)
  197. }
  198. return(users)
  199. }
  200. download_profile_images <- function(profile_image_url, ..., output_dir = "data") {
  201. output_file <- sub("^.+?profile", "profile", profile_image_url)
  202. output_file <- fs::path(output_dir, output_file)
  203. fs::dir_create(fs::path_dir(output_file), recursive = TRUE)
  204. download_file(profile_image_url, output_file)
  205. }
  206. download_file <- function(url, dest) {
  207. if (fs::file_exists(dest)) return(dest)
  208. x <- list(result = NULL, error = NULL)
  209. x$result <- tryCatch({
  210. download.file(url, dest)
  211. dest
  212. }, error = function(e) x$error <<- e$message)
  213. if (!is.null(x$error)) {
  214. log_warn("Error downloading {dest}: {x$error}")
  215. } else x$result
  216. }