# Buggy code
def sendNZB(nzb, proper=False):
    """
    Sends NZB to NZBGet client

    :param nzb: nzb object
    :param proper: True if a Proper download, False if not.
    """
    if app.NZBGET_HOST is None:
        log.warning("No NZBget host found in configuration. Please configure it.")
        return False

    addToTop = False
    nzbgetprio = 0
    category = app.NZBGET_CATEGORY
    if nzb.series.is_anime:
        category = app.NZBGET_CATEGORY_ANIME

    url = "http{}://{}:{}@{}/xmlrpc".format(
        "s" if app.NZBGET_USE_HTTPS else "",
        app.NZBGET_USERNAME,
        app.NZBGET_PASSWORD,
        app.NZBGET_HOST,
    )

    if not NZBConnection(url):
        return False

    nzbGetRPC = ServerProxy(url)

    dupekey = ""
    dupescore = 0
    # if it aired recently make it high priority and generate DupeKey/Score
    for cur_ep in nzb.episodes:
        if dupekey == "":
            if cur_ep.series.indexer == 1:
                dupekey = "Medusa-" + text_type(cur_ep.series.indexerid)
            elif cur_ep.series.indexer == 2:
                dupekey = "Medusa-tvr" + text_type(cur_ep.series.indexerid)
        dupekey += "-" + text_type(cur_ep.season) + "." + text_type(cur_ep.episode)
        if datetime.date.today() - cur_ep.airdate <= datetime.timedelta(days=7):
            addToTop = True
            nzbgetprio = app.NZBGET_PRIORITY
        else:
            category = app.NZBGET_CATEGORY_BACKLOG
            if nzb.series.is_anime:
                category = app.NZBGET_CATEGORY_ANIME_BACKLOG

    if nzb.quality != Quality.UNKNOWN:
        dupescore = nzb.quality * 100
    if proper:
        dupescore += 10

    nzbcontent64 = None
    if nzb.result_type == "nzbdata":
        data = nzb.extra_info[0]
        nzbcontent64 = standard_b64encode(data)

    log.info("Sending NZB to NZBget")
    log.debug("URL: {}", url)

    try:
        # Find out if nzbget supports priority (Version 9.0+),
        # old versions beginning with a 0.x will use the old command
        nzbget_version_str = nzbGetRPC.version()
        nzbget_version = try_int(nzbget_version_str[: nzbget_version_str.find(".")])
        if nzbget_version == 0:
            if nzbcontent64:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, addToTop, nzbcontent64
                )
            else:
                if nzb.result_type == "nzb":
                    if not nzb.provider.login():
                        return False

                    # TODO: Check if this needs exception handling
                    data = nzb.provider.session(nzb.url).content
                    if data is None:
                        return False

                    nzbcontent64 = standard_b64encode(data)

                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, addToTop, nzbcontent64
                )
        elif nzbget_version == 12:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb",
                    category,
                    nzbgetprio,
                    False,
                    nzbcontent64,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
            else:
                nzbget_result = nzbGetRPC.appendurl(
                    nzb.name + ".nzb",
                    category,
                    nzbgetprio,
                    False,
                    nzb.url,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
        # v13+ has a new combined append method that accepts both (url and
        # content) also the return value has changed from boolean to integer
        # (Positive number representing NZBID of the queue item. 0 and negative
        # numbers represent error codes.)
        elif nzbget_version >= 13:
            nzbget_result = (
                nzbGetRPC.append(
                    nzb.name + ".nzb",
                    nzbcontent64 if nzbcontent64 is not None else nzb.url,
                    category,
                    nzbgetprio,
                    False,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
                > 0
            )
        else:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, nzbgetprio, False, nzbcontent64
                )
            else:
                nzbget_result = nzbGetRPC.appendurl(
                    nzb.name + ".nzb", category, nzbgetprio, False, nzb.url
                )

        if nzbget_result:
            log.debug("NZB sent to NZBget successfully")
            return True
        else:
            log.warning(
                "NZBget could not add {name}.nzb to the queue", {"name": nzb.name}
            )
            return False
    except Exception:
        log.warning(
            "Connect Error to NZBget: could not add {file}.nzb to the queue",
            {"name": nzb.name},
        )
        return False


# Traceback (KeyError)
2019-02-03 04:03:40 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Transaction with 1 queries executed
2019-02-03 04:03:43 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Beginning to snatch release: American.Dad.S13E15.720p.HDTV.x264-AVS
2019-02-03 04:03:43 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Downloading American.Dad.S13E15.720p.HDTV.x264-AVS with size: 305.24 MB from Hydra, through a SearchType.DAILY_SEARCH search
2019-02-03 04:03:43 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Successfully connected to NZBget
2019-02-03 04:03:43 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Sending NZB to NZBget
2019-02-03 04:03:43 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] URL: https://**********:**********@nzbget.devue.nl/xmlrpc
2019-02-03 04:03:44 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] NZB sent to NZBget successfully
2019-02-03 04:03:46 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Checking if we should stop searching for a better quality for for episode American.Dad.S13E15.720p.HDTV.x264-AVS
2019-02-03 04:03:46 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Matched release /tv/American Dad!/Season 14/American Dad! - S14E15 - The Life and Times of Stan Smith AVS to a series in your database: American Dad!
2019-02-03 04:03:46 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Parsed /tv/American Dad!/Season 14/American Dad! - S14E15 - The Life and Times of Stan Smith AVS into title: American Dad!, season: 14, episode: [15], episode_title: The Life and Times of Stan Smith AVS, type: episode, parsing_time: 0.0329928398132, total_time: 0.0331439971924, absolute_episode: [], quality: Unknown
2019-02-03 04:03:46 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Found codec for American Dad! The Life and Times of Stan Smith
2019-02-03 04:03:46 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] 73141: Formatting pattern: %SN - %Sx15 - %EN - %QN -> American Dad! - 14x15 - The Life and Times of Stan Smith - 720p HDTV
2019-02-03 04:03:47 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Transaction with 1 queries executed
2019-02-03 04:03:49 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Beginning to snatch release: American.Dad.S13E16.720p.HDTV.x264-AVS
2019-02-03 04:03:49 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Downloading American.Dad.S13E16.720p.HDTV.x264-AVS with size: 392.67 MB from Hydra, through a SearchType.DAILY_SEARCH search
2019-02-03 04:03:49 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Successfully connected to NZBget
2019-02-03 04:03:49 INFO     SNATCHQUEUE-SNATCH-73141 :: [918cfe7] Sending NZB to NZBget
2019-02-03 04:03:49 DEBUG    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] URL: https://**********:**********@nzbget.devue.nl/xmlrpc
2019-02-03 04:04:19 ERROR    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] BraceMessage string formatting failed. Using representation instead.
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 53, in __str__
    return self.msg.format(*args)
