-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Loading status checks…
✨ Add support for downloading
data:
uris with Alchemy#download()
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
let mkdirp = alchemy.use('mkdirp')?.mkdirp, | ||
ncp = alchemy.use('ncp').ncp, | ||
fs = alchemy.use('fs'), | ||
fsp = fs.promises, | ||
libpath = alchemy.use('path'), | ||
child = alchemy.use('child_process'), | ||
crypto = alchemy.use('crypto'), | ||
|
@@ -1106,6 +1107,53 @@ Alchemy.setMethod(function request(url, options, callback) { | |
return Blast.fetch(options, callback); | ||
}); | ||
|
||
/** | ||
* Turn a `data:` uri into a file | ||
* | ||
* @author Jelle De Loecker <[email protected]> | ||
* @since 1.4.0 | ||
* @version 1.4.0 | ||
* | ||
* @param {string} data_uri | ||
* | ||
* @return {Pledge<File>} | ||
*/ | ||
function convertDataUriToFile(data_uri) { | ||
|
||
// Split the data uri into its 2 parts | ||
let pieces = data_uri.slice(5).split(','); | ||
|
||
// Split the info bit | ||
let info = pieces[0].split(';'); | ||
|
||
// Get the expected mime type | ||
let mime_type = info[0]; | ||
|
||
// And is it base64? | ||
let is_b64 = info[1] && info[1].toLowerCase() == 'base64'; | ||
|
||
let buffer; | ||
|
||
if (is_b64) { | ||
buffer = Buffer.from(pieces[1], 'base64'); | ||
} else { | ||
buffer = Buffer.from(String.decodeURI(pieces[1])); | ||
} | ||
|
||
return Pledge.Swift.waterfall( | ||
() => Blast.createTempDir({prefix: 'aldl'}), | ||
async (temp_dir) => { | ||
let full_path = libpath.resolve(temp_dir, 'buffer_' + alchemy.ObjectId()); | ||
|
||
await fsp.writeFile(full_path, buffer); | ||
|
||
return full_path; | ||
}, | ||
(full_path) => Classes.Alchemy.Inode.Inode.from(full_path) | ||
); | ||
|
||
} | ||
|
||
/** | ||
* Download a file | ||
* | ||
|
@@ -1119,6 +1167,14 @@ Alchemy.setMethod(function request(url, options, callback) { | |
*/ | ||
Alchemy.setMethod(function download(url, options) { | ||
|
||
if (url.startsWith('data:')) { | ||
try { | ||
return convertDataUriToFile(url, options); | ||
} catch (err) { | ||
return Pledge.reject(err); | ||
} | ||
} | ||
|
||
const pledge = new Pledge(); | ||
|
||
// Get the file | ||
|