# Buggy code
def update_network_dict():
    """Update timezone information from Medusa repositories"""

    url = "https://cdn.pymedusa.com/sb_network_timezones/network_timezones.txt"
    url_data = helpers.getURL(url, session=helpers.make_session(), returns="text")
    if not url_data:
        logger.log(
            "Updating network timezones failed, this can happen from time to time. URL: %s"
            % url,
            logger.WARNING,
        )
        load_network_dict()
        return

    d = {}
    try:
        for line in url_data.splitlines():
            (key, val) = line.strip().rsplit(":", 1)
            if key is None or val is None:
                continue
            d[key] = val
    except (IOError, OSError):
        pass

    cache_db_con = db.DBConnection("cache.db")

    network_list = dict(cache_db_con.select("SELECT * FROM network_timezones;"))

    queries = []
    for network, timezone in iteritems(d):
        existing = network in network_list
        if not existing:
            queries.append(
                [
                    "INSERT OR IGNORE INTO network_timezones VALUES (?,?);",
                    [network, timezone],
                ]
            )
        elif network_list[network] != timezone:
            queries.append(
                [
                    "UPDATE OR IGNORE network_timezones SET timezone = ? WHERE network_name = ?;",
                    [timezone, network],
                ]
            )

        if existing:
            del network_list[network]

    if network_list:
        purged = [x for x in network_list]
        queries.append(
            [
                "DELETE FROM network_timezones WHERE network_name IN (%s);"
                % ",".join(["?"] * len(purged)),
                purged,
            ]
        )

    if queries:
        cache_db_con.mass_action(queries)
        load_network_dict()


# Traceback (ConnectionError)
DAILYSEARCHER :: [b9d562e] Exception generated in thread DAILYSEARCHER: error HTTPSConnectionPool(host='cdn.pymedusa.com', port=443): Max retries exceeded with url: /sb_network_timezones/network_timezones.txt (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x699fdbb0>: Failed to establish a new connection: [Errno -2] Nome ou servi\xc3\xa7o desconhecido',))
Traceback (most recent call last):
File "/home/osmc/SickRage/sickbeard/scheduler.py", line 106, in run
self.action.run(self.force)
File "/home/osmc/SickRage/sickbeard/dailysearcher.py", line 75, in run
update_network_dict()
File "/home/osmc/SickRage/sickbeard/network_timezones.py", line 47, in update_network_dict
url_data = helpers.getURL(url, session=helpers.make_session(), returns='text')
File "/home/osmc/SickRage/sickbeard/helpers.py", line 1423, in getURL
verify=verify)
File "/home/osmc/SickRage/lib/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/home/osmc/SickRage/lib/requests/sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "/home/osmc/SickRage/lib/cachecontrol/adapter.py", line 46, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "/home/osmc/SickRage/lib/requests/adapters.py", line 467, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='cdn.pymedusa.com', port=443): Max retries exceeded with url: /sb_network_timezones/network_timezones.txt (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x699fdbb0>: Failed to establish a new connection: [Errno -2] Nome ou servi\xc3\xa7o desconhecido',))

# Fixed code
def update_network_dict():
    """Update timezone information from Medusa repositories"""

    url = "https://cdn.pymedusa.com/sb_network_timezones/network_timezones.txt"
    url_data = helpers.getURL(url, session=helpers.make_session(), returns="response")
    if not url_data.text:
        logger.log(
            "Updating network timezones failed, this can happen from time to time. URL: %s"
            % url,
            logger.WARNING,
        )
        load_network_dict()
        return

    d = {}
    try:
        for line in url_data.text.splitlines():
            (key, val) = line.strip().rsplit(":", 1)
            if key is None or val is None:
                continue
            d[key] = val
    except (IOError, OSError):
        pass

    cache_db_con = db.DBConnection("cache.db")

    network_list = dict(cache_db_con.select("SELECT * FROM network_timezones;"))

    queries = []
    for network, timezone in iteritems(d):
        existing = network in network_list
        if not existing:
            queries.append(
                [
                    "INSERT OR IGNORE INTO network_timezones VALUES (?,?);",
                    [network, timezone],
                ]
            )
        elif network_list[network] != timezone:
            queries.append(
                [
                    "UPDATE OR IGNORE network_timezones SET timezone = ? WHERE network_name = ?;",
                    [timezone, network],
                ]
            )

        if existing:
            del network_list[network]

    if network_list:
        purged = [x for x in network_list]
        queries.append(
            [
                "DELETE FROM network_timezones WHERE network_name IN (%s);"
                % ",".join(["?"] * len(purged)),
                purged,
            ]
        )

    if queries:
        cache_db_con.mass_action(queries)
        load_network_dict()