From 8e7ef1d1bef4b39e7589b2390c64cd68b13670da Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Fri, 17 Nov 2017 17:30:01 +1000 Subject: [PATCH] detect image extension, catch errors, add timeout --- anki/media.py | 14 +++++++++++++- aqt/editor.py | 9 +++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/anki/media.py b/anki/media.py index 8abe608a3..d0c46f1b1 100644 --- a/anki/media.py +++ b/anki/media.py @@ -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) diff --git a/aqt/editor.py b/aqt/editor.py index d68905e33..fb0379bcf 100644 --- a/aqt/editor.py +++ b/aqt/editor.py @@ -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 ######################################################################