|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | from datetime import date, datetime, timezone |
| 4 | +from pathlib import Path |
4 | 5 | from typing import TYPE_CHECKING, Any, Callable, Dict |
5 | 6 |
|
6 | 7 | from .bookmark import serializer_unserializable |
| 8 | +from .bookmark._serializers import can_serialize_input_file, serializer_file_input |
7 | 9 |
|
8 | 10 | if TYPE_CHECKING: |
9 | 11 | from .session import Session |
@@ -173,33 +175,79 @@ def _(value: Any, name: ResolvedId, session: Session) -> Any: |
173 | 175 | if value is None: |
174 | 176 | return None |
175 | 177 |
|
176 | | - # TODO: Barret: Input handler for file inputs |
| 178 | + if not can_serialize_input_file(session): |
| 179 | + raise ValueError( |
| 180 | + "`shiny.ui.input_file()` is attempting to restore bookmark state. " |
| 181 | + 'However the App\'s `bookmark_store=` is not set to `"server"`. ' |
| 182 | + "Either exclude the input value (`session.bookmark.exclude.append(NAME)`) " |
| 183 | + 'or set `bookmark_store="server"`.' |
| 184 | + ) |
177 | 185 |
|
178 | | - # # The data will be a named list of lists; convert to a data frame. |
179 | | - # val <- as.data.frame(lapply(val, unlist), stringsAsFactors = FALSE) |
| 186 | + value_obj = value |
| 187 | + |
| 188 | + # Convert from: |
| 189 | + # `{name: (n1, n2, n3), size: (s1, s2, s3), type: (t1, t2, t3), datapath: (d1, d2, d3)}` |
| 190 | + # to: |
| 191 | + # `[{name: n1, size: s1, type: t1, datapath: d1}, ...]` |
| 192 | + value_list: list[dict[str, str | int | None]] = [] |
| 193 | + for i in range(len(value_obj["name"])): |
| 194 | + value_list.append( |
| 195 | + { |
| 196 | + "name": value_obj["name"][i], |
| 197 | + "size": value_obj["size"][i], |
| 198 | + "type": value_obj["type"][i], |
| 199 | + "datapath": value_obj["datapath"][i], |
| 200 | + } |
| 201 | + ) |
180 | 202 |
|
181 | | - # # `val$datapath` should be a filename without a path, for security reasons. |
182 | | - # if (basename(val$datapath) != val$datapath) { |
183 | | - # stop("Invalid '/' found in file input path.") |
184 | | - # } |
| 203 | + # Validate the input value |
| 204 | + for value_item in value_list: |
| 205 | + if value_item["datapath"] is not None: |
| 206 | + if not isinstance(value_item["datapath"], str): |
| 207 | + raise ValueError( |
| 208 | + "Invalid type for file input path: ", type(value_item["datapath"]) |
| 209 | + ) |
| 210 | + if Path(value_item["datapath"]).name != value_item["datapath"]: |
| 211 | + raise ValueError("Invalid '/' found in file input path.") |
185 | 212 |
|
186 | | - # # Prepend the persistent dir |
187 | | - # oldfile <- file.path(getCurrentRestoreContext()$dir, val$datapath) |
| 213 | + import shutil |
| 214 | + import tempfile |
188 | 215 |
|
189 | | - # # Copy the original file to a new temp dir, so that a restored session can't |
190 | | - # # modify the original. |
191 | | - # newdir <- file.path(tempdir(), createUniqueId(12)) |
192 | | - # dir.create(newdir) |
193 | | - # val$datapath <- file.path(newdir, val$datapath) |
194 | | - # file.copy(oldfile, val$datapath) |
| 216 | + from shiny._utils import rand_hex |
195 | 217 |
|
196 | | - # # Need to mark this input value with the correct serializer. When a file is |
197 | | - # # uploaded the usual way (instead of being restored), this occurs in |
198 | | - # # session$`@uploadEnd`. |
199 | | - # setSerializer(name, serializerFileInput) |
| 218 | + from .bookmark._restore_state import get_current_restore_context |
| 219 | + from .session import session_context |
200 | 220 |
|
201 | | - # snapshotPreprocessInput(name, snapshotPreprocessorFileInput) |
| 221 | + with session_context(session): |
| 222 | + restore_ctx = get_current_restore_context() |
202 | 223 |
|
203 | | - # val |
| 224 | + # These should not fail as we know |
| 225 | + if restore_ctx is None or restore_ctx.dir is None: |
| 226 | + raise RuntimeError("No restore context found. Cannot restore file input.") |
204 | 227 |
|
205 | | - return value |
| 228 | + restore_ctx_dir = Path(restore_ctx.dir) |
| 229 | + |
| 230 | + for f in value_list: |
| 231 | + assert f["datapath"] is not None and isinstance(f["datapath"], str) |
| 232 | + |
| 233 | + data_path = f["datapath"] |
| 234 | + |
| 235 | + # Prepend the persistent dir |
| 236 | + old_file = restore_ctx_dir / data_path |
| 237 | + |
| 238 | + # Copy the original file to a new temp dir, so that a restored session can't |
| 239 | + # modify the original. |
| 240 | + tempdir_root = tempfile.TemporaryDirectory() |
| 241 | + session.on_ended(lambda: tempdir_root.cleanup()) |
| 242 | + |
| 243 | + tempdir = Path(tempdir_root.name) / rand_hex(12) |
| 244 | + tempdir.mkdir(parents=True, exist_ok=True) |
| 245 | + f["datapath"] = str(tempdir / Path(data_path).name) |
| 246 | + shutil.copy2(old_file, f["datapath"]) |
| 247 | + |
| 248 | + # Need to mark this input value with the correct serializer. When a file is |
| 249 | + # uploaded the usual way (instead of being restored), this occurs in |
| 250 | + # session$`@uploadEnd`. |
| 251 | + session.input.set_serializer(name, serializer_file_input) |
| 252 | + |
| 253 | + return value_list |
0 commit comments