示例#1
0
def has_buy_auto_updater_dlc(cfg: Config):
    retrtCfg = cfg.common.retry
    for idx in range(retrtCfg.max_retry_count):
        try:
            uploader = Uploader(lanzou_cookie)
            user_list_filepath = uploader.download_file_in_folder(uploader.folder_online_files, uploader.buy_auto_updater_users_filename, ".cached", show_log=False)
            buy_users = []
            with open(user_list_filepath, 'r', encoding='utf-8') as data_file:
                buy_users = json.load(data_file)

            if len(buy_users) == 0:
                # note: 如果读取失败或云盘该文件列表为空,则默认所有人都放行
                return True

            for account_cfg in cfg.account_configs:
                qq = uin2qq(account_cfg.account_info.uin)
                if qq in buy_users:
                    return True

            return False
        except Exception as e:
            logFunc = logger.debug
            if use_by_myself():
                logFunc = logger.error
            logFunc(f"第{idx + 1}次检查是否购买DLC时出错了,稍后重试", exc_info=e)
            time.sleep(retrtCfg.retry_wait_time)

    return True
示例#2
0
def auto_update():
    args = parse_args()

    change_title("自动更新DLC")

    logger.info(color("bold_yellow") + f"更新器的进程为{os.getpid()}, 代码版本为{now_version}")
    logger.info(color("bold_yellow") + f"需要检查更新的小助手主进程为{args.pid}, 版本为{args.version}")

    # note: 工作目录预期为小助手的exe所在目录
    if args.cwd == invalid_cwd:
        logger.error("请不要直接双击打开自动更新工具,正确的用法是放到utils目录后,照常双击【DNF蚊子腿小助手.exe】来使用,小助手会自行调用自动更新DLC的")
        os.system("PAUSE")
        return

    logger.info(f"切换工作目录到{args.cwd}")
    os.chdir(args.cwd)

    if not exists_flag_file(".use_proxy"):
        bypass_proxy()
        logger.info(f"当前已默认无视系统代理(VPN),如果需要dlc使用代理,请在小助手目录创建 .use_proxy 目录或文件")

    uploader = Uploader()

    # 进行实际的检查是否需要更新操作
    latest_version = uploader.latest_version()
    logger.info(f"当前版本为{args.version},网盘最新版本为{latest_version}")

    if need_update(args.version, latest_version):
        update(args, uploader)
        start_new_version(args)
    else:
        logger.info("已经是最新版本,不需要更新")
示例#3
0
def auto_update():
    args = parse_args()

    logger.info(
        f"更新器的进程为{os.getpid()}, 版本为{auto_updater_version}(主代码版本为{now_version}),主进程为{args.pid}, 版本为{args.version}"
    )

    # note: 工作目录预期为小助手的exe所在目录
    if args.cwd == invalid_cwd:
        logger.error(
            "请不要直接双击打开自动更新工具,正确的用法是放到utils目录后,照常双击【DNF蚊子腿小助手.exe】来使用,小助手会自行调用自动更新DLC的"
        )
        os.system("PAUSE")
        return

    logger.info(f"切换工作目录到{args.cwd}")
    os.chdir(args.cwd)

    uploader = Uploader(lanzou_cookie)

    # 进行实际的检查是否需要更新操作
    latest_version = uploader.latest_version()
    logger.info(f"当前版本为{args.version},网盘最新版本为{latest_version}")

    if need_update(args.version, latest_version):
        update(args, uploader)
        start_new_version(args)
    else:
        logger.info("已经是最新版本,不需要更新")
示例#4
0
    def download_latest_notices(self):
        uploader = Uploader()

        dirpath, filename = os.path.dirname(self.cache_path), os.path.basename(
            self.cache_path)
        uploader.download_file_in_folder(uploader.folder_online_files,
                                         filename,
                                         dirpath,
                                         try_compressed_version_first=True)
示例#5
0
def upload():
    logger.info("开始上传到蓝奏云")
    with open("upload_cookie.json") as fp:
        cookie = json.load(fp)
    uploader = Uploader(cookie)
    if uploader.login_ok:
        logger.info("蓝奏云登录成功,开始更新付费名单")
        uploader.upload_to_lanzouyun(os.path.realpath(local_save_path), uploader.folder_online_files, uploader.user_monthly_pay_info_filename)
    else:
        logger.error("蓝奏云登录失败")
