blob: 53fbc1cad59623974f4a00774c211f5d869774f9 [file] [log] [blame]
Marc Kupietzfd9e7492019-11-08 15:45:18 +01001################################################################################
2# Use setClassUnion to define the unholy NULL-data union as a virtual class.
3################################################################################
4setClassUnion("characterOrNULL", c("character", "NULL"))
5
Marc Kupietze95108e2019-09-18 13:23:58 +02006#' Class KorAPConnection
Marc Kupietz25aebc32019-09-16 18:40:50 +02007#'
Akron5e135462019-09-27 16:31:38 +02008#' \code{KorAPConnection} objects represent the connection to a KorAP server.
9#' New \code{KorAPConnection} objects can be created by \code{KorAPConnection()}.
Marc Kupietze95108e2019-09-18 13:23:58 +020010#'
Marc Kupietz0a96b282019-10-01 11:05:31 +020011#' @import R.cache
Marc Kupietze95108e2019-09-18 13:23:58 +020012#' @import utils
13#' @import methods
Marc Kupietze95108e2019-09-18 13:23:58 +020014#' @export
Marc Kupietzfd9e7492019-11-08 15:45:18 +010015KorAPConnection <- setClass("KorAPConnection", slots=c(KorAPUrl="character", apiVersion="character", apiUrl="character", apiToken="characterOrNULL", userAgent="character", timeout="numeric", verbose="logical", cache="logical"))
Marc Kupietze95108e2019-09-18 13:23:58 +020016
17#' @param .Object KorAPConnection object
18#' @param KorAPUrl the URL of the KorAP server instance you want to access.
19#' @param apiVersion which version of KorAP's API you want to connect to.
20#' @param apiUrl URL of the KorAP web service.
Marc Kupietz4862b862019-11-07 10:13:53 +010021#' @param apiToken OAuth2 API token. To use authorization based on an API token
22#' in subsequent queries, intialize your KorAP connection with
23#' \code{kco <- new("KorAPConnection", apiToken="<API Token>")}.
24#' In order to make the API
25#' token persistent for the currently used \code{KorAPUrl} (you can have one
26#' token per KorAPUrl / KorAP server instance), use
27#' \code{persistApiToken(kco)}. This will store it in your keyring using the
28#' \code{\link{keyring}} package. Subsequent new("KorAPConnection") calls will
29#' then automatically retrieve the token from your keying. To stop using a
30#' persisted token, call \code{clearApiToken(kco)}. Please note that for
31#' DeReKo, authorized queries will behave differently inside and outside the
32#' IDS, because of the special license situation. This concerns also cached
33#' results which do not take into account from where a request was issued. If
34#' you experience problems or unexpected results, please try \code{kco <-
35#' new("KorAPConnection", cache=FALSE)} or use
36#' \code{\link{clearCache}} to clear the cache completely.
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +020037#' @param userAgent user agent string.
38#' @param timeout time out in seconds.
Marc Kupietz4862b862019-11-07 10:13:53 +010039#' @param verbose logical. Decides whether following operations will default to
40#' be verbose.
41#' @param cache logical. Decides if API calls are cached locally. You can clear
42#' the cache with \code{\link{clearCache}()}.
43#' @return \code{\link{KorAPConnection}} object that can be used e.g. with
44#' \code{\link{corpusQuery}}
Marc Kupietze95108e2019-09-18 13:23:58 +020045#'
46#' @examples
Marc Kupietz5a519822019-09-20 21:43:52 +020047#' kcon <- new("KorAPConnection", verbose = TRUE)
Marc Kupietze95108e2019-09-18 13:23:58 +020048#' kq <- corpusQuery(kcon, "Ameisenplage")
Marc Kupietz5a519822019-09-20 21:43:52 +020049#' kq <- fetchAll(kq)
Marc Kupietz7915dc42019-09-12 17:44:58 +020050#'
Marc Kupietz4862b862019-11-07 10:13:53 +010051#' \dontrun{
52#' kcon <- new("KorAPConnection", verbose = TRUE, apiToken="e739u6eOzkwADQPdVChxFg")
53#' kq <- corpusQuery(kcon, "Ameisenplage", metadataOnly=FALSE)
54#' kq <- fetchAll(kq)
55#' kq@collectedMatches$snippet
56#' }
Marc Kupietz7915dc42019-09-12 17:44:58 +020057#'
Marc Kupietze95108e2019-09-18 13:23:58 +020058#' @rdname KorAPConnection-class
Marc Kupietz632cbd42019-09-06 16:04:51 +020059#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +020060setMethod("initialize", "KorAPConnection",
Marc Kupietz4862b862019-11-07 10:13:53 +010061 function(.Object, KorAPUrl = "https://korap.ids-mannheim.de/", apiVersion = 'v1.0', apiUrl, apiToken = getApiToken(KorAPUrl), userAgent = "R-KorAP-Client", timeout=10, verbose = FALSE, cache = TRUE) {
Marc Kupietze95108e2019-09-18 13:23:58 +020062 .Object <- callNextMethod()
63 m <- regexpr("https?://[^?]+", KorAPUrl, perl = TRUE)
64 .Object@KorAPUrl <- regmatches(KorAPUrl, m)
65 if (!endsWith(.Object@KorAPUrl, '/')) {
66 .Object@KorAPUrl <- paste0(.Object@KorAPUrl, "/")
67 }
68 if (missing(apiUrl)) {
69 .Object@apiUrl = paste0(.Object@KorAPUrl, 'api/', apiVersion, '/')
70 } else {
71 .Object@apiUrl = apiUrl
72 }
Marc Kupietz4862b862019-11-07 10:13:53 +010073 .Object@apiToken = apiToken
Marc Kupietze95108e2019-09-18 13:23:58 +020074 .Object@apiVersion = apiVersion
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +020075 .Object@userAgent = userAgent
76 .Object@timeout = timeout
Marc Kupietz5a519822019-09-20 21:43:52 +020077 .Object@verbose = verbose
Marc Kupietz0a96b282019-10-01 11:05:31 +020078 .Object@cache = cache
Marc Kupietze95108e2019-09-18 13:23:58 +020079 .Object
80 })
81
Marc Kupietz4862b862019-11-07 10:13:53 +010082apiTokenServiceName <- "RKorAPClientAPIToken"
83
84setGeneric("persistApiToken", function(kco, apiToken) standardGeneric("persistApiToken") )
85
86#' @aliases persistApiToken
87#' @rdname KorAPConnection-class
88#' @import keyring
89#' @export
90#' @examples
91#' \dontrun{
92#' kco <- new("KorAPConnection", apiToken="e739u6eOzkwADQPdVChxFg")
93#' persistApiToken(kco)
94#' }
95#'
96setMethod("persistApiToken", "KorAPConnection", function(kco, apiToken = kco@apiToken) {
97 if (is.null(apiToken))
98 stop("It seems that you have not supplied any API token that could be persisted.", call. = FALSE)
99
100 kco@apiToken <- apiToken
101 key_set_with_value(apiTokenServiceName, kco@KorAPUrl, apiToken)
102})
103
104setGeneric("clearApiToken", function(kco) standardGeneric("clearApiToken") )
105
106#' @aliases clearApiToken
107#' @rdname KorAPConnection-class
108#' @import keyring
109#' @export
110#' @examples
111#' \dontrun{
112#' kco <- new("KorAPConnection")
113#' clearApiToken(kco)
114#' }
115#'
116setMethod("clearApiToken", "KorAPConnection", function(kco) {
117 key_delete("RKorAPClientAPIToken", kco@KorAPUrl)
118})
119
120#' @import keyring
121getApiToken <- function(KorAPUrl) {
Marc Kupietzfd9e7492019-11-08 15:45:18 +0100122 if ("keyring" %in% installed.packages()[,1 ]&& has_keyring_support()
123 && KorAPUrl %in% key_list(service = "RKorAPClientAPIToken"))
124 key_get("RKorAPClientAPIToken", KorAPUrl)
125 else
126 NULL
Marc Kupietz4862b862019-11-07 10:13:53 +0100127}
Marc Kupietz0a96b282019-10-01 11:05:31 +0200128
129KorAPCacheSubDir <- function() {
130 paste0("RKorAPClient_", packageVersion("RKorAPClient"))
131}
132
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200133setGeneric("apiCall", function(kco, ...) standardGeneric("apiCall") )
134
Marc Kupietz4de53ec2019-10-04 09:12:00 +0200135## quiets concerns of R CMD check re: the .'s that appear in pipelines
136if(getRversion() >= "2.15.1") utils::globalVariables(c("."))
137
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200138#' @aliases apiCall
139#' @rdname KorAPConnection-class
140#' @param kco KorAPConnection object
141#' @param url request url
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200142#' @importFrom jsonlite fromJSON
143#' @export
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200144setMethod("apiCall", "KorAPConnection", function(kco, url) {
Marc Kupietz0a96b282019-10-01 11:05:31 +0200145 if (kco@cache) {
Marc Kupietz4862b862019-11-07 10:13:53 +0100146 parsed <- R.cache::loadCache(dir=KorAPCacheSubDir(), key=list(url, kco@apiToken))
Marc Kupietz0a96b282019-10-01 11:05:31 +0200147 if (!is.null(parsed)) {
148 return(parsed)
149 }
150 }
Marc Kupietz4862b862019-11-07 10:13:53 +0100151 if (!is.null(kco@apiToken))
152 resp <- GET(url, user_agent(kco@userAgent), timeout(kco@timeout), add_headers(Authorization = paste("Bearer", kco@apiToken)))
153 else
154 resp <- GET(url, user_agent(kco@userAgent), timeout(kco@timeout))
Marc Kupietz46a57672019-09-27 18:11:31 +0200155 if (!http_type(resp) %in% c("application/json", "application/ld+json")) {
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200156 stop("API did not return json", call. = FALSE)
157 }
158 parsed <- jsonlite::fromJSON(content(resp, "text"))
159 if (!is.null(parsed$warnings)) {
160 message <- ifelse (nrow(parsed$warnings) > 1,
161 sapply(parsed$warnings, function(warning) paste(sprintf("%s: %s", warning[1], warning[2]), sep="\n")),
162 sprintf("%s: %s", parsed$warnings[1], parsed$warnings[2]))
163 warning(message, call. = FALSE)
164 }
165 if (status_code(resp) != 200) {
166 message <- ifelse (!is.null(parsed$errors),
Akron36def512019-09-27 17:30:51 +0200167 sapply(parsed$errors, function(error) paste0(sprintf("\n%s: KorAP API request failed: %s", error[1], error[2]))),
168 message <- sprintf("%s: KorAP API request failed.", status_code(resp)))
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200169 stop(message, call. = FALSE)
170 }
Marc Kupietz0a96b282019-10-01 11:05:31 +0200171 if (kco@cache) {
Marc Kupietz4862b862019-11-07 10:13:53 +0100172 R.cache::saveCache(parsed, key = list(url, kco@apiToken), dir = KorAPCacheSubDir(), compress = TRUE)
Marc Kupietz0a96b282019-10-01 11:05:31 +0200173 }
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200174 parsed
175})
176
Marc Kupietz0a96b282019-10-01 11:05:31 +0200177setGeneric("clearCache", function(kco) standardGeneric("clearCache") )
178
179#' @aliases clearCache
180#' @rdname KorAPConnection-class
181#' @export
182setMethod("clearCache", "KorAPConnection", function(kco) {
183 R.cache::clearCache(dir=KorAPCacheSubDir())
184})
185
Marc Kupietze95108e2019-09-18 13:23:58 +0200186#' @rdname KorAPConnection-class
187#' @param object KorAPConnection object
188#' @export
189setMethod("show", "KorAPConnection", function(object) {
190 cat("<KorAPConnection>", "\n")
191 cat("apiUrl: ", object@apiUrl, "\n")
192})
193
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200194##' Funtion KorAPConnection()
195##'
196##' Wrappper function for new("KorAPConnection")
197##'
198##' @rdname KorAPConnection-constructor
199##' @name KorAPConnection-constructor
200##' @export
201## XKorAPConnection <- function(...) new("KorAPConnection", ...)