-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_ga_basic.R
More file actions
74 lines (73 loc) · 2.7 KB
/
get_ga_basic.R
File metadata and controls
74 lines (73 loc) · 2.7 KB
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
#' Get Basic Google Analytics Info
#'
#' This function takes a character vector of NIH Core Project Numbers and
#' returns a data frame containing the any Google Analytics properties associated
#' with the Core Project Numbers.
#'
#' @param core_project_numbers A character vector of NIH Core Project Numbers
#' @param service_account_json A character string containing the path to a JSON file containing the
#' Google service account credentials. If no file is provided, interactive authentication is used.
#' Defaults to "cfde-access-keyfile.json"
#'
#' @importFrom googleAnalyticsR ga_account_list ga_auth
#' @importFrom purrr map map_chr
#' @importFrom stringr str_remove
#' @importFrom tidyr separate
#' @importFrom rlang .data
#'
#' @return A data frame containing the associated Google Analytics data
#' @export
get_ga_basic <- function(core_project_numbers, service_account_json = 'cfde-access-keyfile.json') {
## This function requires authentication, check for existing creds
## Package Credentials
if(file.exists(system.file("secret", service_account_json, package = "programets")) &&
!is.null(Sys.getenv("CFDE_ENCRYPTION_KEY"))){
programets_service_account <- gargle::secret_decrypt_json(
path = system.file(
"secret",
service_account_json,
package = "programets"
),
key = "CFDE_ENCRYPTION_KEY"
)
googleAnalyticsR::ga_auth(
json_file = programets_service_account
)
## User SA Credentials
} else if (file.exists(service_account_json)) {
ga_auth(json_file = service_account_json)
## Interactive Auth
} else {
ga_auth()
}
## Get All Analytics Properties
core_project_regex <- paste0(unique(tolower(core_project_numbers)), collapse = "|")
account_list <- ga_account_list("ga4") |>
mutate(
property_meta = suppressMessages(map(.data$propertyId, get_ga_meta_by_id)),
core_project_num = map_chr(
.data$property_meta,
~{
res <- .x |>
filter(str_detect(apiName, regex(core_project_regex, ignore_case = TRUE))) |>
tidyr::separate(apiName, into = c("api", "value"), sep = ":", remove = FALSE) |>
pull(value)
if (length(res) == 0) {
NA_character_
} else {
res |>
str_remove("^cfde_") |>
unique() |>
paste(collapse = ",")
}
}
)
) |>
## Filter to those with the requested Core Project Numbers
filter(!is.na(.data$core_project_num)) |>
select(-'property_meta')
if(nrow(account_list) == 0) {
rlang::inform(rlang::format_error_bullets(c(i = "No Google Analytics properties found for the requested Core Project Numbers")))
}
return(account_list)
}