# -*- coding: utf-8 -*-
"""并行下载全部作品视频（断点续传，多线程）
用法: python download_parallel.py [并发数]
"""
import json, os, sys, time, threading, queue, requests

ROOT = r"D:\Deepseek\douyin_fengdaquan"
OUT = os.path.join(ROOT, "videos_all")
os.makedirs(OUT, exist_ok=True)
LIST = os.path.join(ROOT, "_works_final.json")

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36")
HEAD = {"User-Agent": UA, "Referer": "https://www.douyin.com/", "Accept": "*/*"}

rows = [r for r in json.load(open(LIST, encoding="utf-8")) if not r.get("is_image") and r.get("play")]
lock = threading.Lock()
done = {"ok": 0, "skip": 0, "fail": 0, "bytes": 0}


def target(r):
    return os.path.join(OUT, f"{r['created']}_{r['id']}.mp4")


def fetch(r, tries=3):
    fp = target(r)
    for attempt in range(1, tries + 1):
        have = os.path.getsize(fp) if os.path.exists(fp) else 0
        h = dict(HEAD)
        if have:
            h["Range"] = "bytes=%d-" % have
        try:
            with requests.get(r["play"], headers=h, stream=True, timeout=60) as resp:
                if have and resp.status_code == 200:
                    have, mode = 0, "wb"
                elif resp.status_code in (200, 206):
                    mode = "ab" if have else "wb"
                else:
                    raise RuntimeError("HTTP %d" % resp.status_code)
                total = int(resp.headers.get("Content-Length") or 0) + have
                with open(fp, mode) as f:
                    for chunk in resp.iter_content(1 << 16):
                        f.write(chunk)
            size = os.path.getsize(fp)
            if total and size < total:
                raise RuntimeError("incomplete %d/%d" % (size, total))
            return size
        except Exception as e:
            if attempt == tries:
                print("  FAIL %s: %s" % (r["id"], e), flush=True)
                return -1
            time.sleep(2 * attempt)
    return -1


def worker(q):
    while True:
        try:
            r = q.get_nowait()
        except queue.Empty:
            return
        fp = target(r)
        if os.path.exists(fp) and os.path.getsize(fp) > 100_000:
            with lock:
                done["skip"] += 1; done["bytes"] += os.path.getsize(fp)
            q.task_done(); continue
        sz = fetch(r)
        with lock:
            if sz > 0:
                done["ok"] += 1; done["bytes"] += sz
            else:
                done["fail"] += 1
            n = done["ok"] + done["skip"] + done["fail"]
            if n % 10 == 0:
                print("进度 %d/%d  已下 %.2f GB  失败 %d" % (n, len(rows), done["bytes"] / 1e9, done["fail"]), flush=True)
        q.task_done()


def main():
    conc = int(sys.argv[1]) if len(sys.argv) > 1 else 6
    print("待下载 %d 个视频, 并发 %d" % (len(rows), conc), flush=True)
    q = queue.Queue()
    for r in rows:
        q.put(r)
    t0 = time.time()
    ts = [threading.Thread(target=worker, args=(q,), daemon=True) for _ in range(conc)]
    for t in ts: t.start()
    for t in ts: t.join()
    print("完成: 新下 %d, 跳过 %d, 失败 %d, 共 %.2f GB, 耗时 %.0fs"
          % (done["ok"], done["skip"], done["fail"], done["bytes"] / 1e9, time.time() - t0), flush=True)


if __name__ == "__main__":
    main()
