# Buggy code
def parse(
    cls,
    filename,
    library_file=None,
    cover_data=False,
    encoding_errors="strict",
    parse_speed=0.5,
    text=False,
    full=True,
    legacy_stream_display=False,
):
    """
    Analyze a media file using libmediainfo.
    If libmediainfo is located in a non-standard location, the `library_file` parameter can be used:

    >>> pymediainfo.MediaInfo.parse("tests/data/sample.mkv",
    ...     library_file="/path/to/libmediainfo.dylib")

    :param filename: path to the media file which will be analyzed.
        A URL can also be used if libmediainfo was compiled
        with CURL support.
    :param str library_file: path to the libmediainfo library, this should only be used if the library cannot be auto-detected.
    :param bool cover_data: whether to retrieve cover data as base64.
    :param str encoding_errors: option to pass to :func:`str.encode`'s `errors`
        parameter before parsing MediaInfo's XML output.
    :param float parse_speed: passed to the library as `ParseSpeed`,
        this option takes values between 0 and 1.
        A higher value will yield more precise results in some cases
        but will also increase parsing time.
    :param bool text: if ``True``, MediaInfo's text output will be returned instead
        of a :class:`MediaInfo` object.
    :param bool full: display additional tags, including computer-readable values
        for sizes and durations.
    :param bool legacy_stream_display: display additional information about streams.
    :type filename: str or pathlib.Path
    :rtype: str if `text` is ``True``.
    :rtype: :class:`MediaInfo` otherwise.
    :raises FileNotFoundError: if passed a non-existent file
        (Python ≥ 3.3), does not work on Windows.
    :raises IOError: if passed a non-existent file (Python < 3.3),
        does not work on Windows.
    :raises RuntimeError: if parsing fails, this should not
        happen unless libmediainfo itself fails.
    """
    lib = cls._get_library(library_file)
    if pathlib is not None and isinstance(filename, pathlib.PurePath):
        filename = str(filename)
        url = False
    else:
        url = urlparse.urlparse(filename)
    # Try to open the file (if it's not a URL)
    # Doesn't work on Windows because paths are URLs
    if not (url and url.scheme):
        # Test whether the file is readable
        with open(filename, "rb"):
            pass
    # Obtain the library version
    lib_version = lib.MediaInfo_Option(None, "Info_Version", "")
    lib_version = tuple(
        int(_)
        for _ in re.search("^MediaInfoLib - v(\\S+)", lib_version).group(1).split(".")
    )
    # The XML option was renamed starting with version 17.10
    if lib_version >= (17, 10):
        xml_option = "OLDXML"
    else:
        xml_option = "XML"
    # Cover_Data is not extracted by default since version 18.03
    # See https://github.com/MediaArea/MediaInfoLib/commit/d8fd88a1c282d1c09388c55ee0b46029e7330690
    if cover_data and lib_version >= (18, 3):
        lib.MediaInfo_Option(None, "Cover_Data", "base64")
    # Create a MediaInfo handle
    handle = lib.MediaInfo_New()
    lib.MediaInfo_Option(handle, "CharSet", "UTF-8")
    # Fix for https://github.com/sbraz/pymediainfo/issues/22
    # Python 2 does not change LC_CTYPE
    # at startup: https://bugs.python.org/issue6203
    if (
        sys.version_info < (3,)
        and os.name == "posix"
        and locale.getlocale() == (None, None)
    ):
        locale.setlocale(locale.LC_CTYPE, locale.getdefaultlocale())
    lib.MediaInfo_Option(None, "Inform", "" if text else xml_option)
    lib.MediaInfo_Option(None, "Complete", "1" if full else "")
    lib.MediaInfo_Option(None, "ParseSpeed", str(parse_speed))
    lib.MediaInfo_Option(
        None, "LegacyStreamDisplay", "1" if legacy_stream_display else ""
    )
    if lib.MediaInfo_Open(handle, filename) == 0:
        raise RuntimeError(
            "An eror occured while opening {} with libmediainfo".format(filename)
        )
    output = lib.MediaInfo_Inform(handle, 0)
    # Delete the handle
    lib.MediaInfo_Close(handle)
    lib.MediaInfo_Delete(handle)
    if text:
        return output
    else:
        return cls(output, encoding_errors)


