Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[http- unzip_http] handle errors in retrieving URLs #2655

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions visidata/loaders/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ def openZipFile(self, fp, *args, **kwargs):
pwd = vd.input(f'{args[0].filename} is encrypted, enter password: ', display=False)
return zip_open(*args, **kwargs, pwd=pwd.encode('utf-8'))
vd.exceptionCaught(err)
except urllib.error.HTTPError as err:
if err.status is None:
vd.fail(f'cannot open URL: {err.msg}')
else:
vd.fail(f'cannot open URL: HTTP Error {err.status}: {err.msg}')


def openRow(self, row):
fi, zpath = row
Expand Down
3 changes: 3 additions & 0 deletions visidata/loaders/http.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
import http.client

from visidata import Path, RepeatFile, vd, VisiData
from visidata.loaders.tsv import splitter
Expand Down Expand Up @@ -55,6 +56,8 @@ def openurl_http(vd, path, filetype=None):
vd.fail(f'cannot open URL: HTTP Error {e.code}: {e.reason}')
except urllib.error.URLError as e:
vd.fail(f'cannot open URL: {e.reason}')
except (http.client.HTTPException, ConnectionError) as e:
vd.fail(f'cannot open URL: {e}')

filetype = filetype or vd.guessFiletype(path, response, funcprefix='guessurl_').get('filetype') # try guessing by url
filetype = filetype or vd.guessFiletype(path, funcprefix='guess_').get('filetype') # try guessing by contents
Expand Down
24 changes: 22 additions & 2 deletions visidata/loaders/unzip_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import argparse
import pathlib
import urllib.parse
import urllib.error
from visidata import vd


Expand Down Expand Up @@ -149,7 +150,20 @@ def namelist(self):
return list(r.filename for r in self.infoiter())

def infoiter(self):
resp = self.http.request('HEAD', self.url)
urllib3 = vd.importExternal('urllib3')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file (unzip_http.py) should be taken directly from https://github.com/saulpw/unzip-http/blob/master/unzip_http.py, with the vd.importExternal line being manually substituted. It's not a clean process but I didn't/don't expect unzip_http to be updated that often. They've already drifted a bit, but if we could bring them into sync again and make these changes in a way that keeps them as close as possible, that's my preference. Probably the easiest way is to let these errors percolate up and then handle them at a visidata layer instead of in unzip_http.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One complication is, unzip-http uses urllib3, so the exceptions would be from urllib3 and can't be caught in loader/archive.py which does not import it.

I submitted a draft patch that transforms the urllib3 errors into regular urllib errors. What do you think of that? It makes sense in the context of visidata, but it's quite odd in the context of unzip-http by itself.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just catch Exception? Do we only want to catch urllib3 exceptions here?

try:
resp = self.http.request('HEAD', self.url)
except urllib3.exceptions.HTTPError as e:
code = None
msg = f'urllib3.error.{e.__name__}'
hdrs = fp = None
# transform to HTTPError in urllib, instead of urllib3, to avoid caller needing urllib3
raise urllib.error.HTTPError(self.url, code, msg, hdrs, fp)
if not (200 <= resp.status <= 299):
code = resp.status
msg = 'HEAD request status not in range 200-299'
hdrs = fp = None
raise urllib.error.HTTPError(self.url, code, msg, hdrs, fp)
r = resp.headers.get('Accept-Ranges', '')
if r != 'bytes':
hostname = urllib.parse.urlparse(self.url).netloc
Expand Down Expand Up @@ -231,7 +245,13 @@ def extractall(self, path=None, members=None, pwd=None):
self.extract(fn, path, pwd=pwd)

def get_range(self, start, n):
return self.http.request('GET', self.url, headers={'Range': f'bytes={start}-{start+n-1}'}, preload_content=False)
try:
return self.http.request('GET', self.url, headers={'Range': f'bytes={start}-{start+n-1}'}, preload_content=False)
except urllib3.exceptions.HTTPError as e:
code = None
msg = f'urllib3.error.{e.__name__}'
hdrs = fp = None
raise urllib.error.HTTPError(self.url, code, msg, hdrs, fp)

def matching_files(self, *globs):
for f in self.files.values():
Expand Down
Loading