-
Notifications
You must be signed in to change notification settings - Fork 0
/
.Rhistory
512 lines (512 loc) · 17.2 KB
/
.Rhistory
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
data <- rjson::fromJSON(rawToChar(GET(url,
config(token = StravaAuth$public_fields$token))$content))
View(data)
data[[2]]
names(data[[2]])
data[[2]]
data
unlist(data)
grepl("errors.code",names(unlist(data)))
any(grepl("errors.code",names(unlist(data))))
#' Get custom API request string
#'
#' Type in your own request string
#'
#' @param request Request string after https://www.strava.com/api/v3/, e.g. athletes
#'
#' @import httr
#' @import rjson
#'
#'
#' @export
#' @examples
#' strava_customApi(request)
strava_customApi <- function(request){
url <- paste0("https://www.strava.com/api/v3/", request)
tryCatch({
data <- rjson::fromJSON(rawToChar(GET(url,
config(token = StravaAuth$public_fields$token))$content))
if(any(grepl("errors.code",names(unlist(data))))){
cat(crayon::red("Error: Not an authorized API call"))
} else{
return(data)
}
}, error = function(e){
cat(crayon::red("Error: Not an authorized API call"))
})
}
strava_customApi("activities")
strava_customApi("activit")
strava_customApi("ectivities")[[1]]
strava_customApi("ectivities")
strava_customApi("activities")[[1]]
strava_customApi("2323298211")[[1]]
strava_customApi("2323298211")
strava_customApi("activity/2323298211")
strava_customApi("activities/2323298211")
strava_customApi("activities/2323298211")$speed
strava_customApi("activities/2323298211")[[1]]
strava_customApi("activities/2323298211")
strava_customApi("activities/2323298211")[[]]
strava_customApi("activities/2323298211")[['laps']]
strava_customApi("activities/2323298211")[['laps']][[1]]
strava_customApi("activities/2323298211")[['laps']][[1]]$speed
strava_customApi("activities/2323298211")[['laps']][[1]]$average_speed
strava_customApi("activities/2323298211?splits=500")[['laps']][[1]]$average_speed
strava_customApi("activities/2323298211?splits=500")
strava_customApi("activities/2323298211?splits=500") -> df
View(df)
strava_customApi("activities/2323298211?splits_metric=500") -> df
View(df)
strava_customApi("activities/2323298211?splits_distance=500") -> df
View(df)
strava_customApi("activities/2323298211?splits.distance=500") -> df
devtools::document()
strava_auth()
strava_auth("strava.httr-oath")
strava_auth(token = "strava.httr-oath")
#' R6 environment to store authentication credentials
#'
#' Used to keep persistent state.
#' @export
StravaAuth <- R6::R6Class(
"StravaAuth",
public = list(
token = NULL,
method = NULL
),
lock_objects = FALSE,
parent_env = emptyenv()
)
#' Generata Strava API authentication token
#'
#' Generate a token for the user and the desired scope. The user is sent to the strava authentication page if he/she hasn't given permission to the app yet, else, is sent to the app webpage.
#'
#' @param app_name Name of your developer app
#' @param app_client_id The Client ID of your developer app
#' @param app_secret The secret for your developer app
#'
#' @import httr
#' @import assertthat
#'
#' @export
#' @examples
#' strava_auth(app_name = "APP Name", app_client_id = "App Client ID", app_secret = "APP Secret", token = NULL, new_user = FALSE)
strava_auth <- function(app_name = Sys.getenv("STRAVA_APP_NAME"), app_client_id = Sys.getenv("STRAVA_APP_ID"), app_secret = Sys.getenv("STRAVA_APP_SECRET"), token = NULL, new_user = FALSE){
if((app_client_id == "" | app_secret == "" | app_name == "") & is.null(token)){
stop("Need a valid App name, App Client Id and App Secret in order to authorize connection!", call. = FALSE)
} else {
Sys.setenv(STRAVA_APP_NAME = app_name)
Sys.setenv(STRAVA_APP_ID = app_client_id)
Sys.setenv(STRAVA_APP_SECRET = app_secret)
}
checkEnvFile <- function(env){
value <- Sys.getenv(env)
value <- ifelse(value == "", return(NULL), return(value))
}
options("stravaR.httr_oauth_cache" = ifelse(is.null(getOption("stravaR.httr_oauth_cache")),
ifelse(is.null(token), "strava.httr-oauth", token),
getOption("stravaR.httr_oauth_cache")))
options("stravaR.app_name" = checkEnvFile("STRAVA_APP_NAME"))
options("stravaR.app_id" = checkEnvFile("STRAVA_APP_ID"))
options("stravaR.app_secret" = checkEnvFile("STRAVA_APP_SECRET"))
httr_file <- getOption("stravaR.httr_oauth_cache")
if(assertthat::is.flag(httr_file)){
stop("option('stravaR.httr_oauth_cache') must be set to
valid cache file location,
not TRUE or FALSE - (example: '.httr-oauth')",
call. = FALSE)
}
assertthat::assert_that(assertthat::is.string(httr_file),
assertthat::is.flag(new_user))
if(new_user){
rm_old_user_cache(httr_file)
}
if(is.null(token)) { ## supplied no token
strava_token <- create_strava_token()
} else if(is.token2.0(token)){ ## supplied a Token object
legit <- is_legit_token(token)
if(!legit){
stop("Invalid token passed to function", call. = FALSE)
}
StravaAuth$set("public", "method", "passed_token", overwrite=TRUE)
## set the global session token
StravaAuth$set("public", "token", token, overwrite=TRUE)
## just return it back
strava_token <- token
} else if(assertthat::is.string(token)){ ## a filepath
if(file.exists(token)){
strava_token <- read_cache_token(token_path = token)
} else {
cat(crayon::red(paste0("No httr_oauth_cache file found at ", token, " - creating new file.\n")))
options("stravaR.httr_oauth_cache" = token)
StravaAuth$set("public", "token", NULL, overwrite=TRUE)
return(strava_auth(token = NULL))
}
} else {
stop("Unrecognised token object - class ", class(token), call. = FALSE)
}
strava_check_existing_token()
## return strava_token above
cat(crayon::green("Successfully authenticated Strava API!\n"))
return(invisible(strava_token))
}
#' @noRd
#' @importFrom httr oauth_endpoints oauth_app oauth2.0_token
#' @import httpuv
create_strava_token <- function(){
check_existing <- strava_check_existing_token()
if(!check_existing){
cat(crayon::red("Auto-refresh of token not possible, manual re-authentication required\n"))
if(!interactive()){
stop("Authentication options didn't match existing session token and not interactive session
so unable to manually reauthenticate", call. = FALSE)
}
}
endpoint <- oauth_endpoint(request = "https://www.strava.com/oauth/authorize?",
authorize = "https://www.strava.com/oauth/authorize",
access = "https://www.strava.com/oauth/token")
app_name <- getOption("stravaR.app_name", "")
app_client_id <- getOption("stravaR.app_id", "")
app_secret <- getOption("stravaR.app_secret", "")
cache <- getOption("stravaR.httr_oauth_cache", "")
if(app_name == ""){
stop("option('stravaR.app_name') has not been set", call. = FALSE)
}
if(app_client_id == ""){
stop("option('stravaR.app_id') has not been set", call. = FALSE)
}
if(app_secret == ""){
stop("option('stravaR.app_secret') has not been set", call. = FALSE)
}
if(cache == ""){
stop("option('stravaR.httr_oauth_cache') has not been set", call. = FALSE)
}
app <- oauth_app(appname = app_name,
key = app_client_id,
secret = app_secret)
strava_token <- oauth2.0_token(endpoint = endpoint,
app = app,
scope = "public",
cache = cache)
stopifnot(is_legit_token(strava_token))
StravaAuth$set("public", "token", strava_token, overwrite=TRUE)
StravaAuth$set("public", "method", "new_token", overwrite=TRUE)
#strava_token
}
#' @noRd
rm_empty_token <- function(token_path = getOption("stravaR.httr_oauth_cache")){
## delete token if 0B
iz_0B <- file.info(token_path)$size == 0
if(iz_0B){
unlink(token_path)
}
}
#' @noRd
rm_old_user_cache <- function(httr_file){
StravaAuth$set("public", "token", NULL, overwrite=TRUE)
if(file.exists(httr_file)){
cat(crayon::red(paste0("Removing old cached credentials from: ", normalizePath(httr_file),"\n")))
file.remove(httr_file)
}
}
#' Reads a token from a filepath
#'
#' Also sets the option of token cache name to the supplied filepath
#' "stravaR.httr_oauth_cache"
#'
#' httr cache files such as .httr-oauth can hold multiple tokens for different scopes,
#' this only returns the first one and raises a warning if there are multiple
#' in the rds file
#' @noRd
#' @import assertthat
read_cache_token <- function(token_path){
assertthat::assert_that(assertthat::is.readable(token_path))
cat(crayon::red("Reading token from file path\n"))
strava_token <- tryCatch({readRDS(token_path)},
error = function(ex){
stop(sprintf("Cannot read token from alleged .rds file:\n%s",
token_path),
ex,
call. = FALSE)
})
if(is.list(strava_token)){
cat(crayon::red("Multiple httr-tokens in cache ",token_path, ", only returning first found token\n"))
strava_token <- strava_token[[1]]
} else if(is.token2.0(strava_token)){
cat(crayon::red("Read token successfully from file\n"))
} else {
stop("Unknown object read from ", token_path, " of class ", class(strava_token))
}
## for existing tokens, set the options to what is in the token
strava_token <- overwrite_options(strava_token, token_path = token_path)
StravaAuth$set("public", "method", "filepath", overwrite=TRUE)
## set the global session token
StravaAuth$set("public", "token", strava_token, overwrite=TRUE)
strava_token
}
strava_token_info <- function(detail_level = getOption("stravaR.verbose", default = 3)){
token <- StravaAuth$public_fields$token
method <- StravaAuth$public_fields$method
message <- ""
if(is.null(token)){
message <- c(message, "No token found\n")
return(NULL)
}
if(detail_level >= 3){
message <- c(message, paste0("Authentication from cache file: ", token$cache_path,"\n"))
}
if(detail_level <= 2){
if(!is.null(token$app$key)){
message <- c(message, paste0("App key: ", token$app$key,"\n"))
}
message <- c(message, paste0("Method: ", method,"\n"))
}
if(detail_level == 1){
message <- c(message, paste0("Hash: ", token$hash(),"\n"))
}
cat(crayon::red(message))
}
overwrite_options <- function(strava_token, token_path){
options("stravaR.httr_oauth_cache" = token_path)
strava_token$cache_path <- token_path
if(is.null(strava_token$app)){
cat(crayon::red("No App Client ID in token\n"))
return(strava_token)
}
if(is.different(strava_token$app$key, "stravaR.app_id")){
cat(crayon::red(paste0("Overwriting stravaR.app_id from", getOption("stravaR.app_id"),
"to ", strava_token$app$key,"\n")))
options("stravaR.app_id" = strava_token$app$key)
}
if(is.different(strava_token$app$secret, "stravaR.app_secret")){
cat(crayon::red(paste0("Overwriting stravaR.app_secret to ", strava_token$app$secret,"\n")))
options("stravaR.app_secret" = strava_token$app$secret)
}
if(is.different(strava_token$app$appname, "stravaR.app_name")){
cat(crayon::red(paste0("Overwriting stravaR.app_name to ", strava_token$app$appname,"\n")))
options("stravaR.app_name" = strava_token$app$appname)
}
strava_token
}
is.token2.0 <- function(x){
inherits(x, "Token2.0")
}
#' Retrieve Strava token from environment and configs for httr
#'
#' Get token if it's previously stored, else prompt user to get one.
#' @param shiny_return_token In a shiny session, this is passed instead.
#' @return a httr configured option for token
#' For shiny the token is passed from reactive session
#'
#' @keywords internal
#' @family authentication functions
#' @importFrom httr config
get_strava_token <- function(shiny_return_token=NULL) {
if(any(which(grepl("with_mock_API", as.character(sys.calls()))))){
cat(crayon::red("Skipping token checks as using with_mock_API\n"))
return(NULL)
}
if(is.null(shiny_return_token)){
token <- StravaAuth$public_fields$token
if(is.null(token) || !is_legit_token(token)) {
strava_auth()
}
} else { #shiny session
StravaAuth$set("public", "method", "shiny", overwrite=TRUE)
token <- shiny_return_token
}
config(token = token)
}
strava_auth()
strava_auth(token = "strava.httr-oath")
assertthat::is.string("strava.httr-oath")
file.exists("strava.httr-oauth")
read_cache_token(token_path = "strava.httr-oauth")
is.token2.0("strava.httr-oauth")
token = "strava.httr.oauth"
Sys.setenv(STRAVA_APP_NAME = app_name)
Sys.getenv("STRAVA_APP_NAME")
checkEnvFile <- function(env){
value <- Sys.getenv(env)
value <- ifelse(value == "", return(NULL), return(value))
}
options("stravaR.httr_oauth_cache" = ifelse(is.null(getOption("stravaR.httr_oauth_cache")),
ifelse(is.null(token), "strava.httr-oauth", token),
getOption("stravaR.httr_oauth_cache")))
options("stravaR.app_name" = checkEnvFile("STRAVA_APP_NAME"))
options("stravaR.app_id" = checkEnvFile("STRAVA_APP_ID"))
options("stravaR.app_secret" = checkEnvFile("STRAVA_APP_SECRET"))
httr_file <- getOption("stravaR.httr_oauth_cache")
httr_file
if(assertthat::is.flag(httr_file)){
stop("option('stravaR.httr_oauth_cache') must be set to
valid cache file location,
not TRUE or FALSE - (example: '.httr-oauth')",
call. = FALSE)
}
assertthat::assert_that(assertthat::is.string(httr_file),
assertthat::is.flag(new_user))
strava_auth()
strava_auth(token = "strava.httr-oauth")
strava_activities()
strava_activities(dateRange = c(Sys.Date()-4))
is.date()
assertthat::is.date()
is.date("das")
assertthat::is.date("das")
#' Get activities from Strava
#'
#' Get activities from the authenticated user as a data frame
#'
#' @param dateRange Between what dates the data should be collected. Must be in date format! c(date1, date2)
#'
#' @import httr
#' @import assertthat
#' @import plyr
#' @import rjson
#'
#' @export
#' @examples
#' strava_activities(dateRange = c(date1, date2))
strava_activities <- function(dateRange){
if(!strava_check_existing_token()){
return(invisible(FALSE))
} else if(missing(dateRange)){
stop("dateRange must be set!")
}
if(!assertthat::is.date(dateRange[1]) | !assertthat::is.date(dateRange[2])) {
stop("dateRange must contain two date variables: c(date1, date2)")
} else {
start <- as.integer(as.POSIXct(dateRange[1]))
end <- as.integer(as.POSIXct(dateRange[2]+1))
url <- paste0("https://www.strava.com/api/v3/activities/?after=",start,"&before=",end)
}
data <- GET(url, config(token = StravaAuth$public_fields$token))
data <- rjson::fromJSON(rawToChar(data$content))
activities <- NULL
for(i in 1:(length(data))){
if (!is.null(unlist(data[[i]]))){
act <- data.frame(matrix(unlist(data[[i]]), nrow=1))
colnames(act) <- names(unlist(data[[i]]))
activities <- plyr::rbind.fill(activities, act)
}
}
return(activities)
}
strava_activities(dateRange = c(Sys.Date()-4))
library(httr)
strava_activities(dateRange = c(Sys.Date()-4))
strava_activities(dateRange = c(Sys.Date()-4, Sys.Date()-3))
strava_activities(dateRange = c(Sys.Date()-4, Sys.Date()-1))
strava_activities(dateRange = c(Sys.Date()-2))
url <- paste0("https://www.strava.com/api/v3/activities/?after=",start,"&before=",end)
dateRange = c(Sys.Date()-4, Sys.Date()-1)
dateRange = c(Sys.Date()-4, Sys.Date()-2)
dateRange = c(Sys.Date()-4, Sys.Date()-3)
start <- as.integer(as.POSIXct(dateRange[1]))
end <- as.integer(as.POSIXct(dateRange[2]+1))
url <- paste0("https://www.strava.com/api/v3/activities/?after=",start,"&before=",end)
data <- GET(url, config(token = StravaAuth$public_fields$token))
data <- rjson::fromJSON(rawToChar(data$content))
data
is.null(data)
data.length
data.length()
length(data)
#' Get activities from Strava
#'
#' Get activities from the authenticated user as a data frame
#'
#' @param dateRange Between what dates the data should be collected. Must be in date format! c(date1, date2)
#'
#' @import httr
#' @import assertthat
#' @import plyr
#' @import rjson
#'
#' @export
#' @examples
#' strava_activities(dateRange = c(date1, date2))
strava_activities <- function(dateRange){
if(!strava_check_existing_token()){
return(invisible(FALSE))
} else if(missing(dateRange)){
stop("dateRange must be set!")
}
if(!assertthat::is.date(dateRange[1]) | !assertthat::is.date(dateRange[2])) {
stop("dateRange must contain two date variables: c(date1, date2)")
} else {
start <- as.integer(as.POSIXct(dateRange[1]))
end <- as.integer(as.POSIXct(dateRange[2]+1))
url <- paste0("https://www.strava.com/api/v3/activities/?after=",start,"&before=",end)
}
data <- GET(url, config(token = StravaAuth$public_fields$token))
data <- rjson::fromJSON(rawToChar(data$content))
if(length(data) == 0){
stop("Coudln't find any data during the chosen time period. Try a different time period.")
}
activities <- NULL
for(i in 1:(length(data))){
if (!is.null(unlist(data[[i]]))){
act <- data.frame(matrix(unlist(data[[i]]), nrow=1))
colnames(act) <- names(unlist(data[[i]]))
activities <- plyr::rbind.fill(activities, act)
}
}
return(activities)
}
strava_activities(dateRange = c(Sys.Date()-2))
strava_activities(dateRange = c(Sys.Date()-4, Sys.Date()-1))
strava_activities(dateRange = c(Sys.Date()-4, Sys.Date()-1)) -> df
View(df)
laps <- strava_laps(df$id)
#' Get laps from Strava
#'
#' Get laps information by the specific id or vector of ids
#'
#' @param data The activity id or vector of ids
#' @param lapType Wether to import custom laps from data, or standard. Defaults to custom. c("custom", "standard")
#'
#' @import httr
#' @import assertthat
#' @import plyr
#' @import rjson
#'
#'
#' @export
#' @examples
#' strava_laps(12345678, lapType = c("custom", "standard"))
strava_laps <- function(data, lapType = "custom"){
if(!strava_check_existing_token()){
return(invisible(FALSE))
} else if(!(lapType %in% c("custom","standard"))){
stop("lapType must contain 'custom' or 'standard'")
} else if(missing(data)){
stop("data must contain at least one activity id")
}
url <- paste0("https://www.strava.com/api/v3/activities/", data)
laps <- NULL
for(i in 1:(length(url))){
act <- GET(url[i], config(token = StravaAuth$public_fields$token))
if(act$status_code == "404"){
stop(paste0("Couldn't find the id: ",data[i]))
}
act <- rjson::fromJSON(rawToChar(act$content))
if(lapType == "custom"){
act <- act[['laps']]
} else {
act <- act[['splits_standard']]
}
for(j in 1:(length(act))){
df <- data.frame(matrix(unlist(act[[j]]), nrow=1))
colnames(df) <- names(unlist(act[[j]]))
df$activity.id <- data[i]
laps <- plyr::rbind.fill(laps, df)
}
}
return(laps)
}
laps <- strava_laps(df$id)
View(laps)
rm(list=ls())