Debian Codegraph @

R/server-resource-paths.R

raw
1 .globals$resourcePaths <- list()
2 .globals$resources <- list()
3
4 #' Resource Publishing
5 #'
6 #' Add, remove, or list directory of static resources to Shiny's web server,
7 #' with the given path prefix. Primarily intended for package authors to make
8 #' supporting JavaScript/CSS files available to their components.
9 #'
10 #' Shiny provides two ways of serving static files (i.e., resources):
11 #'
12 #' 1. Static files under the `www/` directory are automatically made available
13 #' under a request path that begins with `/`.
14 #' 2. `addResourcePath()` makes static files in a `directoryPath` available
15 #' under a request path that begins with `prefix`.
16 #'
17 #' The second approach is primarily intended for package authors to make
18 #' supporting JavaScript/CSS files available to their components.
19 #'
20 #' Tools for managing static resources published by Shiny's web server:
21 #' * `addResourcePath()` adds a directory of static resources.
22 #' * `resourcePaths()` lists the currently active resource mappings.
23 #' * `removeResourcePath()` removes a directory of static resources.
24 #'
25 #' @param prefix The URL prefix (without slashes). Valid characters are a-z,
26 #' A-Z, 0-9, hyphen, period, and underscore. For example, a value of 'foo'
27 #' means that any request paths that begin with '/foo' will be mapped to the
28 #' given directory.
29 #' @param directoryPath The directory that contains the static resources to be
30 #' served.
31 #'
32 #' @rdname resourcePaths
33 #' @seealso [singleton()]
34 #'
35 #' @examples
36 #' addResourcePath('datasets', system.file('data', package='datasets'))
37 #' resourcePaths()
38 #' removeResourcePath('datasets')
39 #' resourcePaths()
40 #'
41 #' # make sure all resources are removed
42 #' lapply(names(resourcePaths()), removeResourcePath)
43 #' @export
44 addResourcePath <- function(prefix, directoryPath) {
45 if (length(prefix) != 1) stop("prefix must be of length 1")
46 if (grepl("^\\.+$", prefix)) stop("prefix can't be composed of dots only")
47 if (!grepl('[a-z0-9\\-_.]+$', prefix, ignore.case = TRUE, perl = TRUE)) {
48 stop("addResourcePath called with invalid prefix; please see documentation")
49 }
50 if (prefix %in% c('shared')) {
51 stop("addResourcePath called with the reserved prefix '", prefix, "'; ",
52 "please use a different prefix")
53 }
54 normalizedPath <- tryCatch(normalizePath(directoryPath, mustWork = TRUE),
55 error = function(e) {
56 stop("Couldn't normalize path in `addResourcePath`, with arguments: ",
57 "`prefix` = '", prefix, "'; `directoryPath` = '" , directoryPath, "'")
58 }
59 )
60
61 # # Often times overwriting a resource path is "what you want",
62 # # but sometimes it can lead to difficult to diagnose issues
63 # # (e.g. an implict dependency might set a resource path that
64 # # conflicts with what you, the app author, are trying to register)
65 # # Note that previous versions of shiny used to warn about this case,
66 # # but it was eventually removed since it caused confusion (#567).
67 # # It seems a good compromise is to throw a more information message.
68 # if (getOption("shiny.resourcePathChanges", FALSE) &&
69 # prefix %in% names(.globals$resourcePaths)) {
70 # existingPath <- .globals$resourcePaths[[prefix]]$path
71 # if (normalizedPath != existingPath) {
72 # message(
73 # "The resource path '", prefix, "' used to point to ",
74 # existingPath, ", but it now points to ", normalizedPath, ". ",
75 # "If your app doesn't work as expected, you may want to ",
76 # "choose a different prefix name."
77 # )
78 # }
79 # }
80
81 # If a shiny app is currently running, dynamically register this path with
82 # the corresponding httpuv server object.
83 if (!is.null(getShinyOption("server", default = NULL)))
84 {
85 getShinyOption("server")$setStaticPath(.list = stats::setNames(normalizedPath, prefix))
86 }
87
88 # .globals$resourcePaths and .globals$resources persist across runs of applications.
89 .globals$resourcePaths[[prefix]] <- staticPath(normalizedPath)
90 # This is necessary because resourcePaths is only for serving assets out of C++;
91 # to support subapps, we also need assets to be served out of R, because those
92 # URLs are rewritten by R code (i.e. routeHandler) before they can be matched to
93 # a resource path.
94 .globals$resources[[prefix]] <- list(
95 directoryPath = normalizedPath,
96 func = staticHandler(normalizedPath)
97 )
98 }
99
100 #' @rdname resourcePaths
101 #' @export
102 resourcePaths <- function() {
103 urls <- names(.globals$resourcePaths)
104 paths <- vapply(.globals$resourcePaths, function(x) x$path, character(1))
105 stats::setNames(paths, urls)
106 }
107
108 hasResourcePath <- function(prefix) {
109 prefix %in% names(resourcePaths())
110 }
111
112 #' @rdname resourcePaths
113 #' @export
114 removeResourcePath <- function(prefix) {
115 if (length(prefix) > 1) stop("`prefix` must be of length 1.")
116 if (!hasResourcePath(prefix)) {
117 warning("Resource ", prefix, " not found.")
118 return(invisible(FALSE))
119 }
120 .globals$resourcePaths[[prefix]] <- NULL
121 .globals$resources[[prefix]] <- NULL
122 invisible(TRUE)
123 }
124
125 # This function handles any GET request with two or more path elements where the
126 # first path element matches a prefix that was previously added using
127 # addResourcePath().
128 #
129 # For example, if `addResourcePath("foo", "~/bar")` was called, then a GET
130 # request for /foo/one/two.html would rewrite the PATH_INFO as /one/two.html and
131 # send it to the resource path function for "foo". As of this writing, that
132 # function will always be a staticHandler, which serves up a file if it exists
133 # and NULL if it does not.
134 #
135 # Since Shiny 1.3.x, assets registered via addResourcePath should mostly be
136 # served out of httpuv's native static file serving features. However, in the
137 # specific case of subapps, the R code path must be used, because subapps insert
138 # a giant random ID into the beginning of the URL that must be stripped off by
139 # an R route handler (see addSubApp()).
140 resourcePathHandler <- function(req) {
141 if (!identical(req$REQUEST_METHOD, 'GET'))
142 return(NULL)
143
144 # e.g. "/foo/one/two.html"
145 path <- req$PATH_INFO
146
147 match <- regexpr('^/([^/]+)/', path, perl=TRUE)
148 if (match == -1)
149 return(NULL)
150 len <- attr(match, 'capture.length')
151 # e.g. "foo"
152 prefix <- substr(path, 2, 2 + len - 1)
153
154 resInfo <- .globals$resources[[prefix]]
155 if (is.null(resInfo))
156 return(NULL)
157
158 # e.g. "/one/two.html"
159 suffix <- substr(path, 2 + len, nchar(path))
160
161 # Create a new request that's a clone of the current request, but adjust
162 # PATH_INFO and SCRIPT_NAME to reflect that we have already matched the first
163 # path element (e.g. "/foo"). See routeHandler() for more info.
164 subreq <- as.environment(as.list(req, all.names=TRUE))
165 subreq$PATH_INFO <- suffix
166 subreq$SCRIPT_NAME <- paste(subreq$SCRIPT_NAME, substr(path, 1, 2 + len), sep='')
167
168 return(resInfo$func(subreq))
169 }