blob: cfdfb86bb842e649ede65e2a0a471fc947147b15 [file] [log] [blame]
Marc Kupietza93a2722021-04-28 12:22:45 +02001#' Get reports from a 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#' @param matomoUrl base URL of your matomo instance
8#' @param siteId matomo site id or vector of site ids
9#' @param period \code{day}, \code{week}, \code{month} or \code{year}
10#' @param date date range (see \url{https://developer.matomo.org/api-reference/reporting-api})
11#' @param filter_limit defines the maximum number of rows to be returned
12#' @param removeFirst logical that determines whether the first row of each site should be removed (to account for incomplete periods)
13#' @param removeLast logical that determines whether the last row of each site should be removed (to account for incomplete periods)
14#' @param accessToken API Authentication Token - you can get this in your
15#' matomo interface under Settings -> Personal -> Settings -> API Authentication Token
16#' and pass it here, or you can make it persistent with \code{\link{persistAccessToken}}.
17#' @param getMethod API method to call – default: VisitsSummary.get
18#' @return Data frame with visits summary as returned by matomo. Note that the \code{date} column in the returned data frame refers to the first day of the respective period.
19#'
Marc Kupietz39dd9332023-05-06 18:07:18 +020020#' @importFrom httr2 request req_url_query req_perform resp_body_json resp_body_raw req_error
Marc Kupietza93a2722021-04-28 12:22:45 +020021#' @importFrom jsonlite fromJSON
22#' @importFrom dplyr mutate rowwise bind_rows select summarise n
23#' @import tibble
24#' @importFrom magrittr %>%
Marc Kupietzd07b8eb2023-04-22 23:23:18 +020025#' @importFrom stringr str_replace str_replace_all
Marc Kupietza93a2722021-04-28 12:22:45 +020026#' @importFrom utils head tail
27#'
28#' @examples
29#' \dontrun{
30#' df <- matomoQuery("https://demo.matomo.org/", getMethod = "UserCountry.getCountry")
31#' }
32#'
33#' @export
34matomoQuery <- function(matomoUrl,
35 siteId,
36 period = "month",
37 date = "last16",
Marc Kupietz0ec50522022-04-09 15:53:24 +020038 filter_limit = 500,
Marc Kupietza93a2722021-04-28 12:22:45 +020039 removeFirst = FALSE,
40 removeLast = FALSE,
41 accessToken = getAccessToken(matomoUrl),
42 getMethod = "VisitsSummary.get"
43) {
Marc Kupietzf17fb822023-04-21 20:54:56 +020044 if ((is.null(accessToken) || accessToken == '' ) && matomoUrl != "https://demo.matomo.org/") {
Marc Kupietza93a2722021-04-28 12:22:45 +020045 stop(
46 paste0(
47 "You must first set an access token with:\n\npersistAccessToken(\"",
48 matomoUrl,
49 "\", <token>)\n\nYou can get the token in your matomo interface under Settings -> Personal -> Security -> Auth token\nprobably at:\n\n", matomoUrl, "index.php?module=UsersManager&action=userSecurity\n\n"
50 ),
51 call. = FALSE
52 )
53 }
Marc Kupietz39dd9332023-05-06 18:07:18 +020054 res <- httr2::request(matomoUrl) %>%
55 httr2::req_url_query(
Marc Kupietza93a2722021-04-28 12:22:45 +020056 module = "API",
Marc Kupietz0ec50522022-04-09 15:53:24 +020057 method = getMethod,
Marc Kupietza93a2722021-04-28 12:22:45 +020058 format = "json",
Marc Kupietza93a2722021-04-28 12:22:45 +020059 idSite = paste0(siteId, collapse = ","),
Marc Kupietzd07b8eb2023-04-22 23:23:18 +020060 date = str_replace_all(date, " *UTC", ""),
Marc Kupietza93a2722021-04-28 12:22:45 +020061 period = period,
62 filter_limit = filter_limit,
Marc Kupietzea986d02021-04-28 15:54:23 +020063 language = "de",
Marc Kupietza93a2722021-04-28 12:22:45 +020064 token_auth = accessToken
Marc Kupietz39dd9332023-05-06 18:07:18 +020065 ) %>%
66 httr2::req_error(body = error_body) %>%
67 httr2::req_perform()
Marc Kupietza93a2722021-04-28 12:22:45 +020068
Marc Kupietz39dd9332023-05-06 18:07:18 +020069 l <-res %>% httr2::resp_body_json()
Marc Kupietza93a2722021-04-28 12:22:45 +020070
Marc Kupietz39dd9332023-05-06 18:07:18 +020071 if("result" %in% names(l) && l[["result"]] == 'error') {
72 stop(paste("In api call", res$url, ":", l[["message"]], "\n"), call. = FALSE)
Marc Kupietzf17fb822023-04-21 20:54:56 +020073 }
74
Marc Kupietz0ec50522022-04-09 15:53:24 +020075 if (period=="range") {
Marc Kupietzd07b8eb2023-04-22 23:23:18 +020076 df <- if (is.list(l) && length(l) == 0) {
Marc Kupietz39dd9332023-05-06 18:07:18 +020077 stop(paste0("API call ", res$url, " returned the empty list [].\n"), call. = FALSE)
78 } else if (is.list(l)) {
79 df <- bind_rows(l)
Marc Kupietzd07b8eb2023-04-22 23:23:18 +020080 } else if (length(siteId) == 1) {
81 l %>% mutate(site_id=siteId)
Marc Kupietz0ec50522022-04-09 15:53:24 +020082 } else {
Marc Kupietz39dd9332023-05-06 18:07:18 +020083 bind_rows(l, .id = "site_id")
Marc Kupietza93a2722021-04-28 12:22:45 +020084 }
Marc Kupietz0ec50522022-04-09 15:53:24 +020085 } else {
Marc Kupietz0ec50522022-04-09 15:53:24 +020086 df <- (if (length(siteId) == 1) {
87 bind_rows(l, .id=period) %>%
88 head(if(removeLast) -1 else filter_limit) %>%
89 tail(if(removeFirst) -1 else filter_limit) %>%
90 mutate(site_id=siteId)
91 } else {
92 df <- bind_rows(l[[1]], .id=period) %>%
93 head(if(removeLast) -1 else filter_limit) %>%
94 tail(if(removeFirst) -1 else filter_limit) %>%
95 mutate(site_id=siteId[1])
96 for (i in 2:length(l)) {
97 df <- bind_rows(df,
98 bind_rows(l[[i]], .id=period) %>%
99 head(if(removeLast) -1 else filter_limit) %>%
100 tail(if(removeFirst) -1 else filter_limit) %>%
101 mutate(site_id=siteId[i]))
102 }
103 df
104 })
105 }
Marc Kupietza93a2722021-04-28 12:22:45 +0200106
107 if("day" %in% colnames(df) | "month" %in% colnames(df) | "ye" %in% colnames(df)) {
108 df <- df %>%
109 mutate(date = as.Date(
110 if (period == "month")
111 paste0(month, "-01")
112 else if (period == "year")
113 paste0(year, "-01-01")
114 else if (period == "week")
115 sub(",.*", "", week)
116 else if (period == "day")
117 day
118 else
119 stop(paste0("unsupported period parameter: '", period, "'"), call. = FALSE)
Marc Kupietz0ec50522022-04-09 15:53:24 +0200120 , optional = TRUE))
Marc Kupietza93a2722021-04-28 12:22:45 +0200121 }
122 return(df)
123}
124
Marc Kupietz39dd9332023-05-06 18:07:18 +0200125
126error_body <- function(resp) {
127 return(paste0("getting ", resp$url))
128}
129
Marc Kupietza93a2722021-04-28 12:22:45 +0200130utils::globalVariables(c("year", "month", "day", "week"))
131
132#' Save access token persistently to your keyring
133#'
134#' @param matomoUrl base URL of your matomo instance
135#' @param accessToken your oauth token
136#' @param id supply if you have multiple IDs, i.e. logins to your matomo instance
137#'
138#' @import keyring
139#'
140#' @export
141#'
142#' @examples
143#' persistAccessToken("https://demo.matomo.org/", "ad7609a669179c4ebca7c995342f7e09")
144#'
145persistAccessToken <- function(matomoUrl, accessToken, id="default") {
146 if (is.null(accessToken))
147 stop("It seems that you have not supplied any access token that could be persisted.", call. = FALSE)
148
149 keyring::key_set_with_value(matomoUrl, username=id, password=accessToken, keyring = NULL)
150}
151
152clearAccessToken <- function(matomoUrl, id="default") {
153 key_delete(matomoUrl, id)
154}
155
156
Marc Kupietza93a2722021-04-28 12:22:45 +0200157#' get access token for matomo from keyring
158#'
159#' @param matomoUrl base URL of your matomo instance
160#' @param id supply if you have multiple IDs, i.e. logins to your matomo instance
161#'
162#' @return access token
163#' @export
164#'
165#' @import keyring
166#'
167getAccessToken <- function(matomoUrl, id="default") {
168 keyList <- tryCatch(withCallingHandlers(key_list(service = matomoUrl),
169 warning = function(w) invokeRestart("muffleWarning"),
170 error = function(e) return(NULL)),
171 error = function(e) { })
172 if (id %in% keyList)
173 key_get(matomoUrl, id)
174 else
175 NULL
176}
177
178