示例#6
0
def get_update_desc(config: CommonConfig):
    try:
        uploader = Uploader(lanzou_cookie)
        latest_version = uploader.latest_version()

        if not need_update(now_version, latest_version):
            return ""

        return f"最新版本为v{latest_version},请及时更新~"
    except Exception as e:
        logger.debug("get_update_desc error", exc_info=e)
        return ""
示例#7
0
def upload():
    logger.info("购买用户有变动,开始上传到蓝奏云")
    with open("upload_cookie.json") as fp:
        cookie = json.load(fp)
    uploader = Uploader(cookie)
    if uploader.login_ok:
        logger.info("蓝奏云登录成功,开始更新购买名单")
        uploader.upload_to_lanzouyun(os.path.realpath(local_save_path),
                                     uploader.folder_online_files,
                                     uploader.buy_auto_updater_users_filename)
    else:
        logger.error("蓝奏云登录失败")
示例#8
0
def has_buy_auto_updater_dlc(cfg: Config):
    retrtCfg = cfg.common.retry
    for idx in range(retrtCfg.max_retry_count):
        try:
            uploader = Uploader(lanzou_cookie)
            has_no_users = True
            for remote_filename in [
                    uploader.buy_auto_updater_users_filename,
                    uploader.cs_buy_auto_updater_users_filename
            ]:
                try:
                    user_list_filepath = uploader.download_file_in_folder(
                        uploader.folder_online_files,
                        remote_filename,
                        ".cached",
                        show_log=False)
                except FileNotFoundError as e:
                    # 如果网盘没有这个文件,就跳过
                    continue

                buy_users = []
                with open(user_list_filepath, 'r',
                          encoding='utf-8') as data_file:
                    buy_users = json.load(data_file)

                if len(buy_users) != 0:
                    has_no_users = False

                for account_cfg in cfg.account_configs:
                    qq = uin2qq(account_cfg.account_info.uin)
                    if qq in buy_users:
                        return True

                logger.debug((
                    "DLC购买调试日志:\n"
                    f"remote_filename={remote_filename}\n"
                    f"账号列表={[uin2qq(account_cfg.account_info.uin) for account_cfg in cfg.account_configs]}\n"
                    f"用户列表={buy_users}\n"))

            if has_no_users:
                # note: 如果读取失败或云盘该文件列表为空,则默认所有人都放行
                return True

            return False
        except Exception as e:
            logFunc = logger.debug
            if use_by_myself():
                logFunc = logger.error
            logFunc(f"第{idx + 1}次检查是否购买DLC时出错了,稍后重试", exc_info=e)
            time.sleep(retrtCfg.retry_wait_time)

    return True
示例#9
0
def get_user_buy_info(cfg: Config):
    retrtCfg = cfg.common.retry
    default_user_buy_info = BuyInfo()
    for idx in range(retrtCfg.max_retry_count):
        try:
            # 默认设置首个qq为购买信息
            default_user_buy_info.qq = uin2qq(
                cfg.account_configs[0].account_info.uin)

            uploader = Uploader(lanzou_cookie)
            buy_info_filepath = uploader.download_file_in_folder(
                uploader.folder_online_files,
                uploader.user_monthly_pay_info_filename,
                ".cached",
                show_log=False)
            buy_users = {}  # type: Dict[str, BuyInfo]
            with open(buy_info_filepath, 'r', encoding='utf-8') as data_file:
                raw_infos = json.load(data_file)
                for qq, raw_info in raw_infos.items():
                    info = BuyInfo().auto_update_config(raw_info)
                    buy_users[qq] = info
                    for game_qq in info.game_qqs:
                        buy_users[game_qq] = info

            if len(buy_users) == 0:
                # note: 如果读取失败或云盘该文件列表为空,则默认所有人都放行
                default_user_buy_info.expire_at = "2120-01-01 00:00:00"
                return default_user_buy_info

            user_buy_info = default_user_buy_info
            for account_cfg in cfg.account_configs:
                qq = uin2qq(account_cfg.account_info.uin)
                if qq in buy_users:
                    if time_less(user_buy_info.expire_at,
                                 buy_users[qq].expire_at):
                        # 若当前配置的账号中有多个账号都付费了,选择其中付费结束时间最晚的那个
                        user_buy_info = buy_users[qq]

            return user_buy_info
        except Exception as e:
            logFunc = logger.debug
            if use_by_myself():
                logFunc = logger.error
            logFunc(f"第{idx + 1}次检查是否付费时出错了,稍后重试", exc_info=e)
            time.sleep(retrtCfg.retry_wait_time)

    return default_user_buy_info
