def convertor(ut_data: str, qbt_dir: str):
    """ Converts from uTorrent resume.dat to qBt

        @ut_data Path to uT resum.data
        @qbt_dir Path to store results
    """
    message = messagebox
    """
    backup_data = ".".join((ut_data, "old"))
    try:
        copy(ut_data, backup_data)
    except IOError:
        if message.askyesno("Backup error", "Cannot back-up UT data\nIs it ok?"):
            backup_data = ""
        else:
            return
    """

    with open(ut_data, 'rb') as ut_fd:
        data = ut_fd.read()

        try:
            torrents = bdecode(data)
        except DecodingError as error:
            message.showerror(
                "Decoding error", "".join(
                    ("Cannot decode uTorrent data\n", "Error: ", str(error))))
            return

    ut_folder = path.dirname(ut_data)

    print(torrents)
    for key, value in torrents.items():
        torrent_file = path.join(ut_folder, key)
        with open(torrent_file, 'rb') as ut_fd:
            try:
                bdecoded_data = bdecode(ut_fd.read())
            except BTFailure:
                continue
            tor_file = punchup(value, bdecoded_data)

            file_hash = sha1(bencode(tor_file["info"])).hexdigest().lower()

            #paths
            path_torrent_file = path.join(qbt_dir, ".".join(
                (file_hash, "torrent")))
            path_fast_resume = path.join(qbt_dir, ".".join(
                (file_hash, "fastresume")))

            if path.exists(path_torrent_file) or path.exists(path_fast_resume):
                continue

            fast_resume_file = mkfr(value, tor_file)

            with open(path_torrent_file, "wb") as tor_file:
                tor_file.write(bencode(tor_file))

            with open(path_fast_resume, "wb") as tor_file:
                tor_file.write(bencode(fast_resume_file))
def convertor(ut_data: str, qbt_dir: str):
    """ Converts from uTorrent resume.dat to qBt

        @ut_data Path to uT resum.data
        @qbt_dir Path to store results
    """
    message = messagebox

    """
    backup_data = ".".join((ut_data, "old"))
    try:
        copy(ut_data, backup_data)
    except IOError:
        if message.askyesno("Backup error", "Cannot back-up UT data\nIs it ok?"):
            backup_data = ""
        else:
            return
    """

    with open(ut_data, 'rb') as ut_fd:
        data = ut_fd.read()

        try:
            torrents = bdecode(data)
        except DecodingError as error:
            message.showerror("Decoding error", "".join(("Cannot decode uTorrent data\n",
                                                         "Error: ", str(error))))
            return

    ut_folder = path.dirname(ut_data)

    print(torrents)
    for key, value in torrents.items():
        torrent_file = path.join(ut_folder, key)
        with open(torrent_file, 'rb') as ut_fd:
            try:
                bdecoded_data = bdecode(ut_fd.read())
            except BTFailure:
                continue
            tor_file = punchup(value, bdecoded_data)

            file_hash = sha1(bencode(tor_file["info"])).hexdigest().lower()

            #paths
            path_torrent_file = path.join(qbt_dir, ".".join((file_hash, "torrent")))
            path_fast_resume = path.join(qbt_dir, ".".join((file_hash, "fastresume")))

            if path.exists(path_torrent_file) or path.exists(path_fast_resume):
                continue

            fast_resume_file = mkfr(value, tor_file)

            with open(path_torrent_file, "wb") as tor_file:
                tor_file.write(bencode(tor_file))

            with open(path_fast_resume, "wb") as tor_file:
                tor_file.write(bencode(fast_resume_file))
