#!/usr/bin/env python3
import json, urllib.request, urllib.parse, os, sys

token = None
for line in open("/root/site/yandex/.env", encoding="utf-8"):
    line = line.strip()
    if line.startswith("YANDEX_ACCESS_TOKEN="):
        token = line.split("=", 1)[1].strip()

def api(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, headers={"Authorization": f"OAuth {token}"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode())

BASE = "/Добротный дом рендеры/Добротный 1.0 Троицкий"
os.makedirs("/root/site/video/renders", exist_ok=True)

d = api(BASE)
for i in d.get("_embedded", {}).get("items", []):
    if i["type"] != "file":
        continue
    name = i["name"]
    href = i.get("file")
    if not href:
        print("no href for", name); continue
    dest = f"/root/site/video/renders/{name}"
    if os.path.exists(dest) and os.path.getsize(dest) == i.get("size"):
        print("already:", name); continue
    req = urllib.request.Request(href, headers={"Authorization": f"OAuth {token}"})
    with urllib.request.urlopen(req, timeout=120) as r:
        data = r.read()
    open(dest, "wb").write(data)
    print(f"downloaded {name}: {len(data)} bytes")

print("DONE")