示例#10
0
def demo():
    logger.info(
        color("bold_yellow") +
        "尝试启动更新器,等待其执行完毕。若版本有更新,则会干掉这个进程并下载更新文件,之后重新启动进程...(请稍作等待)")

    dlc_path = os.path.realpath("auto_updater.py")
    p = subprocess.Popen([
        dlc_path,
        "--pid",
        str(os.getpid()),
        "--version",
        str(now_version),
        "--cwd",
        os.getcwd(),
        "--exe_name",
        os.path.realpath("DNF蚊子腿小助手.exe"),
    ],
                         cwd="utils",
                         shell=True,
                         creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
                         | subprocess.DETACHED_PROCESS,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    p.wait()

    if p.returncode != 0:
        last_modify_time = parse_timestamp(os.stat(dlc_path).st_mtime)
        logger.error(
            f"DLC出错了,错误码为{p.returncode},DLC最后一次修改时间为{last_modify_time}")

        uploader = Uploader()
        netdisk_latest_dlc_info = uploader.find_latest_dlc_version()
        latest_version_time = parse_time(netdisk_latest_dlc_info.time)

        if latest_version_time > last_modify_time:
            logger.info(
                f"网盘中最新版本dlc上传于{latest_version_time}左右,在当前版本最后修改时间{last_modify_time}之后,有可能已经修复dlc的该问题,将尝试更新dlc为最新版本"
            )
            uploader.download_file(netdisk_latest_dlc_info, "utils")
        else:
            logger.warning(
                f"网盘中最新版本dlc上传于{latest_version_time}左右,在当前版本最后修改时间{last_modify_time}之前,请耐心等待修复该问题的新版本发布~"
            )
示例#11
0
def test():
    global TEST_MODE
    TEST_MODE = True

    logger.info(color("bold_yellow") + "开始测试更新器功能(不会实际覆盖文件)")

    args = parse_args()
    uploader = Uploader()

    full_update(args, uploader)
示例#12
0
def auto_update():
    args = parse_args()

    logger.info("更新器的进程为{},主进程为{}".format(os.getpid(), args.pid))

    # note: 工作目录预期为小助手的exe所在目录
    logger.info("切换工作目录到{}".format(args.cwd))
    os.chdir(args.cwd)

    uploader = Uploader(lanzou_cookie)

    # 进行实际的检查是否需要更新操作
    latest_version = uploader.latest_version()
    logger.info("当前版本为{},网盘最新版本为{}".format(args.version, latest_version))

    if need_update(args.version, latest_version):
        update(args, uploader)
        start_new_version(args)
    else:
        logger.info("已经是最新版本,不需要更新")
示例#13
0
文件: notice.py 项目: Fine112358/dnf-
    def save(self):
        # 本地存盘
        with open(self.save_path, 'w', encoding='utf-8') as save_file:
            json.dump(to_raw_type(self.notices), save_file, ensure_ascii=False, indent=2)
            logger.info("公告存盘完毕")

        # 上传到网盘
        uploader = Uploader()
        with open("upload_cookie.json") as fp:
            cookie = json.load(fp)
        uploader.login(cookie)
        uploader.upload_to_lanzouyun(self.save_path, uploader.folder_online_files, also_upload_compressed_version=True)
示例#14
0
                               dir_github_action_artifact,
                               get_final_patch_path_only=True)

# ---------------标记新版本
show_head_line(f"提交版本和版本变更说明,并同步到docs目录,用于生成github pages",
               color("bold_yellow"))
os.chdir(dir_src)
commit_new_version()

# ---------------上传到蓝奏云
show_head_line(f"开始上传到蓝奏云", color("bold_yellow"))
os.chdir(dir_src)
with open("upload_cookie.json") as fp:
    cookie = json.load(fp)
