分享一个从云端下载快照到本地的脚本

一个手贱,把我本地的快照全给清空了。

image.png

想了想感觉还是需要下载回来一部分,不然还是有些风险。

但是一个个翻页点击,体感还是太恐怖了。

image.png

看了一下,发现有提供快照相关的 API,所以写了一个脚本批量处理,以下的代码依赖于 RunJs 插件,请放到代码块里面,然后使用插件运行。

"use strict";
const request = globalThis.runJs.api.request;
class SnapshotScheduler {
    constructor() {
        this.now = new Date();
    }
    isInCurrentWeek(date) {
        const startOfWeek = new Date(this.now);
        startOfWeek.setDate(this.now.getDate() - this.now.getDay());
        return date >= startOfWeek;
    }
    getTimeDifferenceInDays(date) {
        return Math.floor((this.now.getTime() - date.getTime()) / (1000 * 3600 * 24));
    }
    isSameDay(date1, date2) {
        return date1.getFullYear() === date2.getFullYear() &&
            date1.getMonth() === date2.getMonth() &&
            date1.getDate() === date2.getDate();
    }
    isHourDifferent(date1, date2) {
        return date1.getHours() !== date2.getHours();
    }
    shouldDownloadSnapshot(last, current, next) {
        const currentDate = new Date(current.created);
        const daysDifference = this.getTimeDifferenceInDays(currentDate);
        if (this.isInCurrentWeek(currentDate)) {
            return true; // Download all snapshots from the current week
        }
        const lastDate = last ? new Date(last.created) : null;
        const nextDate = next ? new Date(next.created) : null;
        if (daysDifference <= 30) {
            // Every hour, plus start and end of day
            if (!lastDate || !this.isSameDay(currentDate, lastDate)) {
                return true; // First snapshot of the day
            }
            if (!nextDate || !this.isSameDay(currentDate, nextDate)) {
                return true; // Last snapshot of the day
            }
            return this.isHourDifferent(currentDate, lastDate);
        }
        if (daysDifference <= 90) {
            // First and last snapshot of each day
            return (!lastDate || !this.isSameDay(currentDate, lastDate)) ||
                (!nextDate || !this.isSameDay(currentDate, nextDate));
        }
        if (daysDifference <= 180) {
            // Last snapshot of each day
            return !nextDate || !this.isSameDay(currentDate, nextDate);
        }
        if (daysDifference <= 365) {
            // Every third day, last snapshot
            if (daysDifference % 3 !== 0)
                return false;
            return !nextDate || !this.isSameDay(currentDate, nextDate);
        }
        // Over a year: weekly, last snapshot
        const weekNumber = Math.floor(daysDifference / 7);
        if (daysDifference % 7 !== 0)
            return false;
        return !nextDate || Math.floor(this.getTimeDifferenceInDays(nextDate) / 7) !== weekNumber;
    }
}
class SnapshotManager {
    constructor() {
        this.scheduler = new SnapshotScheduler();
    }
    async getAllSnapshots(startFrom, endTo, startPage) {
        let page = startPage !== null && startPage !== void 0 ? startPage : 0;
        let allSnapshots = [];
        let continueFetching = true;
        while (continueFetching) {
            const snaps = await this.getCloudRepoSnapshots(page);
            const filteredSnapshots = snaps.snapshots.filter(snapshot => {
                const snapshotDate = new Date(snapshot.created);
                return snapshotDate <= startFrom && snapshotDate >= endTo;
            });
            console.debug(`Fetched page ${page + 1}, total snapshots: ${filteredSnapshots.length}: ${snaps.snapshots[0].hCreated} ~ ${snaps.snapshots[snaps.snapshots.length - 1].hCreated}`);
            allSnapshots = allSnapshots.concat(filteredSnapshots);
            page++;
            if (page >= snaps.pageCount || new Date(snaps.snapshots[snaps.snapshots.length - 1].created) < endTo) {
                continueFetching = false;
            }
        }
        return allSnapshots.sort((a, b) => b.created - a.created); // Sort descending
    }
    async downloadSnapshots(startFrom, cutoff, startPage) {
        console.log("Fetching all snapshots...");
        const allSnapshots = await this.getAllSnapshots(startFrom, cutoff, startPage);
        console.log(`Total snapshots fetched: ${allSnapshots.length}`);
        let totalDownloaded = 0;
        for (let i = 0; i < allSnapshots.length; i++) {
            const currentSnapshot = allSnapshots[i];
            const lastSnapshot = i > 0 ? allSnapshots[i - 1] : null;
            const nextSnapshot = i < allSnapshots.length - 1 ? allSnapshots[i + 1] : null;
            if (this.scheduler.shouldDownloadSnapshot(lastSnapshot, currentSnapshot, nextSnapshot)) {
                await this.downloadSnapshot(currentSnapshot);
                totalDownloaded++;
            }
        }
        return totalDownloaded;
    }
    async getCloudRepoSnapshots(page) {
        const response = await request('/api/repo/getCloudRepoSnapshots', {
            page: page
        });
        return response;
    }
    async downloadSnapshot(snapshot) {
        const snapshotId = snapshot.id;
        console.debug(`[${snapshot.hCreated}] Downloaded snapshot ${snapshotId}`);
        await request('/api/repo/downloadCloudSnapshot', {
            id: snapshotId,
            tag: ''
        });
    }
}
async function runMainWithTiming(startFrom, endTo, startPage) {
    console.log("Starting snapshot download process...");
    console.log(`Start date: ${startFrom.toISOString()}`);
    console.log(`Cutoff date: ${endTo.toISOString()}`);
    const startTime = Date.now();
    const snapshotManager = new SnapshotManager();
    const totalDownloaded = await snapshotManager.downloadSnapshots(startFrom, endTo, startPage);
    const endTime = Date.now();
    const executionTime = (endTime - startTime) / 1000; // Convert to seconds
    console.log(`Download process completed.`);
    console.log(`Total snapshots downloaded: ${totalDownloaded}`);
    console.log(`Total execution time: ${executionTime.toFixed(2)} seconds`);
}
let startFrom = new Date('2024-09-01');
let endTo = new Date('2023-12-01');
runMainWithTiming(startFrom, endTo, 74);

