forked from FrissAnalytics/shiny-vue-r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.R
106 lines (71 loc) · 2.45 KB
/
helpers.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
popular_urls <- function(n){
sapply(1:n, function(k){
paste0("http://api.themoviedb.org/3/movie/popular?api_key=1832c46bf5ad73f96183eaddb5f8ab88&page=",k,"&language=en")
})
}
get_urls_async <- function(urls){
# create pool
pool <- new_pool()
# storage
data <- list()
# callback
cb <- function(req){ data <<- c(data, list(req)) }
# scheduled requests
x <- urls %>% sapply(curl_fetch_multi, done=cb, pool=pool)
# perform requests
out <- multi_run(pool = pool)
# extract data
L <- lapply(data, function(req){req$content %>% rawToChar %>% fromJSON( flatten = TRUE)})
# merge into single data frame
df <- NULL
for(l in 1:length(L)){
df <- rbind(df, L[[l]]$results)
}
# remove rows with missing values
df %>% drop_na()
}
get_urls_async2 <- function(urls){
# create pool
pool <- new_pool()
# storage
data <- list()
# callback
cb <- function(req){ data <<- c(data, list(req)) }
# scheduled requests
x <- urls %>% sapply(curl_fetch_multi, done=cb, pool=pool)
# perform requests
out <- multi_run(pool = pool)
# store results + url
L <- list(results = lapply(data, function(req){req$content %>% rawToChar %>% fromJSON( flatten = TRUE)}),
urls = sapply(data, function(req){req$url}))
}
get_movie_details <- function(id){
urls <- c(
paste0("http://api.themoviedb.org/3/movie/", id, "?api_key=", api_key),
paste0("http://api.themoviedb.org/3/movie/", id, "/credits?api_key=", api_key),
paste0("http://api.themoviedb.org/3/movie/", id, "/videos?api_key=", api_key),
paste0("http://api.themoviedb.org/3/movie/", id, "/images?api_key=", api_key))
type <- c("movie","credits","videos","images")
# make requests
L <- get_urls_async2(urls)
# get results
results <- L$results
# make sure results are in known order
m <- match(L$urls, urls)
# add name for easy reference
names(results) <- type[m]
return(results)
}
get_movie_details2 <- function(id){
TMDb::movie(api_key, id = id, append_to_response = "credits,videos,images,images")
}
get_person_details <- function(id){
TMDb::person_tmdb(api_key, id = id,
append_to_response = "movie_credits,external_ids,images,tagged_images,changes,popular,latest")
}
get_urls <- function(urls, keys){
L <- get_urls_async2(urls)
results <- L$results
names(results) <- keys[match(L$urls, urls)]
return(results)
}