hikari_uploader/hikari/hikari.py

89 lines
2.2 KiB
Python
Executable file

#!/usr/bin/env python3
import hashlib
from pathlib import Path
from pprint import pprint
import orjson
import pyperclip
import requests
import typer
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",
help="Obstruct filename (by hashing)"
),
filename: str = typer.Option(
None, "--name", "-n",
help="Rename the uploaded file."
),
copy: bool = typer.Option(
False, "--copy", "-c",
help="Copy file URL to clipboard."
),
hash: bool = typer.Option(
True, "--hash/--no-hash", "-h/-H",
help="Hash file before uploading to avoid having to send the whole file twice."
)):
if copy:
pyperclip.copy("")
if obstruct:
filename = hashlib.sha256(file.name.encode()).hexdigest()
elif filename is None:
filename = file.name
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(HIKARI_URL, files=files, stream=True) as req:
req.raise_for_status()
resp = req.raw.read()
data = orjson.loads(resp)
if copy:
pyperclip.copy(data['url'])
else:
print(resp.decode())
def main():
typer.run(upload)