blob: 62075e1d02747c5ddee66c7e209f6713438a084e [file] [log] [blame]
Marc Kupietza93a2722021-04-28 12:22:45 +02001#' Get user country report from matomo API server
2#'
3#' See matomo Reporting API Reference (\url{https://developer.matomo.org/api-reference/reporting-api}) for details.
4#'
5#' @references \url{https://developer.matomo.org/api-reference/reporting-api}
6#'
7#' @inheritParams matomoQuery
8#'
Marc Kupietz71c89752023-07-28 15:58:12 +02009#' @importFrom stringr str_replace str_replace_all str_split
Marc Kupietzd07b8eb2023-04-22 23:23:18 +020010#'
Marc Kupietza93a2722021-04-28 12:22:45 +020011#' @examples
12#' \dontrun{
13#' df <- getUserCountry("https://demo.matomo.org/", siteId=3, period="day", date="last60")
14#' }
15#'
16#' @export
17getUserCountry <- function(matomoUrl,
18 siteId,
19 period = "month",
20 date = "last36",
21 filter_limit = 100,
22 accessToken = getAccessToken(matomoUrl)
23) {
Marc Kupietz71c89752023-07-28 15:58:12 +020024 result <- list()
25 MAX_RETRIES <- 5
26 retry_count <- 0
27
28 while (length(result) == 0 && retry_count < MAX_RETRIES) {
29 result <- matomoQuery(matomoUrl = matomoUrl,
30 siteId = siteId,
31 period = period,
32 date = str_replace_all(str_replace_all(date, " *UTC", ""), "-00", "-01"),
33 removeFirst = FALSE,
34 removeLast = FALSE,
35 accessToken = accessToken,
36 getMethod = "UserCountry.getCountry",
37 ignoreEmptyResult = retry_count < MAX_RETRIES)
38
39 if (length(result) == 0 && retry_count < MAX_RETRIES) {
40 msg <- paste0("UserCountry.getCountry returned an empty list (known MATOMO bug). Changing date range from ", date, " to ")
41 retry_count <- retry_count + 1
42 startend <- str_split(date, ",", simplify = T)
43 l <- str_split(startend[1], "-", simplify = T)
44 l[3] <- sprintf("%02d", as.numeric(l[3]) + 1)
45 date <- paste0(paste0(l, collapse = "-"), ",", startend[2])
46 msg <- paste0(msg, date, "\n")
47 warning(msg)
48 }
49 }
50 return(result)
Marc Kupietza93a2722021-04-28 12:22:45 +020051}