| Marc Kupietz | a93a272 | 2021-04-28 12:22:45 +0200 | [diff] [blame] | 1 | #' 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 Kupietz | 71c8975 | 2023-07-28 15:58:12 +0200 | [diff] [blame^] | 9 | #' @importFrom stringr str_replace str_replace_all str_split | 
| Marc Kupietz | d07b8eb | 2023-04-22 23:23:18 +0200 | [diff] [blame] | 10 | #' | 
| Marc Kupietz | a93a272 | 2021-04-28 12:22:45 +0200 | [diff] [blame] | 11 | #' @examples | 
|  | 12 | #' \dontrun{ | 
|  | 13 | #' df <- getUserCountry("https://demo.matomo.org/", siteId=3, period="day", date="last60") | 
|  | 14 | #' } | 
|  | 15 | #' | 
|  | 16 | #' @export | 
|  | 17 | getUserCountry <- function(matomoUrl, | 
|  | 18 | siteId, | 
|  | 19 | period = "month", | 
|  | 20 | date = "last36", | 
|  | 21 | filter_limit = 100, | 
|  | 22 | accessToken = getAccessToken(matomoUrl) | 
|  | 23 | ) { | 
| Marc Kupietz | 71c8975 | 2023-07-28 15:58:12 +0200 | [diff] [blame^] | 24 | 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 Kupietz | a93a272 | 2021-04-28 12:22:45 +0200 | [diff] [blame] | 51 | } |