下载快照的时候,遵循以下策略:

  • 对于当前周的快照,全部下载
  • 对于最近一个月内的快照,确保每小时至少下载一个,并且总是下载每天的第一个和最后一个快照
  • 对于 1-3 个月内的快照,只保留每天的第一个和最后一个快照
  • 对于 3-6 个月内的快照,只保留每天的最后一个快照
  • 对于 6 个月到 1 年内的快照,每三天保留最后一个快照。
  • 对于超过 1 年的快照,每周保留最后一个快照

运行时间还是相当长的,我大概跑了半个小时的样子,主要问题在于为了谨慎期间没有做并行处理,而是在 for loop 里面一个个 await Promise。

最后效果如下,原本 387 页,下载之后保留了 22 页。临近的一段时间,快照保存的都比较密集;而更为久远的时间段,快照的保存就稀疏一些。

image.png

image.png

  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    21193 引用 • 83520 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • Gitea

    Gitea 是一个开源社区驱动的轻量级代码托管解决方案,后端采用 Go 编写,采用 MIT 许可证。

    4 引用 • 16 回帖
  • MyBatis

    MyBatis 本是 Apache 软件基金会 的一个开源项目 iBatis,2010 年这个项目由 Apache 软件基金会迁移到了 google code,并且改名为 MyBatis ,2013 年 11 月再次迁移到了 GitHub。

    170 引用 • 414 回帖 • 389 关注
  • Q&A

    提问之前请先看《提问的智慧》,好的问题比好的答案更有价值。

    7543 引用 • 34344 回帖 • 197 关注
  • V2Ray
    1 引用 • 15 回帖 • 1 关注
  • 书籍

    宋真宗赵恒曾经说过:“书中自有黄金屋,书中自有颜如玉。”

    77 引用 • 390 回帖 • 1 关注
  • RESTful

    一种软件架构设计风格而不是标准,提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    30 引用 • 114 回帖
  • MySQL

    MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司。MySQL 是最流行的关系型数据库管理系统之一。

    676 引用 • 535 回帖
  • Logseq

    Logseq 是一个隐私优先、开源的知识库工具。

    Logseq is a joyful, open-source outliner that works on top of local plain-text Markdown and Org-mode files. Use it to write, organize and share your thoughts, keep your to-do list, and build your own digital garden.

    5 引用 • 62 回帖 • 4 关注
  • 互联网

    互联网(Internet),又称网际网络,或音译因特网、英特网。互联网始于 1969 年美国的阿帕网,是网络与网络之间所串连成的庞大网络,这些网络以一组通用的协议相连,形成逻辑上的单一巨大国际网络。

    98 引用 • 344 回帖 • 1 关注
  • JSON

    JSON (JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写。同时也易于机器解析和生成。

    52 引用 • 190 回帖 • 1 关注
  • Dubbo

    Dubbo 是一个分布式服务框架,致力于提供高性能和透明化的 RPC 远程服务调用方案,是 [阿里巴巴] SOA 服务化治理方案的核心框架,每天为 2,000+ 个服务提供 3,000,000,000+ 次访问量支持,并被广泛应用于阿里巴巴集团的各成员站点。

    60 引用 • 82 回帖 • 604 关注
  • Mac

    Mac 是苹果公司自 1984 年起以“Macintosh”开始开发的个人消费型计算机,如:iMac、Mac mini、Macbook Air、Macbook Pro、Macbook、Mac Pro 等计算机。

    165 引用 • 594 回帖 • 1 关注
  • Ruby

    Ruby 是一种开源的面向对象程序设计的服务器端脚本语言,在 20 世纪 90 年代中期由日本的松本行弘(まつもとゆきひろ/Yukihiro Matsumoto)设计并开发。在 Ruby 社区,松本也被称为马茨(Matz)。

    7 引用 • 31 回帖 • 200 关注
  • Hadoop

    Hadoop 是由 Apache 基金会所开发的一个分布式系统基础架构。用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。

    86 引用 • 122 回帖 • 628 关注
  • RYMCU

    RYMCU 致力于打造一个即严谨又活泼、专业又不失有趣,为数百万人服务的开源嵌入式知识学习交流平台。

    4 引用 • 6 回帖 • 50 关注
  • 倾城之链
    23 引用 • 66 回帖 • 132 关注
  • 阿里云

    阿里云是阿里巴巴集团旗下公司,是全球领先的云计算及人工智能科技公司。提供云服务器、云数据库、云安全等云计算服务,以及大数据、人工智能服务、精准定制基于场景的行业解决方案。

    89 引用 • 345 回帖
  • CongSec

    本标签主要用于分享网络空间安全专业的学习笔记

    6 引用 • 1 回帖
  • PWA

    PWA(Progressive Web App)是 Google 在 2015 年提出、2016 年 6 月开始推广的项目。它结合了一系列现代 Web 技术,在网页应用中实现和原生应用相近的用户体验。

    14 引用 • 69 回帖 • 137 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    167 引用 • 1493 回帖 • 1 关注
  • Love2D

    Love2D 是一个开源的, 跨平台的 2D 游戏引擎。使用纯 Lua 脚本来进行游戏开发。目前支持的平台有 Windows, Mac OS X, Linux, Android 和 iOS。

    14 引用 • 53 回帖 • 533 关注
  • 导航

    各种网址链接、内容导航。

    38 引用 • 169 回帖
  • 创造

    你创造的作品可能会帮助到很多人,如果是开源项目的话就更赞了!

    175 引用 • 994 回帖
  • Docker

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的操作系统上。容器完全使用沙箱机制,几乎没有性能开销,可以很容易地在机器和数据中心中运行。

    490 引用 • 914 回帖
  • QQ

    1999 年 2 月腾讯正式推出“腾讯 QQ”,在线用户由 1999 年的 2 人(马化腾和张志东)到现在已经发展到上亿用户了,在线人数超过一亿,是目前使用最广泛的聊天软件之一。

    45 引用 • 557 回帖 • 122 关注
  • Scala

    Scala 是一门多范式的编程语言,集成面向对象编程和函数式编程的各种特性。

    13 引用 • 11 回帖 • 117 关注
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖 • 3 关注