n/chit-chatu/cpp · 3 个月前
注册 登录
n/chit-chat · 3 个月前 · 已编辑 · 231 次浏览
u/cpp黄金

IPFS to OpenList

IPFS to OpenList

在线工具将 IPFS 转成 OpenList 网页版。

工具链接 ->(https://4567.link2.dns.army/)

Faq

Q: 这和 OpenList 有什么区别

这个是静态网页无需服务器,OpenList 需要服务器才能运行,OpenList 路径为 /aaa/bbb,这个等价路径为 ?path=/aaa/bbb

Q: 报 530 错误

具体原因不清楚,大概超过 2 个人同时使用就会报,现在应该不会报了

Q: 无法生成某些 CID

需要通过其他 IPFS 网关预热一下

Q: 生成后的网页打不开

多刷新一下,或者试一试英文界面的->(https://3456.link2.dns.army/)

注:如果在线工具不能生成 ,楼层回复或者到 ipfs2.discourse.group 回复 CID 帮助生成。
只要是热门 CID 还是可以生成的,一万以上的文件需要等一下。
如果自建网关,直接用自建网关会更快。
工具中的 cid.py
import sys, os, re, json, ctypes, requests, hashlib
from functools import cmp_to_key
from urllib.parse import quote
from pathlib import Path

# ========= 排序逻辑 =========
if os.name == "nt":
    _strcmp = ctypes.windll.shlwapi.StrCmpLogicalW
    _strcmp.argtypes, _strcmp.restype = [ctypes.c_wchar_p, ctypes.c_wchar_p], ctypes.c_int
    def _cmp_name(a, b):
        return _strcmp(str(a), str(b))
else:
    def _alphanum_key(s):
        return [int(x) if x.isdigit() else x.lower() for x in re.split(r'(\d+)', s)]
    def _cmp_name(a, b):
        ka, kb = _alphanum_key(a), _alphanum_key(b)
        return (ka > kb) - (ka < kb)

# ========= IPFS API =========
API = "http://127.0.0.1:5001/api/v0"
session = requests.Session()

def ipfs(endpoint, arg):
    r = session.post(f"{API}/{endpoint}?arg={quote(arg)}")
    r.raise_for_status()
    return r.json()

def check_cid(cid):
    try:
        res = ipfs("cid/format", cid)
        return not res.get("ErrorMsg", ""), res
    except Exception as e:
        return False, str(e)

# ========= 树构建 =========
def fetch_tree(cid, path="/", name=""):
    print(path)
    links = ipfs("ls", f"{cid}{path if path != '/' else ''}").get("Objects", [{}])[0].get("Links", [])
    children = []
    for e in links:
        if e["Type"] == 1:  # 文件夹
            children.append(fetch_tree(cid, f"{path.rstrip('/')}/{e['Name']}", e["Name"]))
        else:
            children.append([e["Name"], int(e["Size"])])
    # 目录优先 + 自然排序
    children.sort(key=cmp_to_key(lambda a, b:
        -1 if isinstance(a[-1], list) and not isinstance(b[-1], list)
        else 1 if not isinstance(a[-1], list) and isinstance(b[-1], list)
        else _cmp_name(a[0], b[0])
    ))
    return [name, children]


# ========= 压缩导出 =========
def export_zstd(tree, output_path):
    """将数据导出为 Zstandard 压缩的 JSON(.json.zst),返回 (压缩文件路径, json_bytes)。"""
    try:
        import zstandard as zstd
    except ImportError:
        print("错误:未检测到 zstandard 模块,请先安装: pip install zstandard")
        sys.exit(1)

    json_bytes = json.dumps(tree, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    size_mb = len(json_bytes) / (1024 ** 2)
    level = 22 if size_mb < 32 else 19

    compressed = zstd.ZstdCompressor(level=level).compress(json_bytes)
    output_path = output_path.with_suffix(output_path.suffix + ".zst")
    output_path.write_bytes(compressed)

    print(f"✅ 数据已压缩导出到 {output_path} (压缩等级 {level},原始大小 {size_mb:.2f} MiB)")
    return json_bytes


# ========= hash 更新 =========
def update_hash_in_index(js_path: Path, json_bytes: bytes):
    """计算 JSON 数据 hash,并修改 index.js 中的 __HASH__ = ..."""
    if not js_path.exists():
        print(f"错误:文件 {js_path} 不存在,无法写入哈希")
        sys.exit(1)

    hash_value = hashlib.sha256(json_bytes).hexdigest()
    text = js_path.read_text(encoding="utf-8")
    new_text, count = re.subn(
        r"(t=)['\"]?[0-9a-fA-F]*['\"]?",
        rf'\1"{hash_value}"',
        text,
        count=1,
    )
    if count == 0:
        print(f"警告:未在 {js_path} 中找到 __HASH__ = ... 替换点")
    else:
        js_path.write_text(new_text, encoding="utf-8")
        print(f"✅ 已更新 {js_path} 中的哈希值为:{hash_value[:12]}...")


# ========= 主函数 =========
def main():
    if len(sys.argv) < 2:
        print("用法: python cid.py <CID>")
        sys.exit(1)

    cid = sys.argv[1]
    ok, info = check_cid(cid)
    if not ok:
        print(f"❌ CID 无效: {info}")
        sys.exit(1)

    print("✅ CID 格式有效,开始获取树")
    tree = fetch_tree(cid)
    tree[0] = ""

    Path("static").mkdir(exist_ok=True)
    output_path = Path("static/data.json")

    json_bytes = export_zstd(tree, output_path)

    # 更新 hash 至 index.js
    js_path = Path("static/index.js")
    update_hash_in_index(js_path, json_bytes)


if __name__ == "__main__":
    main()
工具中的 data.py
import os, re, json, ctypes, sys, hashlib
from pathlib import Path
from functools import cmp_to_key

# ========= 排序逻辑 =========

if os.name == "nt":
    _strcmp = ctypes.windll.shlwapi.StrCmpLogicalW
    _strcmp.argtypes, _strcmp.restype = [ctypes.c_wchar_p, ctypes.c_wchar_p], ctypes.c_int
    def _cmp_name(a, b):
        return _strcmp(str(a), str(b))
else:
    def _alphanum_key(s):
        return [int(x) if x.isdigit() else x.lower() for x in re.split(r'(\d+)', s)]
    def _cmp_name(a, b):
        ka, kb = _alphanum_key(a), _alphanum_key(b)
        return (ka > kb) - (ka < kb)

# ========= 树构建 =========

def safe_stat(path):
    try:
        return os.stat(path, follow_symlinks=False)
    except Exception:
        return None


def scan_tree(path):
    """扫描目录并返回 [name, size或children, mtime]"""
    if os.path.islink(path):
        return None

    st = safe_stat(path)
    if not st:
        return None

    name = Path(path).name
    if os.path.isdir(path):
        try:
            entries = os.listdir(path)
        except OSError:
            return [name, [], int(st.st_mtime)]

        def cmp_entry(a, b):
            a_path, b_path = os.path.join(path, a), os.path.join(path, b)
            a_isdir, b_isdir = os.path.isdir(a_path), os.path.isdir(b_path)
            if a_isdir and not b_isdir:
                return -1
            elif b_isdir and not a_isdir:
                return 1
            return _cmp_name(a, b)

        children = filter(None, (
            scan_tree(os.path.join(path, e))
            for e in sorted(entries, key=cmp_to_key(cmp_entry))
        ))
        return [name, list(children), int(st.st_mtime)]
    else:
        return [name, st.st_size, int(st.st_mtime)]


# ========= 导出与压缩 =========

def export_data(tree, output_path):
    """
    将数据导出为 Zstandard 压缩的 JSON(.json.zst)
    返回:(压缩文件路径, 原始 JSON 字节)
    """
    try:
        import zstandard as zstd
    except ImportError:
        print("错误:未检测到 zstandard 模块,请先安装: pip install zstandard")
        sys.exit(1)

    json_bytes = json.dumps(tree, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    size_mb = len(json_bytes) / (1024 ** 2)

    level = 22 if size_mb < 32 else 19
    cctx = zstd.ZstdCompressor(level=level)
    compressed = cctx.compress(json_bytes)

    output_path = output_path.with_suffix(output_path.suffix + ".zst")
    with open(output_path, "wb") as f:
        f.write(compressed)

    print(f"数据已压缩导出到 {output_path} (压缩等级 {level},原始大小 {size_mb:.2f} MiB)")
    return json_bytes


# ========= hash 更新 =========

def update_hash_in_index(js_path: Path, json_bytes: bytes):
    """计算 JSON 数据 hash,并修改 index.js 中的 __HASH__ = ..."""
    if not js_path.exists():
        print(f"错误:文件 {js_path} 不存在,无法写入哈希")
        sys.exit(1)

    hash_value = hashlib.sha256(json_bytes).hexdigest()

    text = js_path.read_text(encoding="utf-8")
    new_text, count = re.subn(
        r"(t=)['\"]?[0-9a-fA-F]*['\"]?",
        rf'\1"{hash_value}"',
        text,
        count=1,
    )
    if count == 0:
        print(f"警告:未在 {js_path} 中找到 __HASH__ = ... 替换点")
    else:
        js_path.write_text(new_text, encoding="utf-8")
        print(f"已更新 {js_path} 中的哈希值为:{hash_value[:12]}...")


# ========= 主函数 =========

def main():
    root = "d"
    if not os.path.exists(root):
        print(f"错误:目录 '{root}' 不存在")
        return

    print("正在扫描目录,请稍候...")
    tree = scan_tree(root)
    if tree:
        tree[0] = ""  # 根名置空

    Path("static").mkdir(exist_ok=True)
    output_path = Path("static/data.json")

    json_bytes = export_data(tree, output_path)

    js_path = Path("static/index.js")
    update_hash_in_index(js_path, json_bytes)


if __name__ == "__main__":
    main()
2
5
登录后参与讨论。
u/deleted 广告
海外原生IP VPS,稳定访问全球网络

还在为IP不纯、平台风控、频繁验证而烦恼? 丽萨主机海外原生IP VPS,双ISP住宅IP,覆盖美国、香港、日本、新加坡、台湾、德国、越南、英国等热门地区,适合跨境电商、社媒运营、AI工具、流媒体及海外业务使用。

lisahost.com 了解更多

5 条回复

排序
  1. Furry 钻石 文圣 3 个月前

    传说中的ipfs吗
    有点意思

    0
  2. yhm 白银 3 个月前

    写得很清楚,受益了。

    0
  3. cpp 黄金 楼主 3 个月前

    工具.zip (3.8 KB)
    如果需要记录时间,data.py 可以生成时间
    整体只改动两个文件
    static/index.js
    static/data.json.zst

    0
  4. lezi-fun 钻石 水王 3 个月前

    没用过,但相信有用

    0
  5. wentao918168 黄金 3 YEARS 3 个月前

    第一次知道这个,纯小白

    0