os.chdir(dir_all_release)
uploader = Uploader()
uploader.login(cookie)
if uploader.login_ok:
    logger.info("蓝奏云登录成功,开始上传压缩包")

    def path_in_src(filepath_relative_to_src: str) -> str:
        return os.path.realpath(os.path.join(dir_src,
                                             filepath_relative_to_src))

    realpath = os.path.realpath

    upload_info_list = [(uploader.folder_djc_helper, [
        (realpath(release_7z_name), uploader.history_version_prefix),
        (path_in_src("utils/auto_updater.exe"), ""),
        (path_in_src("使用教程/使用文档.docx"), ""),
        (path_in_src("使用教程/视频教程.txt"), ""),
示例#15
0
def _get_user_buy_info(cfg: Config):
    retrtCfg = cfg.common.retry
    default_user_buy_info = BuyInfo()
    for try_idx in range(retrtCfg.max_retry_count):
        try:
            # 默认设置首个qq为购买信息
            default_user_buy_info.qq = uin2qq(cfg.account_configs[0].account_info.uin)

            uploader = Uploader(lanzou_cookie)
            has_no_users = True

            remote_filenames = [uploader.user_monthly_pay_info_filename, uploader.cs_user_monthly_pay_info_filename]
            import copy
            # 单种渠道内选择付费结束时间最晚的,手动和卡密间则叠加
            user_buy_info_list = [copy.deepcopy(default_user_buy_info) for v in remote_filenames]
            for idx, remote_filename in enumerate(remote_filenames):
                user_buy_info = user_buy_info_list[idx]

                try:
                    buy_info_filepath = uploader.download_file_in_folder(uploader.folder_online_files, remote_filename, ".cached", show_log=False)
                except FileNotFoundError as e:
                    # 如果网盘没有这个文件,就跳过
                    continue

                buy_users = {}  # type: Dict[str, BuyInfo]
                with open(buy_info_filepath, 'r', encoding='utf-8') as data_file:
                    raw_infos = json.load(data_file)
                    for qq, raw_info in raw_infos.items():
                        info = BuyInfo().auto_update_config(raw_info)
                        buy_users[qq] = info
                        for game_qq in info.game_qqs:
                            buy_users[game_qq] = info

                if len(buy_users) != 0:
                    has_no_users = False

                for account_cfg in cfg.account_configs:
                    qq = uin2qq(account_cfg.account_info.uin)
                    if qq in buy_users:
                        if time_less(user_buy_info.expire_at, buy_users[qq].expire_at):
                            # 若当前配置的账号中有多个账号都付费了,选择其中付费结束时间最晚的那个
                            user_buy_info = buy_users[qq]

                user_buy_info_list[idx] = user_buy_info

            if has_no_users:
                # note: 如果读取失败或云盘该文件列表为空,则默认所有人都放行
                default_user_buy_info.expire_at = "2120-01-01 00:00:00"
                return default_user_buy_info

            merged_user_buy_info = copy.deepcopy(default_user_buy_info)
            for user_buy_info in user_buy_info_list:
                if user_buy_info.total_buy_month == 0:
                    continue

                if merged_user_buy_info.total_buy_month == 0:
                    merged_user_buy_info = copy.deepcopy(user_buy_info)
                else:
                    merged_user_buy_info.merge(user_buy_info)

            return merged_user_buy_info
        except Exception as e:
            logFunc = logger.debug
            if use_by_myself():
                logFunc = logger.error
            logFunc(f"第{try_idx + 1}次检查是否付费时出错了,稍后重试", exc_info=e)
            time.sleep(retrtCfg.retry_wait_time)

    return default_user_buy_info
示例#16
0
# ---------------构建
# 调用构建脚本
os.chdir(dir_src)
build()

# ---------------打包
os.chdir(dir_src)
package(dir_src, dir_all_release, release_dir_name, release_7z_name)

# ---------------上传到蓝奏云
logger.info("开始上传到蓝奏云")
os.chdir(dir_src)
with open("upload_cookie.json") as fp:
    cookie = json.load(fp)
os.chdir(dir_all_release)
uploader = Uploader(cookie)
if uploader.login_ok:
    logger.info("蓝奏云登录成功,开始上传压缩包")
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_djc_helper)
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_dnf_calc)
else:
    logger.error("蓝奏云登录失败")

# ---------------推送版本到github
# 打包完成后git添加标签
os.chdir(dir_src)
logger.info("开始推送到github")
# 先尝试移除该tag,并同步到github,避免后面加标签失败
subprocess.call(['git', 'tag', '-d', version])
subprocess.call(['git', 'push', 'origin', 'master', ':refs/tags/{version}'.format(version=version)])
# 然后添加新tab,并同步到github
示例#17
0
patch_file_name = create_patch(dir_src, dir_all_release,
                               create_patch_for_latest_n_version,
                               dir_github_action_artifact)

# ---------------标记新版本
logger.info("提交版本和版本变更说明,并同步到docs目录,用于生成github pages")
os.chdir(dir_src)
commit_new_version()

# ---------------上传到蓝奏云
logger.info("开始上传到蓝奏云")
os.chdir(dir_src)
with open("upload_cookie.json") as fp:
    cookie = json.load(fp)
os.chdir(dir_all_release)
uploader = Uploader(cookie)
if uploader.login_ok:
    logger.info("蓝奏云登录成功,开始上传压缩包")
    uploader.upload_to_lanzouyun(
        patch_file_name,
        uploader.folder_djc_helper,
        history_file_prefix=uploader.history_patches_prefix)
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_djc_helper)
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_dnf_calc)
else:
    logger.error("蓝奏云登录失败")