# Traceback (UnicodeDecodeError)
2019-06-07 16:18:01 ERROR    Thread_31 :: [6a21a60] Exception generated: 'utf-8' codec can't decode byte 0x94 in position 0: invalid start byte
Traceback (most recent call last):
File "/Users/ovidijus/Apps/Medusa/medusa/server/web/core/base.py", line 261, in async_call
result = function(**kwargs)
File "/Users/ovidijus/Apps/Medusa/medusa/server/web/core/error_logs.py", line 62, in submit_errors
results = self.issue_submitter.submit_github_issue(CheckVersion())
File "/Users/ovidijus/Apps/Medusa/medusa/issue_submitter.py", line 199, in submit_github_issue
return self.submit_issues(github, github_repo, loglines, similar_issues)
File "/Users/ovidijus/Apps/Medusa/medusa/issue_submitter.py", line 216, in submit_issues
gist = cls.create_gist(github, line)
File "/Users/ovidijus/Apps/Medusa/medusa/issue_submitter.py", line 75, in create_gist
context_loglines = logline.get_context_loglines()
File "/Users/ovidijus/Apps/Medusa/medusa/logger/__init__.py", line 448, in get_context_loglines
for logline in read_loglines(modification_time=start_timestamp):
File "/Users/ovidijus/Apps/Medusa/medusa/logger/__init__.py", line 166, in read_loglines
for line in reverse_readlines(f):
File "/Users/ovidijus/Apps/Medusa/medusa/logger/__init__.py", line 281, in reverse_readlines
for block in block_generator(filename, **block_generator_kws):
File "/Users/ovidijus/Apps/Medusa/medusa/logger/__init__.py", line 243, in blocks_r
block = file_obj.read(min(remaining_size, size))
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 0: invalid start byte
2019-06-07 08:05:17 ERROR    SHOWQUEUE-REFRESH :: [6a21a60] 305075: Error while refreshing show Bungo Stray Dogs. Error: 'MediaInfo' object has no attribute 'xml_dom'
Traceback (most recent call last):
File "/Users/ovidijus/Apps/Medusa/ext/knowit/api.py", line 64, in know
result = provider.describe(video_path, context)
File "/Users/ovidijus/Apps/Medusa/ext/knowit/providers/mediainfo.py", line 296, in describe
video_path, self.executor.location, debug_data())
File "/Users/ovidijus/Apps/Medusa/ext/knowit/providers/mediainfo.py", line 289, in debug_data
xml = ensure_text(ElementTree.tostring(media_info.xml_dom)).replace('\r', '').replace('\n', '')
AttributeError: 'MediaInfo' object has no attribute 'xml_dom'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/ovidijus/Apps/Medusa/medusa/show_queue.py", line 688, in run
self.show.refresh_dir()
File "/Users/ovidijus/Apps/Medusa/medusa/tv/series.py", line 1792, in refresh_dir
self.load_episodes_from_dir()
File "/Users/ovidijus/Apps/Medusa/medusa/tv/series.py", line 1053, in load_episodes_from_dir
cur_episode = self.make_ep_from_file(os.path.join(self.location, media_file))
File "/Users/ovidijus/Apps/Medusa/medusa/tv/series.py", line 1397, in make_ep_from_file
cur_ep.update_status_quality(filepath)
File "/Users/ovidijus/Apps/Medusa/medusa/tv/episode.py", line 2040, in update_status_quality
new_quality = Quality.name_quality(filepath, self.series.is_anime)
File "/Users/ovidijus/Apps/Medusa/medusa/common.py", line 284, in name_quality
return Quality._extend_quality(name)
File "/Users/ovidijus/Apps/Medusa/medusa/common.py", line 383, in _extend_quality
quality = Quality.quality_from_file_meta(file_path)
File "/Users/ovidijus/Apps/Medusa/medusa/common.py", line 405, in quality_from_file_meta
knowledge = knowit.know(file_path)
File "/Users/ovidijus/Apps/Medusa/ext/knowit/api.py", line 70, in know
raise KnowitException(debug_info(context=context, exc_info=True))
File "/Users/ovidijus/Apps/Medusa/ext/knowit/api.py", line 121, in debug_info
lines.append(debug_data())
File "/Users/ovidijus/Apps/Medusa/ext/knowit/providers/mediainfo.py", line 289, in debug_data
xml = ensure_text(ElementTree.tostring(media_info.xml_dom)).replace('\r', '').replace('\n', '')
AttributeError: 'MediaInfo' object has no attribute 'xml_dom'

