diff --git a/docs/downloading-files.md b/docs/downloading-files.md index 6f76f4a3..3c2fc155 100644 --- a/docs/downloading-files.md +++ b/docs/downloading-files.md @@ -1,7 +1,8 @@ # File Downloading WeTTY supports file downloads by printing terminal escape sequences between a -base64 encoded file. +base64 encoded file. The name of the downloaded file can optionally be provided, +also base64 encoded, before the encoded file contents with a `:` separating them. The terminal escape sequences used are `^[[5i` and `^[[4i` (VT100 for "enter auto print" and "exit auto print" respectively - @@ -13,8 +14,14 @@ To take advantage add the following bash function to your `.bashrc` function wetty-download() { file=${1:-/dev/stdin} - if [[ -f $file || $file == "/dev/stdin" ]]; then - printf "\033[5i"$(cat $file | base64 -w 0)"\033[4i" + nameprefix="" + if [[ -f "$file" ]]; then + nameprefix="$(basename "$file" | base64 -w 0):" + fi + + + if [[ -f "$file" || "$file" == "/dev/stdin" ]]; then + printf "\033[5i"$nameprefix$(cat "$file" | base64 -w 0)"\033[4i" else echo "$file does not appear to be a file" fi @@ -27,7 +34,7 @@ You are then able to download files via WeTTY! wetty-download my-pdf-file.pdf ``` -or you can still use the classic style: +or you can still use the classic style: ```bash $ cat my-pdf-file.pdf | wetty-download diff --git a/src/client/wetty/download.ts b/src/client/wetty/download.ts index 90cb09d9..8ee96e04 100644 --- a/src/client/wetty/download.ts +++ b/src/client/wetty/download.ts @@ -7,7 +7,11 @@ const DEFAULT_FILE_END = '\u001b[4i'; type OnCompleteFile = (bufferCharacters: string) => void; function onCompleteFile(bufferCharacters: string): void { + let fileNameBase64; let fileCharacters = bufferCharacters; + if (bufferCharacters.includes(":")) { + [fileNameBase64, fileCharacters] = bufferCharacters.split(":"); + } // Try to decode it as base64, if it fails we assume it's not base64 try { fileCharacters = window.atob(fileCharacters); @@ -34,12 +38,23 @@ function onCompleteFile(bufferCharacters: string): void { mimeType = 'text/plain'; fileExt = 'txt'; } - const fileName = `file-${new Date() - .toISOString() - .split('.')[0] - .replace(/-/g, '') - .replace('T', '') - .replace(/:/g, '')}${fileExt ? `.${fileExt}` : ''}`; + let fileName; + try { + if (fileNameBase64 !== undefined) { + fileName = window.atob(fileNameBase64); + } + } catch (err) { + // Filename wasn't base64-encoded so let's ignore it + } + + if (fileName === undefined) { + fileName = `file-${new Date() + .toISOString() + .split('.')[0] + .replace(/-/g, '') + .replace('T', '') + .replace(/:/g, '')}${fileExt ? `.${fileExt}` : ''}`; + } const blob = new Blob([new Uint8Array(bytes.buffer)], { type: mimeType,