# ---------------推送版本到github
# 打包完成后git添加标签
os.chdir(dir_src)
logger.info("开始推送到github")
示例#18
0
    def check_and_download_chrome_ahead(self):
        """
        尝试预先下载解压缩chrome的driver和便携版
        主要用于处理多进程模式下,可能多个进程同时尝试该操作导致的问题
        :return:
        """
        logger.info("检查chrome相关内容是否ok")
        logger.info(
            color("bold_yellow") +
            f"如果自动下载失败,可能是网络问题,请根据提示下载的内容,自行去网盘下载该内容到utils目录下 https://fzls.lanzoui.com/s/djc-tools"
        )
        chrome_driver_exe_name = os.path.basename(
            self.chrome_driver_executable_path())
        zip_name = os.path.basename(self.chrome_binary_7z())
        chrome_root_directory = self.chrome_root_directory()

        logger.info("检查driver是否存在")
        if not os.path.isfile(self.chrome_driver_executable_path()):
            logger.info(
                color("bold_yellow") +
                f"未在小助手utils目录里发现 {chrome_driver_exe_name} ,将尝试从网盘下载")
            uploader = Uploader()
            uploader.download_file_in_folder(uploader.folder_djc_helper_tools,
                                             chrome_driver_exe_name,
                                             chrome_root_directory)

        options = Options()
        options.headless = True
        options.add_experimental_option("excludeSwitches", ["enable-logging"])
        if not self.cfg.force_use_portable_chrome:
            try:
                logger.info("检查系统自带的chrome是否可用")
                self.driver = webdriver.Chrome(
                    executable_path=self.chrome_driver_executable_path(),
                    options=options)
                self.driver.quit()
                return
            except:
                logger.info("走到这里说明系统自带的chrome不可用")
                pass
        else:
            logger.info("当前配置为强制使用便携版chrome")

        # 尝试从网盘下载合适版本的便携版chrome
        if not os.path.isfile(self.chrome_binary_7z()):
            logger.info(
                color("bold_yellow") +
                f"本地未发现便携版chrome的压缩包,尝试自动从网盘下载 {zip_name},需要下载大概80MB的压缩包,请耐心等候"
            )
            uploader = Uploader()
            uploader.download_file_in_folder(uploader.folder_djc_helper_tools,
                                             zip_name, chrome_root_directory)

        # 尝试解压
        if not os.path.isdir(self.chrome_binary_directory()):
            logger.info(f"自动解压便携版chrome到当前目录")
            decompress_dir_with_bandizip(
                self.chrome_binary_7z(),
                dst_parent_folder=chrome_root_directory)

        logger.info("检查便携版chrome是否有效")
        try:
            options.binary_location = self.chrome_binary_location()
            # you may need some other options
            options.add_argument('--no-sandbox')
            options.add_argument('--no-default-browser-check')
            options.add_argument('--no-first-run')
            self.driver = webdriver.Chrome(
                executable_path=self.chrome_driver_executable_path(),
                options=options)
            self.driver.quit()
            return
        except:
            pass

        # 走到这里,大概率是多线程并行下载导致文件出错了,尝试重新下载
        logger.info(color("bold_yellow") + "似乎chrome相关文件损坏了,尝试重新下载并解压")
        uploader = Uploader()
        uploader.download_file_in_folder(uploader.folder_djc_helper_tools,
                                         chrome_driver_exe_name,
                                         chrome_root_directory,
                                         cache_max_seconds=0)
        uploader.download_file_in_folder(uploader.folder_djc_helper_tools,
                                         zip_name,
                                         chrome_root_directory,
                                         cache_max_seconds=0)

        shutil.rmtree(self.chrome_binary_directory(), ignore_errors=True)
        decompress_dir_with_bandizip(self.chrome_binary_7z(),
                                     dst_parent_folder=chrome_root_directory)
