125 lines
5.4 KiB
Python
Executable File
125 lines
5.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""osmike-publish - publish a file and print its public https URL (https://charts.osmike.com/...).
|
|
|
|
osmike-publish <file> [prefix] [--quiet]
|
|
|
|
Types: png jpg jpeg gif webp svg pdf html htm txt md csv json mp4 webm zip. Max 50 MB.
|
|
The URL is public but unguessable (<prefix>-<unixtime>-<18 hex>.<ext>); don't publish secrets.
|
|
Images in an a2a message: write  and the ws6 panel shows it inline.
|
|
|
|
stdout: the URL only. stderr: a one-line summary (suppressed by --quiet). Exit 0 ok, 2 error.
|
|
Inside an agent: through the bus with the agent's key (POST /v1/runs/publish). On hosts: ssh with ~/.ssh/mikeos_media.
|
|
Override the ssh target with $OSMIKE_PUBLISH_RELAY.
|
|
"""
|
|
import argparse, os, re, secrets, shlex, subprocess, sys, time
|
|
|
|
DEST_DIR = "/var/lib/docker/volumes/deploy_caddy_data/_data/charts"
|
|
BASE_URL = "https://charts.osmike.com/"
|
|
MAX_BYTES = 50 * 1024 * 1024
|
|
TYPES = {"png", "jpg", "jpeg", "gif", "webp", "svg", "pdf", "html", "htm", "txt", "md", "csv", "json",
|
|
"mp4", "webm", "zip"}
|
|
SSH_OPTS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=20", "-o", "StrictHostKeyChecking=accept-new"]
|
|
|
|
|
|
def die(msg):
|
|
print(f"osmike-publish: {msg}", file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
|
|
def relay_argv():
|
|
"""ssh argv (without the remote command) that reaches relay 242 as root."""
|
|
override = os.environ.get("OSMIKE_PUBLISH_RELAY")
|
|
if override:
|
|
return ["ssh"] + SSH_OPTS + [override]
|
|
cfg = os.path.expanduser("~/.ssh/config")
|
|
try:
|
|
if re.search(r"(?im)^\s*Host\s+(.*\s)?relay242(\s|$)", open(cfg).read()):
|
|
return ["ssh"] + SSH_OPTS + ["relay242"]
|
|
except OSError:
|
|
pass
|
|
key = os.path.expanduser("~/.ssh/mikeos_media")
|
|
if os.path.exists(key):
|
|
return ["ssh"] + SSH_OPTS + ["-i", key, "root@91.98.177.242"]
|
|
return ["ssh"] + SSH_OPTS + ["relay242"]
|
|
|
|
|
|
def make_name(prefix, ext):
|
|
p = re.sub(r"[^A-Za-z0-9._-]", "_", prefix).strip("._-")[:40] or "file"
|
|
return f"{p}-{int(time.time())}-{secrets.token_hex(9)}.{ext}"
|
|
|
|
|
|
def main(argv=None):
|
|
ap = argparse.ArgumentParser(prog="osmike-publish", description=__doc__,
|
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
ap.add_argument("file")
|
|
ap.add_argument("prefix", nargs="?", help="name prefix (default: the file name)")
|
|
ap.add_argument("--quiet", "-q", action="store_true", help="print only the URL")
|
|
a = ap.parse_args(argv)
|
|
|
|
f = a.file
|
|
if not os.path.isfile(f):
|
|
die(f"not a readable file: {f}")
|
|
size = os.path.getsize(f)
|
|
if size == 0:
|
|
die(f"empty file: {f}")
|
|
if size > MAX_BYTES:
|
|
die(f"too large: {size} bytes (max 50 MB)")
|
|
ext = os.path.splitext(f)[1].lower().lstrip(".")
|
|
if ext not in TYPES:
|
|
die(f"unsupported type '{('.' + ext) if ext else 'no extension'}' (allowed: {' '.join(sorted(TYPES))})")
|
|
if ext == "jpeg":
|
|
ext = "jpg"
|
|
if ext == "htm":
|
|
ext = "html"
|
|
api, key = os.environ.get("A2A_API", "").rstrip("/"), os.environ.get("A2A_AGENT_KEY", "")
|
|
if api and key and not os.environ.get("OSMIKE_PUBLISH_RELAY"):
|
|
# Inside an agent: upload through the bus with the agent's own key (no SSH to the servers; 2026-11-13).
|
|
import json, urllib.error, urllib.parse, urllib.request
|
|
label = (a.prefix or os.path.splitext(os.path.basename(f))[0]) + "." + ext
|
|
req = urllib.request.Request(api + "/v1/runs/publish?name=" + urllib.parse.quote(label), data=open(f, "rb").read(),
|
|
headers={"X-API-KEY": key, "Content-Type": "application/octet-stream"}, method="POST")
|
|
try:
|
|
d = json.load(urllib.request.urlopen(req, timeout=300))
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
detail = json.load(e).get("detail")
|
|
except Exception:
|
|
detail = e.reason
|
|
die(f"publish failed: {detail} (HTTP {e.code})")
|
|
except urllib.error.URLError as e:
|
|
die(f"cannot reach OsMike: {e.reason}")
|
|
url = d["url"]
|
|
print(url)
|
|
if not a.quiet:
|
|
hint = f" (embed: )" if ext in {"png", "jpg", "gif", "webp", "svg"} else ""
|
|
print(f"published {os.path.basename(f)} ({size} bytes){hint}", file=sys.stderr)
|
|
return 0
|
|
name = make_name(a.prefix or os.path.splitext(os.path.basename(f))[0], ext)
|
|
dest = f"{DEST_DIR}/{name}"
|
|
q, qt = shlex.quote(dest), shlex.quote(dest + ".part")
|
|
remote = (f"umask 022; cat > {qt} && mv {qt} {q} && chmod 644 {q} && "
|
|
f"(stat -c %s {q} 2>/dev/null || wc -c < {q})")
|
|
try:
|
|
with open(f, "rb") as fh:
|
|
r = subprocess.run(relay_argv() + [remote], stdin=fh, capture_output=True, timeout=300)
|
|
except subprocess.TimeoutExpired:
|
|
die("upload timed out (5 min)")
|
|
except OSError as e:
|
|
die(f"cannot run ssh: {e}")
|
|
if r.returncode != 0:
|
|
err = r.stderr.decode("utf-8", "replace").strip().splitlines()
|
|
die(f"upload to relay 242 failed (ssh rc {r.returncode}): {err[-1] if err else ''}")
|
|
got = r.stdout.decode().strip().split()[-1:] or [""]
|
|
if got[0] != str(size):
|
|
die(f"size mismatch after upload ({got[0]} != {size})")
|
|
url = BASE_URL + name
|
|
print(url)
|
|
if not a.quiet:
|
|
hint = f" (embed: )" if ext in {"png", "jpg", "gif", "webp", "svg"} else ""
|
|
print(f"published {os.path.basename(f)} ({size} bytes){hint}", file=sys.stderr)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|