Debian Codegraph @

mediafile/utils/mutagen_wrapper.py

raw
1 import functools
2 import logging
3 import traceback
4
5 import mutagen
6 import mutagen._util
7
8 from mediafile.exceptions import MutagenError, UnreadableFileError
9
10 log = logging.getLogger(__name__)
11
12
13 def mutagen_call(action, filename, func, *args, **kwargs):
14 """Call a Mutagen function with appropriate error handling.
15
16 `action` is a string describing what the function is trying to do,
17 and `filename` is the relevant filename. The rest of the arguments
18 describe the callable to invoke.
19
20 We require at least Mutagen 1.33, where `IOError` is *never* used,
21 neither for internal parsing errors *nor* for ordinary IO error
22 conditions such as a bad filename. Mutagen-specific parsing errors and IO
23 errors are reraised as `UnreadableFileError`. Other exceptions
24 raised inside Mutagen---i.e., bugs---are reraised as `MutagenError`.
25 """
26 try:
27 return func(*args, **kwargs)
28 except mutagen._util.MutagenError as exc:
29 log.debug("%s failed: %s", action, str(exc))
30 raise UnreadableFileError(filename, str(exc))
31 except UnreadableFileError:
32 # Reraise our errors without changes.
33 # Used in case of decorating functions (e.g. by `loadfile`).
34 raise
35 except Exception as exc:
36 # Isolate bugs in Mutagen.
37 log.debug("%s", traceback.format_exc())
38 log.error("uncaught Mutagen exception in %s: %s", action, exc)
39 raise MutagenError(filename, exc)
40
41
42 def loadfile(method=True, writable=False, create=False):
43 """A decorator that works like `mutagen._util.loadfile` but with
44 additional error handling.
45
46 Opens a file and passes a `mutagen._utils.FileThing` to the
47 decorated function. Should be used as a decorator for functions
48 using a `filething` parameter.
49 """
50
51 def decorator(func):
52 f = mutagen._util.loadfile(method, writable, create)(func)
53
54 @functools.wraps(func)
55 def wrapper(*args, **kwargs):
56 return mutagen_call("loadfile", "", f, *args, **kwargs)
57
58 return wrapper
59
60 return decorator
61
62
63 def update_filething(filething):
64 """Reopen a `filething` if it's a local file.
65
66 A filething that is *not* an actual file is left unchanged; a
67 filething with a filename is reopened and a new object is returned.
68 """
69 if filething.filename:
70 return mutagen._util.FileThing(None, filething.filename, filething.name)
71 else:
72 return filething