示例#19
0
def create_patch(dir_src,
                 dir_all_release,
                 create_patch_for_latest_n_version,
                 dir_github_action_artifact,
                 get_final_patch_path_only=False) -> str:
    latest_version = now_version
    path_bz = os.path.join(dir_src, "utils/bandizip_portable", "bz.exe")

    old_cwd = os.getcwd()
    os.chdir(dir_all_release)
    if not get_final_patch_path_only:
        logger.info(f"工作目录已调整为{os.getcwd()},最新版本为v{latest_version}")

    uploader = Uploader()

    if not get_final_patch_path_only:
        logger.info(
            f"尝试从网盘查找在{latest_version}版本之前最近{create_patch_for_latest_n_version}个版本的信息"
        )
    old_version_infos = []  # type: List[HistoryVersionFileInfo]

    # 获取当前网盘的最新版本,若比当前发布版本低,也加入
    netdisk_latest_version_fileinfo = uploader.find_latest_version()
    netdisk_latest_version = uploader.parse_version_from_djc_helper_file_name(
        netdisk_latest_version_fileinfo.name)
    if version_less(netdisk_latest_version, latest_version):
        old_version_infos.append(
            HistoryVersionFileInfo(netdisk_latest_version_fileinfo,
                                   netdisk_latest_version))

    # 从历史版本网盘中查找旧版本
    for page in range_from_one(100):
        folder_info = uploader.get_folder_info_by_url(
            uploader.folder_history_files.url, get_this_page=page)
        for file in folder_info.files:
            filename = file.name  # type: str

            if not filename.startswith(uploader.history_version_prefix):
                # 跳过非历史版本的文件
                continue

            file_version = uploader.parse_version_from_djc_helper_file_name(
                filename)
            info = HistoryVersionFileInfo(file, file_version)

            if not version_less(file_version, latest_version):
                continue

            if info in old_version_infos:
                # 已经加入过(可能重复)
                continue

            old_version_infos.append(info)

        if len(old_version_infos) >= create_patch_for_latest_n_version + 2:
            # 已经找到超过前n+2个版本,因为网盘返回的必定是按上传顺序排列的,不过为了保险起见,多考虑一些
            break

    if create_patch_for_latest_n_version > len(old_version_infos):
        create_patch_for_latest_n_version = len(old_version_infos)

    old_version_infos = sorted(
        old_version_infos)[-create_patch_for_latest_n_version:]

    # 确认最终文件名
    patch_oldest_version = old_version_infos[0].version
    patch_newest_version = old_version_infos[-1].version
    patches_dir = f"DNF蚊子腿小助手_增量更新文件_v{patch_oldest_version}_to_v{patch_newest_version}"
    temp_dir = "patches_temp"

    patch_7z_file = f"{patches_dir}.7z"
    if get_final_patch_path_only:
        return patch_7z_file

    logger.info(f"需要制作补丁包的版本为{old_version_infos}")

    # 确保版本都在本地
    logger.info(f"确保以上版本均已下载并解压到本地~")
    for info in old_version_infos:
        local_folder_path = os.path.join(dir_all_release,
                                         f"DNF蚊子腿小助手_v{info.version}_by风之凌殇")
        local_7z_path = local_folder_path + ".7z"

        if os.path.isdir(local_folder_path):
            # 本地已存在对应版本,跳过
            continue

        logger.info(f"本地发布目录不存在 {local_folder_path}")
        if not os.path.isfile(local_7z_path):
            logger.info(f"本地不存在{info.fileinfo.name}的7z文件,将从网盘下载")
            uploader.download_file(info.fileinfo, dir_all_release)

        logger.info(f"尝试解压 {info.fileinfo.name} 到 {local_folder_path}")
        decompress_dir_with_bandizip(local_7z_path, dir_src)

    # --------------------------- 实际只做补丁包 ---------------------------
    logger.info(color("bold_yellow") + f"将为【{old_version_infos}】版本制作补丁包")

    shutil.rmtree(patches_dir, ignore_errors=True)
    os.mkdir(patches_dir)
    shutil.rmtree(temp_dir, ignore_errors=True)
    os.mkdir(temp_dir)

    def temp_path(dir_name):
        return os.path.realpath(os.path.join(temp_dir, dir_name))

    def preprocess_before_patch(temp_version_path):
        for filename in ["config.toml", "utils/auto_updater.exe"]:
            filepath = os.path.join(temp_version_path, filename)
            if os.path.isfile(filepath):
                os.remove(filepath)

    # 为旧版本创建patch文件
    target_version_dir = f"DNF蚊子腿小助手_v{latest_version}_by风之凌殇"
    logger.info(f"目标版本目录为{target_version_dir}")
    shutil.copytree(target_version_dir, temp_path(target_version_dir))
    preprocess_before_patch(temp_path(target_version_dir))

    for idx, version_info in enumerate(old_version_infos):
        version = version_info.version
        patch_file = f"{patches_dir}/{version}.patch"

        logger.info("-" * 80)
        logger.info(
            color("bold_yellow") +
            f"[{idx + 1}/{len(old_version_infos)}] 创建从v{version}升级到v{latest_version}的补丁{patch_file}"
        )

        version_dir = f"DNF蚊子腿小助手_v{version}_by风之凌殇"

        shutil.copytree(version_dir, temp_path(version_dir))
        preprocess_before_patch(temp_path(version_dir))

        subprocess.call([
            os.path.realpath(os.path.join(dir_src, "utils/hdiffz.exe")),
            f"-p-{multiprocessing.cpu_count()}",  # 设置系统最大cpu数
            os.path.realpath(os.path.join(temp_dir, version_dir)),
            os.path.realpath(os.path.join(temp_dir, target_version_dir)),
            patch_file,
        ])

        filesize = os.path.getsize(patch_file)
        logger.info(f"创建补丁{patch_file}结束,最终大小为{human_readable_size(filesize)}")

    # 移除临时目录
    shutil.rmtree(temp_dir, ignore_errors=True)

    # 压缩打包
    compress_dir_with_bandizip(patches_dir, patch_7z_file, dir_src)

    # 额外备份一份最新的供github action 使用
    shutil.copyfile(
        patch_7z_file,
        os.path.join(dir_github_action_artifact, 'djc_helper_patches.7z'))

    os.chdir(old_cwd)

    return patch_7z_file
示例#20
0
def release():
    # ---------------准备工作
    prompt = f"如需直接使用默认版本号:{now_version} 请直接按回车\n或手动输入版本号后按回车:"
    version = input(prompt) or now_version

    version_reg = r"\d+\.\d+\.\d+"

    if re.match(version_reg, version) is None:
        logger.info(f"版本号格式有误,正确的格式类似:1.0.0 ,而不是 {version}")
        pause_and_exit(-1)

    # 最大化窗口
    change_console_window_mode_async(disable_min_console=True)

    version = "v" + version

    run_start_time = datetime.now()
    show_head_line(f"开始发布版本 {version}", color("bold_yellow"))

    set_title_cmd = f"title 发布 {version}"
    os.system(set_title_cmd)

    # 先声明一些需要用到的目录的地址
    dir_src = os.path.realpath(".")
    dir_all_release = os.path.realpath(os.path.join("releases"))
    release_dir_name = f"DNF蚊子腿小助手_{version}_by风之凌殇"
    release_7z_name = f"{release_dir_name}.7z"
    dir_github_action_artifact = "_github_action_artifact"

    # ---------------构建
    # 调用构建脚本
    os.chdir(dir_src)
    build()

    # ---------------清除一些历史数据
    make_sure_dir_exists(dir_all_release)
    os.chdir(dir_all_release)
    clear_github_artifact(dir_all_release, dir_github_action_artifact)

    # ---------------打包
    os.chdir(dir_src)
    package(dir_src, dir_all_release, release_dir_name, release_7z_name, dir_github_action_artifact)

    # ---------------构建增量补丁
    create_patch_for_latest_n_version = 3

    # ---------------构建增量包
    os.chdir(dir_all_release)
    show_head_line(f"开始构建增量包,最多包含过去{create_patch_for_latest_n_version}个版本到最新版本的补丁", color("bold_yellow"))
    create_patch(dir_src, dir_all_release, create_patch_for_latest_n_version, dir_github_action_artifact)

    # ---------------获取补丁地址(分开方便调试)
    os.chdir(dir_all_release)
    patch_file_name = create_patch(
        dir_src,
        dir_all_release,
        create_patch_for_latest_n_version,
        dir_github_action_artifact,
        get_final_patch_path_only=True,
    )

    # ---------------标记新版本
    show_head_line("提交版本和版本变更说明,并同步到docs目录,用于生成github pages", color("bold_yellow"))
    os.chdir(dir_src)
    commit_new_version()

    # ---------------上传到蓝奏云
    show_head_line("开始上传到蓝奏云", color("bold_yellow"))
    os.chdir(dir_src)
    with open("upload_cookie.json") as fp:
        cookie = json.load(fp)
    os.chdir(dir_all_release)
    uploader = Uploader()
    uploader.login(cookie)
    if uploader.login_ok:
        logger.info("蓝奏云登录成功,开始上传压缩包")

        def path_in_src(filepath_relative_to_src: str) -> str:
            return os.path.realpath(os.path.join(dir_src, filepath_relative_to_src))

        realpath = os.path.realpath

        upload_info_list = [
            (
                uploader.folder_djc_helper,
                [
                    (realpath(release_7z_name), uploader.history_version_prefix),
                    (path_in_src("utils/auto_updater.exe"), ""),
                    (path_in_src("使用教程/使用文档.docx"), ""),
                    (path_in_src("使用教程/视频教程.txt"), ""),
                    (path_in_src("付费指引/付费指引.docx"), ""),
                    (path_in_src("utils/不要下载增量更新文件_这个是给自动更新工具使用的.txt"), ""),
                    (realpath(patch_file_name), uploader.history_patches_prefix),
                ],
            ),
            (
                uploader.folder_dnf_calc,
                [
                    (realpath(release_7z_name), uploader.history_version_prefix),
                ],
            ),
        ]

        logger.info(color("bold_green") + "具体上传列表如下:")
        for upload_folder, upload_list in upload_info_list:
            logger.info(color("bold_cyan") + f"\t{upload_folder.name}:")
            for local_filepath, _history_file_prefix in upload_list:
                logger.info(f"\t\t{local_filepath}")

            logger.info("\n")

        for upload_folder, upload_list in upload_info_list:
            for local_filepath, history_file_prefix in reversed(upload_list):
                # 逆序遍历,确保同一个网盘目录中,列在前面的最后才上传,从而在网盘显示时显示在最前方
                total_try_count = 1
                for try_index in range_from_one(total_try_count):
                    upload_ok = uploader.upload_to_lanzouyun(
                        local_filepath, upload_folder, history_file_prefix=history_file_prefix
                    )
                    if upload_ok:
                        break

                    logger.warning(f"第{try_index}/{total_try_count}次尝试上传{local_filepath}失败,等待一会后重试")
                    if try_index < total_try_count:
                        count_down("上传到网盘", 5 * try_index)

    else:
        logger.error("蓝奏云登录失败")

    # ---------------推送版本到github
    # 打包完成后git添加标签
    os.chdir(dir_src)
    show_head_line("开始推送到github", color("bold_yellow"))
    push_github(version)

    # ---------------结束
    logger.info("+" * 40)
    logger.info(color("bold_yellow") + f"{version} 发布完成,共用时{datetime.now() - run_start_time},请检查上传至蓝奏云流程是否OK")
    logger.info("+" * 40)

    os.system("PAUSE")
