blob: 62075e1d02747c5ddee66c7e209f6713438a084e [file] [log] [blame]
#' Get user country report from matomo API server
#'
#' See matomo Reporting API Reference (\url{https://developer.matomo.org/api-reference/reporting-api}) for details.
#'
#' @references \url{https://developer.matomo.org/api-reference/reporting-api}
#'
#' @inheritParams matomoQuery
#'
#' @importFrom stringr str_replace str_replace_all str_split
#'
#' @examples
#' \dontrun{
#' df <- getUserCountry("https://demo.matomo.org/", siteId=3, period="day", date="last60")
#' }
#'
#' @export
getUserCountry <- function(matomoUrl,
siteId,
period = "month",
date = "last36",
filter_limit = 100,
accessToken = getAccessToken(matomoUrl)
) {
result <- list()
MAX_RETRIES <- 5
retry_count <- 0
while (length(result) == 0 && retry_count < MAX_RETRIES) {
result <- matomoQuery(matomoUrl = matomoUrl,
siteId = siteId,
period = period,
date = str_replace_all(str_replace_all(date, " *UTC", ""), "-00", "-01"),
removeFirst = FALSE,
removeLast = FALSE,
accessToken = accessToken,
getMethod = "UserCountry.getCountry",
ignoreEmptyResult = retry_count < MAX_RETRIES)
if (length(result) == 0 && retry_count < MAX_RETRIES) {
msg <- paste0("UserCountry.getCountry returned an empty list (known MATOMO bug). Changing date range from ", date, " to ")
retry_count <- retry_count + 1
startend <- str_split(date, ",", simplify = T)
l <- str_split(startend[1], "-", simplify = T)
l[3] <- sprintf("%02d", as.numeric(l[3]) + 1)
date <- paste0(paste0(l, collapse = "-"), ",", startend[2])
msg <- paste0(msg, date, "\n")
warning(msg)
}
}
return(result)
}