KeyError: u'file'
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 60, in __str__
    raise BraceException(self.msg)
BraceException: Connect Error to NZBget: could not add {file}.nzb to the queue
2019-02-03 04:04:19 ERROR    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] BraceMessage string formatting failed. Using representation instead.
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 53, in __str__
    return self.msg.format(*args)
KeyError: u'file'
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 60, in __str__
    raise BraceException(self.msg)
BraceException: Connect Error to NZBget: could not add {file}.nzb to the queue
2019-02-03 04:04:19 ERROR    SNATCHQUEUE-SNATCH-73141 :: [918cfe7] BraceMessage string formatting failed. Using representation instead.
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 53, in __str__
    return self.msg.format(*args)
KeyError: u'file'
Traceback (most recent call last):
  File "/app/medusa/medusa/logger/adapters/style.py", line 60, in __str__
    raise BraceException(self.msg)
BraceException: Connect Error to NZBget: could not add {file}.nzb to the queue

# Fixed code
def sendNZB(nzb, proper=False):
    """
    Sends NZB to NZBGet client

    :param nzb: nzb object
    :param proper: True if a Proper download, False if not.
    """
    if app.NZBGET_HOST is None:
        log.warning("No NZBget host found in configuration. Please configure it.")
        return False

    addToTop = False
    nzbgetprio = 0
    category = app.NZBGET_CATEGORY
    if nzb.series.is_anime:
        category = app.NZBGET_CATEGORY_ANIME

    url = "http{}://{}:{}@{}/xmlrpc".format(
        "s" if app.NZBGET_USE_HTTPS else "",
        app.NZBGET_USERNAME,
        app.NZBGET_PASSWORD,
        app.NZBGET_HOST,
    )

    if not NZBConnection(url):
        return False

    nzbGetRPC = ServerProxy(url)

    dupekey = ""
    dupescore = 0
    # if it aired recently make it high priority and generate DupeKey/Score
    for cur_ep in nzb.episodes:
        if dupekey == "":
            if cur_ep.series.indexer == 1:
                dupekey = "Medusa-" + text_type(cur_ep.series.indexerid)
            elif cur_ep.series.indexer == 2:
                dupekey = "Medusa-tvr" + text_type(cur_ep.series.indexerid)
        dupekey += "-" + text_type(cur_ep.season) + "." + text_type(cur_ep.episode)
        if datetime.date.today() - cur_ep.airdate <= datetime.timedelta(days=7):
            addToTop = True
            nzbgetprio = app.NZBGET_PRIORITY
        else:
            category = app.NZBGET_CATEGORY_BACKLOG
            if nzb.series.is_anime:
                category = app.NZBGET_CATEGORY_ANIME_BACKLOG

    if nzb.quality != Quality.UNKNOWN:
        dupescore = nzb.quality * 100
    if proper:
        dupescore += 10

    nzbcontent64 = None
    if nzb.result_type == "nzbdata":
        data = nzb.extra_info[0]
        nzbcontent64 = standard_b64encode(data)

    log.info("Sending NZB to NZBget")
    log.debug("URL: {}", url)

    try:
        # Find out if nzbget supports priority (Version 9.0+),
        # old versions beginning with a 0.x will use the old command
        nzbget_version_str = nzbGetRPC.version()
        nzbget_version = try_int(nzbget_version_str[: nzbget_version_str.find(".")])
        if nzbget_version == 0:
            if nzbcontent64:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, addToTop, nzbcontent64
                )
            else:
                if nzb.result_type == "nzb":
                    if not nzb.provider.login():
                        return False

                    # TODO: Check if this needs exception handling
                    data = nzb.provider.session(nzb.url).content
                    if data is None:
                        return False

                    nzbcontent64 = standard_b64encode(data)

                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, addToTop, nzbcontent64
                )
        elif nzbget_version == 12:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb",
                    category,
                    nzbgetprio,
                    False,
                    nzbcontent64,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
            else:
                nzbget_result = nzbGetRPC.appendurl(
                    nzb.name + ".nzb",
                    category,
                    nzbgetprio,
                    False,
                    nzb.url,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
        # v13+ has a new combined append method that accepts both (url and
        # content) also the return value has changed from boolean to integer
        # (Positive number representing NZBID of the queue item. 0 and negative
        # numbers represent error codes.)
        elif nzbget_version >= 13:
            nzbget_result = (
                nzbGetRPC.append(
                    nzb.name + ".nzb",
                    nzbcontent64 if nzbcontent64 is not None else nzb.url,
                    category,
                    nzbgetprio,
                    False,
                    False,
                    dupekey,
                    dupescore,
                    "score",
                )
                > 0
            )
        else:
            if nzbcontent64 is not None:
                nzbget_result = nzbGetRPC.append(
                    nzb.name + ".nzb", category, nzbgetprio, False, nzbcontent64
                )
            else:
                nzbget_result = nzbGetRPC.appendurl(
                    nzb.name + ".nzb", category, nzbgetprio, False, nzb.url
                )

        if nzbget_result:
            log.debug("NZB sent to NZBget successfully")
            return True
        else:
            log.warning(
                "NZBget could not add {name}.nzb to the queue", {"name": nzb.name}
            )
            return False
    except Exception:
        log.warning(
            "Connect Error to NZBget: could not add {name}.nzb to the queue",
            {"name": nzb.name},
        )
        return False