示例#21
0
patch_file_name = create_patch(dir_src, dir_all_release,
                               create_patch_for_latest_n_version,
                               dir_github_action_artifact)

# ---------------标记新版本
logger.info("提交版本和版本变更说明,并同步到docs目录,用于生成github pages")
os.chdir(dir_src)
commit_new_version()

# ---------------上传到蓝奏云
logger.info("开始上传到蓝奏云")
os.chdir(dir_src)
with open("upload_cookie.json") as fp:
    cookie = json.load(fp)
os.chdir(dir_all_release)
uploader = Uploader(cookie)
if uploader.login_ok:
    logger.info("蓝奏云登录成功,开始上传压缩包")
    uploader.upload_to_lanzouyun(
        patch_file_name,
        uploader.folder_djc_helper,
        history_file_prefix=uploader.history_patches_prefix)
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_djc_helper)
    uploader.upload_to_lanzouyun(release_7z_name, uploader.folder_dnf_calc)
    uploader.upload_to_lanzouyun(
        os.path.realpath(
            os.path.join(dir_src, "utils/buy_auto_updater_users.txt")),
        uploader.folder_online_files, uploader.buy_auto_updater_users_filename)
    uploader.upload_to_lanzouyun(
        os.path.realpath(
            os.path.join(dir_src, "utils/user_monthly_pay_info.txt")),