summaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorAnton Khirnov <anton@khirnov.net>2021-02-12 15:39:38 +0100
committerAnton Khirnov <anton@khirnov.net>2021-02-12 15:39:38 +0100
commit0cb9deef3e7b11288d85b0ec4911e50aec6f4f6e (patch)
tree591e52924547017d7734e652a32d28864531cb29 /bin
parent436ad7e2ae90dd1195e63f90976dc7abdca205ef (diff)
ups: rewrite in Python
When streaming stdin, use libmagic to guess the desired extension
Diffstat (limited to 'bin')
-rwxr-xr-xbin/ups57
1 files changed, 49 insertions, 8 deletions
diff --git a/bin/ups b/bin/ups
index 75c386b..7011747 100755
--- a/bin/ups
+++ b/bin/ups
@@ -1,11 +1,52 @@
-#!/bin/bash
+#!/usr/bin/python3
# ups.khirnov.net uploader
-if [ "$1" ]; then
- fpath=$1
-else
- fpath="-"
-fi
+import os.path
+import shutil
+import subprocess
+import sys
-url=$(curl -sS -E ~/.local/var/up/cert --data-binary "@${fpath}" "https://ups.khirnov.net/${fpath}")
-[ "${url}" ] && echo "${url}"
+try:
+ import magic
+ have_magic = True
+except ImportError:
+ have_magic = False
+
+server = 'https://ups.khirnov.net/'
+cert_path = os.path.expanduser('~/.local/var/up/cert')
+
+if len(sys.argv) > 2:
+ sys.stderr.write('Too many arguments\n')
+ sys.exit(1)
+elif len(sys.argv) == 2 and sys.argv[1] != '-':
+ src_name = sys.argv[1]
+ dst_name = os.path.basename(src_name)
+ stdin = subprocess.DEVNULL
+else:
+ src_name = '-'
+ dst_name = src_name
+ stdin = subprocess.PIPE
+
+ # try to guess the extension
+ if have_magic:
+ m = magic.Magic(extension = True)
+ e = m.from_buffer(sys.stdin.buffer.peek(2048))
+ if e != '???':
+ dst_name += '.' + e.split('/')[0]
+
+
+curl_cmdline = ['curl', '--silent', '--show-error', '--cert', cert_path,
+ '--data-binary', '@' + src_name, server + dst_name]
+
+child = subprocess.Popen(curl_cmdline, stdin = stdin)
+if stdin != subprocess.DEVNULL:
+ # stream our stdin to the child process
+ # cannot pass stdin to the child directly because we peeked at it above
+ shutil.copyfileobj(sys.stdin.buffer, child.stdin)
+ child.stdin.close()
+
+ret = child.wait()
+if ret != 0:
+ sys.stderr.write('curl returned an error code: %d\n' % ret)
+else:
+ sys.stdout.write('\n')