detect image extension, catch errors, add timeout

This commit is contained in:
Damien Elmes 2017-11-17 17:30:01 +10:00
parent 56444ab967
commit 8e7ef1d1be
2 changed files with 20 additions and 3 deletions

View file

@ -128,9 +128,21 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0);
def addFile(self, opath):
return self.writeData(opath, open(opath, "rb").read())
def writeData(self, opath, data):
def writeData(self, opath, data, typeHint=None):
# if fname is a full path, use only the basename
fname = os.path.basename(opath)
# if it's missing an extension and a type hint was provided, use that
if not os.path.splitext(fname)[1] and typeHint:
# mimetypes is returning '.jpe' even after calling .init(), so we'll do
# it manually instead
typeMap = {
"image/jpeg": ".jpg",
"image/png": ".png",
}
if typeHint in typeMap:
fname += typeMap[typeHint]
# make sure we write it in NFC form (on mac will autoconvert to NFD),
# and return an NFC-encoded reference
fname = unicodedata.normalize("NFC", fname)

View file

@ -591,26 +591,31 @@ to a cloze type first, via Edit>Change Note Type."""))
# fetch it into a temporary folder
self.mw.progress.start(
immediate=True, parent=self.parentWindow)
ct = None
try:
if local:
req = urllib.request.Request(url, None, {
'User-Agent': 'Mozilla/5.0 (compatible; Anki)'})
filecontents = urllib.request.urlopen(req).read()
else:
r = requests.get(url)
r = requests.get(url, timeout=30)
if r.status_code != 200:
showWarning(_("Unexpected response code: %s") % r.status_code)
return
filecontents = r.content
ct = r.headers.get("content-type")
except urllib.error.URLError as e:
showWarning(_("An error occurred while opening %s") % e)
return
except requests.exceptions.RequestException as e:
showWarning(_("An error occurred while opening %s") % e)
return
finally:
self.mw.progress.finish()
# strip off any query string
url = re.sub("\?.*?$", "", url)
path = urllib.parse.unquote(url)
return self.mw.col.media.writeData(path, filecontents)
return self.mw.col.media.writeData(path, filecontents, typeHint=ct)
# Paste/drag&drop
######################################################################