def mkfr(res, tor):
    """ Creates libtorrent fast resume file.

        @res uTorrent data.
        @tor Torrent File.
    """
    qbt_torrent = FIELD_MAP
    time_now = int(time())
    pieces_num = int(tor['info']['pieces'].size / 20)  # SHA1 hash is 20 bytes
    qbt_torrent['added_time'] = int(res['added_on'])
    qbt_torrent['completed_time'] = int(res['completed_on'])
    qbt_torrent['active_time'] = int(res['runtime'])
    qbt_torrent['seeding_time'] = qbt_torrent['active_time']
    qbt_torrent['blocks per piece'] = int(
        int(tor['info']['piece length']) / int(res['blocksize']))
    qbt_torrent['info-hash'] = sha1(bencode(tor['info'])).digest()
    qbt_torrent['paused'] = 1 if res['started'] == 0 else 0
    qbt_torrent['auto_managed'] = 0
    qbt_torrent['total_downloaded'] = int(res['downloaded'])
    qbt_torrent['total_uploaded'] = int(res['uploaded'])
    qbt_torrent['upload_rate_limit'] = int(res['upspeed'])
    qbt_torrent['trackers'] = [[tracker] for tracker in res['trackers']]
    #wat?
    qbt_torrent['piece_priority'] = "".join(
        bin(hexik)[2:] * pieces_num for hexik in res["have"])
    #wat?
    qbt_torrent['pieces'] = qbt_torrent['piece_priority']
    qbt_torrent['finished_time'] = time_now - qbt_torrent['completed_time']
    qbt_torrent['last_seen_complete'] = int(
        time_now) if qbt_torrent["finished_time"] else 0
    qbt_torrent['last_download'] = qbt_torrent['finished_time']
    qbt_torrent['last_scrape'] = qbt_torrent['finished_time']
    qbt_torrent['last_upload'] = qbt_torrent['finished_time']
    qbt_torrent['mapped_files'] = []
    qbt_torrent['file sizes'] = []
    # Per file fields:
    ##########
    # mapped_files
    # file_priority
    # file sizes
    #wat?
    get_hex = re_compile("[0-9A-Fa-f][0-9A-Fa-f]")
    qbt_torrent["file_priority"] = [
        (1 if int(hex_number, 16) in range(1, 9) else
         (2 if int(hex_number, 16) in range(9, 16) else (0)))
        for hex_number in get_hex.split(res["prio"])
    ]

    fmt = 0
    if "files" in tor['info']:
        for file_index in range(len(tor['info']['files'])):
            tor_file = tor['info']['files'][file_index]
            qbt_torrent['mapped_files'].append(path.normpath(tor_file))

            if not "modtimes" in res:
                fmt = int(res['modtimes'][file_index])
            else:
                fmt = 0

            res_file = path.join(res['path'], qbt_torrent['mapped_files'][-1])
            if path.isfile(res_file) and not fmt:
                fmt = int(path.getmtime(res_file))

            if qbt_torrent['file_priority'][file_index]:
                qbt_torrent['file sizes'].append(
                    [int(tor_file['length']), fmt])
            else:
                qbt_torrent['file sizes'].append([0, 0])

        qbt_torrent['qBt-savePath'] = res['path']

    else:
        qbt_torrent['qBt-savePath'] = path.dirname(res['path'])

        if "modtimes" in res:
            fmt = int(res['modtimes']
                      [0])  # file time to avoid checking / not presen in ut2.2
        else:
            fmt = 0

        res_file = res['path']
        if path.isfile(res_file) and not fmt:
            fmt = int(path.getmtime(res_file))

        if qbt_torrent['file_priority'][0]:
            qbt_torrent['file sizes'].append([int(tor['info']['length']), fmt])
        else:
            qbt_torrent['file sizes'].append([0, 0])
    ##########
    # qBittorrent 3.1+ Fields
    ##########
    if "label" in res:
        qbt_torrent['qBt-label'] = res['label']
    qbt_torrent['qBt-queuePosition'] = -1  # -1 for completed
    qbt_torrent['qBt-seedDate'] = qbt_torrent['completed_time']
    qbt_torrent[
        'qBt-ratioLimit'] = "-2"  # -2 = Use Global, -1 = No limit, other number = actual ratio?
    return qbt_torrent
