#!/usr/bin/env python3
import json, io, os, urllib.request, urllib.parse
from PIL import Image
import pillow_heif
pillow_heif.register_heif_opener()

tok = None
for line in open("/root/site/yandex/.env_hram", encoding="utf-8"):
    if line.startswith("YANDEX2_ACCESS_TOKEN="):
        tok = line.split("=", 1)[1].strip()
H = {"Authorization": f"OAuth {tok}"}

def get_download_url(path):
    url = "https://cloud-api.yandex.net/v1/disk/resources/download?path=" + urllib.parse.quote(path)
    req = urllib.request.Request(url, headers=H)
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())["href"]

cache = json.load(open("/root/site/video/gps_cache2.json", encoding="utf-8"))
samples = [
    ("/Фото/Фотокамера/2015-06-23 19-23-09.JPG", "C3_pavshino.jpg"),
    ("/Фото/Фотокамера/2015-06-29 10-39-20.JPG", "C4_sergiev.jpg"),
]
for path, outname in samples:
    try:
        href = get_download_url(path)
        data = urllib.request.urlopen(urllib.request.Request(href), timeout=180).read()
        im = Image.open(io.BytesIO(data)).convert("RGB")
        im.thumbnail((900, 900), Image.LANCZOS)
        im.save(f"/root/site/video/cluster_previews/{outname}", quality=88)
        print("OK", outname, len(data))
    except Exception as e:
        print(outname, "ERR", e)
