From ed06c9736d4085d8c024686a563c5cdb878ee037 Mon Sep 17 00:00:00 2001 From: odrling Date: Thu, 6 Oct 2022 07:31:38 +0200 Subject: [PATCH] check file with upload/hash endpoint --- hikari/hikari.py | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/hikari/hikari.py b/hikari/hikari.py index 007f5af..42706ba 100755 --- a/hikari/hikari.py +++ b/hikari/hikari.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import hashlib from pathlib import Path +from pprint import pprint import orjson import pyperclip @@ -12,6 +13,34 @@ HIKARI_BASE = "https://hikari.butaishoujo.moe" HIKARI_URL = f"{HIKARI_BASE}/upload" + +def check_hash(filename: str, file: Path): + h = hashlib.sha256() + with file.open('br') as f: + while buf := f.read(1024**2): + h.update(buf) + + h.hexdigest()[:8] + url = f"{HIKARI_URL}/{h.hexdigest()[:8]}" + + with file.open('br') as f: + files = {'file': (filename, f.read(2048))} + + with requests.post(url, files=files, stream=True) as req: + if req.status_code == 404: + return + + req.raise_for_status() + resp = req.raw.read() + return orjson.loads(resp) + + +def output(copy: bool, resp: dict): + if copy: + pyperclip.copy(resp['url']) + else: + pprint(resp) + def upload(file: Path, obstruct: bool = typer.Option( False, "--obstruct", "-o", @@ -26,7 +55,7 @@ def upload(file: Path, help="Copy file URL to clipboard." ), hash: bool = typer.Option( - False, "--hash", "-h", + True, "--hash/--no-hash", "-h/-H", help="Hash file before uploading to avoid having to send the whole file twice." )): @@ -38,21 +67,14 @@ def upload(file: Path, elif filename is None: filename = file.name - if hash: - h = hashlib.sha256() - with file.open('br') as f: - while buf := f.read(1024**2): - h.update(buf) - - h.hexdigest()[:8] - url = f"{HIKARI_URL}/{h.hexdigest()[:8]}" - else: - url = HIKARI_URL + if hash and (resp := check_hash(filename, file)): + return output(copy, resp) with file.open('br') as f: files = {'file': (filename, f)} - with requests.post(url, files=files, stream=True) as req: + with requests.post(HIKARI_URL, files=files, stream=True) as req: + req.raise_for_status() resp = req.raw.read() data = orjson.loads(resp)