OK Inspired by Joseph Wright's idea of using lua for this i threw together an attempt at this in pure lua.
\newcommand{\grabto}[2]{#2\ifluatex%
\directlua 0 {
local uri = "\luatexluaescapestring{#1}"
local fname = "\luatexluaescapestring{#2}"
local job = "\luatexluaescapestring{\jobname}"
local file = io.open(fname, 'r')
if file \string~= nil then
io.close(file)
else
% This detection isn't foolproof because this will happily write to a 0200
% file for example but latex can't read it and confusingly won't barf, but
% this case is pathologic and depending on posix is somewhat unpreferable
file = io.open(fname, 'w')
if file == nil then
print("(" .. job .. " file " .. fname .. " does exist already but cannot be read)")
else
require("ltn12")
local outputsink = ltn12.sink.file(file)
require("socket.url")
local parsed = socket.url.parse(uri, {scheme = 'file'})
if parsed.scheme == 'http' then
require("socket.http")
socket.http.request { url = uri, sink = outputsink, }
elseif parsed.scheme == 'ftp' then
require("socket.ftp")
socket.ftp.get { url = uri, sink = outputsink, }
else
% file scheme doesn't make sense because this branch indicates we
% at least couldn't read the file.
tex.error("Don't know how to download this sorry")
% This situation is a little annoying because we may have
% accidentally created a file and can't delete it in case our heuristics
% failed
end
end
end}%
\else%
% fallback
\fi}
This is the first lua I ever touched, so improvements are greatly appreciated. I believe it works for all cases i could come up with.
As mentioned in the comment, I tried to come up with a resonable fallback if luatex isn't the compiler, but it get's nasty quick.
I also changed the interface, so it returns #2, because then I can write
\includegraphics{\luagrabto{https://i.stack.imgur.com/Bil0Q.png}{test.png}}
That works fine for the lua part and for the rudimentary fallback, but \includegraphic really is fussy in some parts and absolutely disliked me playing around with \hyper@normalize to make sure this doesn't blow up for weird urls.
wgetting and saving the file in the first place—why should TeX do that for you? – You Dec 28 '12 at 21:00downloadpackage. – You Dec 31 '12 at 22:19