# Fixed code
def parse(
    cls,
    filename,
    library_file=None,
    cover_data=False,
    encoding_errors="strict",
    parse_speed=0.5,
):
    """
    Analyze a media file using libmediainfo.
    If libmediainfo is located in a non-standard location, the `library_file` parameter can be used:

    >>> pymediainfo.MediaInfo.parse("tests/data/sample.mkv",
    ...     library_file="/path/to/libmediainfo.dylib")

    :param filename: path to the media file which will be analyzed.
        A URL can also be used if libmediainfo was compiled
        with CURL support.
    :param str library_file: path to the libmediainfo library, this should only be used if the library cannot be auto-detected.
    :param bool cover_data: whether to retrieve cover data as base64.
    :param str encoding_errors: option to pass to :func:`str.encode`'s `errors`
        parameter before parsing MediaInfo's XML output.
    :param float parse_speed: passed to the library as `ParseSpeed`,
        this option takes values between 0 and 1.
        A higher value will yield more precise results in some cases
        but will also increase parsing time.
    :type filename: str or pathlib.Path
    :rtype: MediaInfo
    :raises FileNotFoundError: if passed a non-existent file
        (Python ≥ 3.3), does not work on Windows.
    :raises IOError: if passed a non-existent file (Python < 3.3),
        does not work on Windows.
    :raises RuntimeError: if parsing fails, this should not
        happen unless libmediainfo itself fails.
    """
    lib = cls._get_library(library_file)
    if pathlib is not None and isinstance(filename, pathlib.PurePath):
        filename = str(filename)
        url = False
    else:
        url = urlparse.urlparse(filename)
    # Try to open the file (if it's not a URL)
    # Doesn't work on Windows because paths are URLs
    if not (url and url.scheme):
        # Test whether the file is readable
        with open(filename, "rb"):
            pass
    # Define arguments and return types
    lib.MediaInfo_Inform.restype = c_wchar_p
    lib.MediaInfo_New.argtypes = []
    lib.MediaInfo_New.restype = c_void_p
    lib.MediaInfo_Option.argtypes = [c_void_p, c_wchar_p, c_wchar_p]
    lib.MediaInfo_Option.restype = c_wchar_p
    lib.MediaInfo_Inform.argtypes = [c_void_p, c_size_t]
    lib.MediaInfo_Inform.restype = c_wchar_p
    lib.MediaInfo_Open.argtypes = [c_void_p, c_wchar_p]
    lib.MediaInfo_Open.restype = c_size_t
    lib.MediaInfo_Delete.argtypes = [c_void_p]
    lib.MediaInfo_Delete.restype = None
    lib.MediaInfo_Close.argtypes = [c_void_p]
    lib.MediaInfo_Close.restype = None
    # Obtain the library version
    lib_version = lib.MediaInfo_Option(None, "Info_Version", "")
    lib_version = tuple(
        int(_)
        for _ in re.search("^MediaInfoLib - v(\\S+)", lib_version).group(1).split(".")
    )
    # The XML option was renamed starting with version 17.10
    if lib_version >= (17, 10):
        xml_option = "OLDXML"
    else:
        xml_option = "XML"
    # Cover_Data is not extracted by default since version 18.03
    # See https://github.com/MediaArea/MediaInfoLib/commit/d8fd88a1c282d1c09388c55ee0b46029e7330690
    if cover_data and lib_version >= (18, 3):
        lib.MediaInfo_Option(None, "Cover_Data", "base64")
    # Create a MediaInfo handle
    handle = lib.MediaInfo_New()
    lib.MediaInfo_Option(handle, "CharSet", "UTF-8")
    # Fix for https://github.com/sbraz/pymediainfo/issues/22
    # Python 2 does not change LC_CTYPE
    # at startup: https://bugs.python.org/issue6203
    if (
        sys.version_info < (3,)
        and os.name == "posix"
        and locale.getlocale() == (None, None)
    ):
        locale.setlocale(locale.LC_CTYPE, locale.getdefaultlocale())
    lib.MediaInfo_Option(None, "Inform", xml_option)
    lib.MediaInfo_Option(None, "Complete", "1")
    lib.MediaInfo_Option(None, "ParseSpeed", str(parse_speed))
    if lib.MediaInfo_Open(handle, filename) == 0:
        raise RuntimeError(
            "An eror occured while opening {0} with libmediainfo".format(filename)
        )
    xml = lib.MediaInfo_Inform(handle, 0)
    # Delete the handle
    lib.MediaInfo_Close(handle)
    lib.MediaInfo_Delete(handle)
    return cls(xml, encoding_errors)