| 1 |
#' Encode/decode data into/from base64 encoding. |
| 2 |
#' |
| 3 |
#' The function `base64_encode()` encodes a file or a raw vector into the |
| 4 |
#' base64 encoding. The function `base64_decode()` decodes data from the |
| 5 |
#' base64 encoding. |
| 6 |
#' @param x For `base64_encode()`, a raw vector. If not raw, it is assumed |
| 7 |
#' to be a file or a connection to be read via `readBin()`. For |
| 8 |
#' `base64_decode()`, a string. |
| 9 |
#' @param from If provided (and `x` is not provided), a connection or file |
| 10 |
#' to be read via `readChar()`, and the result will be passed to the |
| 11 |
#' argument `x`. |
| 12 |
#' @return `base64_encode()` returns a character string. |
| 13 |
#' `base64_decode()` returns a raw vector. |
| 14 |
#' @useDynLib xfun, .registration = TRUE |
| 15 |
#' @export |
| 16 |
#' @examples xfun::base64_encode(as.raw(1:10)) |
| 17 |
#' logo = xfun:::R_logo() |
| 18 |
#' xfun::base64_encode(logo) |
| 19 |
base64_encode = function(x) { |
| 20 |
if (!is.raw(x)) x = read_bin(x) |
| 21 |
.Call('base64_enc', x, PACKAGE = 'xfun') |
| 22 |
} |
| 23 |
|
| 24 |
#' @export |
| 25 |
#' @rdname base64_encode |
| 26 |
#' @examples xfun::base64_decode("AQIDBAUGBwgJCg==") |
| 27 |
base64_decode = function(x, from = NA) { |
| 28 |
if (!is.na(from)) { |
| 29 |
if (!missing(x)) stop("Please provide either 'x' or 'from', but not both.") |
| 30 |
x = readChar(from, file.size(from), TRUE) |
| 31 |
} |
| 32 |
if (!is.character(x) || length(x) != 1) stop("'x' must be a single character string.") |
| 33 |
.Call('base64_dec', x, PACKAGE = 'xfun') |
| 34 |
} |
| 35 |
|
| 36 |
# an R implementation of base64 encoding by Wush Wu moved from knitr (of |
| 37 |
# historic interest only): https://github.com/yihui/knitr/pull/324 |
| 38 |
base64_encode_r = function(x) { |
| 39 |
if (!is.raw(x)) x = read_bin(x) |
| 40 |
chars = c(LETTERS, letters, 0:9, '+', '/') |
| 41 |
n = length(s <- as.integer(x)) |
| 42 |
res = rep(NA, (n + 2) / 3 * 4) |
| 43 |
i = 0L # index of res vector |
| 44 |
j = 1L # index of base64_table |
| 45 |
while (n > 2L) { |
| 46 |
res[i <- i + 1L] = chars[s[j] %/% 4L + 1L] |
| 47 |
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + s[j + 1L] %/% 16 + 1L] |
| 48 |
res[i <- i + 1L] = chars[4L * (s[j + 1L] %% 16) + s[j + 2L] %/% 64L + 1L] |
| 49 |
res[i <- i + 1L] = chars[s[j + 2L] %% 64L + 1L] |
| 50 |
j = j + 3L |
| 51 |
n = n - 3L |
| 52 |
} |
| 53 |
if (n) { |
| 54 |
res[i <- i + 1L] = chars[s[j] %/% 4L + 1L] |
| 55 |
if (n > 1L) { |
| 56 |
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + s[j + 1L] %/% 16 + 1L] |
| 57 |
res[i <- i + 1L] = chars[4L * (s[j + 1L] %% 16) + 1L] |
| 58 |
res[i <- i + 1L] = '=' |
| 59 |
} else { |
| 60 |
res[i <- i + 1L] = chars[16 * (s[j] %% 4L) + 1L] |
| 61 |
res[i <- i + 1L] = '=' |
| 62 |
res[i <- i + 1L] = '=' |
| 63 |
} |
| 64 |
} |
| 65 |
paste(res[!is.na(res)], collapse = '') |
| 66 |
} |
| 67 |
|
| 68 |
#' Generate the Data URI for a file |
| 69 |
#' |
| 70 |
#' Encode the file in the base64 encoding, and add the media type. The data URI |
| 71 |
#' can be used to embed data in HTML documents, e.g., in the `src` attribute of |
| 72 |
#' the `<img />` tag. |
| 73 |
#' @param x A file path. |
| 74 |
#' @param type The MIME type of the file, e.g., `"image/png"` for a PNG image |
| 75 |
#' file. |
| 76 |
#' @return A string of the form `data:<media type>;base64,<data>`. |
| 77 |
#' @export |
| 78 |
#' @examples |
| 79 |
#' logo = xfun:::R_logo() |
| 80 |
#' img = xfun::html_tag('img', src = xfun::base64_uri(logo), alt = "R logo") |
| 81 |
#' if (interactive()) xfun::html_view(img) |
| 82 |
base64_uri = function(x, type = mime_type(x)) { |
| 83 |
paste0("data:", type, ";base64,", base64_encode(x)) |
| 84 |
} |
| 85 |
|
| 86 |
#' Get the MIME types of files |
| 87 |
#' |
| 88 |
#' If the \pkg{mime} package is installed, call [mime::guess_type()], otherwise |
| 89 |
#' use the system command `file --mime-type` to obtain the MIME type of a file. |
| 90 |
#' Typically, the `file` command exists on *nix. On Windows, the command should |
| 91 |
#' exist if Cygwin or Rtools is installed. If it is not found, .NET's |
| 92 |
#' `MimeMapping` class will be used instead (which requires the .NET framework). |
| 93 |
#' @param x A vector of file paths. |
| 94 |
#' @param use_mime Whether to use the \pkg{mime} package. |
| 95 |
#' @param empty The MIME type for files without extensions (e.g., `Makefile`). |
| 96 |
#' If `NA`, the type will be obtained from system command. This argument is |
| 97 |
#' used only for `use_mime = FALSE`. |
| 98 |
#' @return A character vector of MIME types. |
| 99 |
#' @note When querying the MIME type via the system command, the result will be |
| 100 |
#' cached to `xfun:::cache_dir()`. This will make future queries much faster, |
| 101 |
#' since running the command in real time can be a little slow. |
| 102 |
#' @export |
| 103 |
#' @examplesIf tolower(Sys.getenv('CI')) == 'true' |
| 104 |
#' f = list.files(R.home('doc'), full.names = TRUE) |
| 105 |
#' mime_type(f) |
| 106 |
#' mime_type(f, FALSE) # don't use mime |
| 107 |
#' mime_type(f, FALSE, NA) # run command for files without extension |
| 108 |
mime_type = function(x, use_mime = loadable('mime'), empty = 'text/plain') { |
| 109 |
if (use_mime) return(mime::guess_type(x)) |
| 110 |
ext = tolower(file_ext(x)) |
| 111 |
res = character(n <- length(x)) |
| 112 |
# try to read from cache since running command in real time can be slow |
| 113 |
p = file.path(cache_dir(), 'mime.rds') |
| 114 |
db = mimemap |
| 115 |
for (i in seq_len(n)) { |
| 116 |
e = ext[i] |
| 117 |
m = if (e == '') empty else .mime_type(x[i], e) |
| 118 |
if (is.na(m) && is.na(m <- db[e])) { |
| 119 |
if (file_exists(p)) db = readRDS(p) |
| 120 |
m = db[e] |
| 121 |
} |
| 122 |
if (is.na(m)) { |
| 123 |
m = .mime_cmd(x[i]) |
| 124 |
if (grepl('^[a-zA-Z]+/[-a-zA-Z0-9.+]+$', m)) { |
| 125 |
if (e != '') { |
| 126 |
db[e] = m; if (dir_create(dirname(p))) saveRDS(db, p) |
| 127 |
} |
| 128 |
} else warning("'", m, "' does not appear to be a valid MIME type for '", x[i], "'") |
| 129 |
} |
| 130 |
res[i] = m |
| 131 |
} |
| 132 |
res |
| 133 |
} |
| 134 |
|
| 135 |
# try to get the MIME type from tools:::mime_type() |
| 136 |
.mime_type = function(x, ext = file_ext(x)) { |
| 137 |
if (ext != '' && is.function(f <- asNamespace('tools')$mime_type)) { |
| 138 |
m = f(x, ext) |
| 139 |
if (m != 'text/plain') return(m) |
| 140 |
} |
| 141 |
NA |
| 142 |
} |
| 143 |
|
| 144 |
# MIME type from command line `powershell` or `file` |
| 145 |
.mime_cmd = function(x, use_file = !is_windows() || Sys.which('file') != '') { |
| 146 |
if (!file.exists(x <- path.expand(x))) stop("The file '", x, "' does not exist.") |
| 147 |
if (use_file) { |
| 148 |
cmd = 'file' |
| 149 |
arg = c('--mime-type', '-b') |
| 150 |
} else { |
| 151 |
# IT said "thou shall not include .ps1 in source package", so I use .txt; |
| 152 |
# then Windoz said "thou shall not execute .txt", so I copy .txt to .ps1; |
| 153 |
# How much of our life has been wasted on making these idiots happy... |
| 154 |
ps1 = tempfile(fileext = '.ps1'); on.exit(unlink(ps1), add = TRUE) |
| 155 |
file.copy(pkg_file('scripts', 'mime-type.txt'), ps1) |
| 156 |
cmd = 'powershell' |
| 157 |
arg = c('-ExecutionPolicy', 'Bypass', '-File', shQuote(ps1)) |
| 158 |
} |
| 159 |
if (Sys.which(cmd) == '') stop("The '", cmd, "' command is not found") |
| 160 |
system2(cmd, c(arg, shQuote(x)), stdout = TRUE)[1] |
| 161 |
} |
| 162 |
|
| 163 |
# a comprehensive version is mime::mimemap |
| 164 |
mimemap = c( |
| 165 |
css = 'text/css', csv = 'text/csv', gif = 'image/gif', jpeg = 'image/jpeg', |
| 166 |
jpg = 'image/jpeg', js = 'text/javascript', png = 'image/png', |
| 167 |
r = 'text/plain', rmd = 'text/x-markdown', svg = 'image/svg+xml', |
| 168 |
ttf = 'font/ttf', woff = 'font/woff', woff2 = 'font/woff2' |
| 169 |
) |