def mkfr(res, tor):
    """ Creates libtorrent fast resume file.

        @res uTorrent data.
        @tor Torrent File.
    """
    qbt_torrent = FIELD_MAP
    time_now = int(time())
    pieces_num = int(tor['info']['pieces'].size / 20) # SHA1 hash is 20 bytes
    qbt_torrent['added_time']               = int(res['added_on'])
    qbt_torrent['completed_time']           = int(res['completed_on'])
    qbt_torrent['active_time']              = int(res['runtime'])
    qbt_torrent['seeding_time']             = qbt_torrent['active_time']
    qbt_torrent['blocks per piece']         = int(int(tor['info']['piece length']) / int(res['blocksize']))
    qbt_torrent['info-hash']                = sha1(bencode(tor['info'])).digest()
    qbt_torrent['paused']                   = 1 if res['started'] == 0 else 0
    qbt_torrent['auto_managed']             = 0
    qbt_torrent['total_downloaded']         = int(res['downloaded'])
    qbt_torrent['total_uploaded']           = int(res['uploaded'])
    qbt_torrent['upload_rate_limit']        = int(res['upspeed'])
    qbt_torrent['trackers']                 = [[tracker] for tracker in res['trackers']]
    #wat?
    qbt_torrent['piece_priority']           = "".join(bin(hexik)[2:]*pieces_num for hexik in res["have"])
    #wat?
    qbt_torrent['pieces']                   = qbt_torrent['piece_priority']
    qbt_torrent['finished_time']            = time_now - qbt_torrent['completed_time']
    qbt_torrent['last_seen_complete']       = int(time_now) if qbt_torrent["finished_time"] else 0
    qbt_torrent['last_download']            = qbt_torrent['finished_time']
    qbt_torrent['last_scrape']              = qbt_torrent['finished_time']
    qbt_torrent['last_upload']              = qbt_torrent['finished_time']
    qbt_torrent['mapped_files']             = []
    qbt_torrent['file sizes']               = []
    # Per file fields:
    ##########
    # mapped_files
    # file_priority
    # file sizes
    #wat?
    get_hex = re_compile("[0-9A-Fa-f][0-9A-Fa-f]")
    qbt_torrent["file_priority"] = [(1 if int(hex_number, 16) in range(1, 9) else
                                     (2 if int(hex_number, 16) in range(9, 16) else
                                     (0))) for hex_number in get_hex.split(res["prio"])]

    fmt = 0
    if "files" in tor['info']:
        for file_index in range(len(tor['info']['files'])):
            tor_file = tor['info']['files'][file_index]
            qbt_torrent['mapped_files'].append(path.normpath(tor_file))

            if not "modtimes" in res:
                fmt = int(res['modtimes'][file_index])
            else:
                fmt = 0

            res_file = path.join(res['path'], qbt_torrent['mapped_files'][-1])
            if path.isfile(res_file) and not fmt:
                fmt = int(path.getmtime(res_file))

            if qbt_torrent['file_priority'][file_index]:
                qbt_torrent['file sizes'].append([int(tor_file['length']), fmt])
            else:
                qbt_torrent['file sizes'].append([0, 0])

        qbt_torrent['qBt-savePath'] = res['path']

    else:
        qbt_torrent['qBt-savePath'] = path.dirname(res['path'])

        if "modtimes" in res:
            fmt = int(res['modtimes'][0]) # file time to avoid checking / not presen in ut2.2
        else:
            fmt = 0

        res_file = res['path']
        if path.isfile(res_file) and not fmt:
            fmt = int(path.getmtime(res_file))

        if qbt_torrent['file_priority'][0]:
            qbt_torrent['file sizes'].append([int(tor['info']['length']), fmt])
        else:
            qbt_torrent['file sizes'].append([0, 0])
    ##########
    # qBittorrent 3.1+ Fields
    ##########
    if "label" in res:
        qbt_torrent['qBt-label']        = res['label']
    qbt_torrent['qBt-queuePosition']    = -1  # -1 for completed
    qbt_torrent['qBt-seedDate']         = qbt_torrent['completed_time']
    qbt_torrent['qBt-ratioLimit']       = "-2"  # -2 = Use Global, -1 = No limit, other number = actual ratio?
    return qbt_torrent