dotfiles/config/scripts/o

83 lines
1.8 KiB
Plaintext
Raw Permalink Normal View History

2018-11-24 13:45:14 +01:00
#!/usr/bin/env python3
2019-10-17 12:44:30 +02:00
# pylint: disable=C0103
"""
Find the subjectively best software
to open the file given in arguments with.
Doesn't use that XDG mess (only in last resort).
"""
2018-11-24 13:45:14 +01:00
import os
import subprocess
2019-10-17 12:44:30 +02:00
import sys
2018-11-24 13:45:14 +01:00
import tempfile
2019-10-17 12:44:30 +02:00
import urllib.request
import magic
2018-11-24 13:45:14 +01:00
# Getting what's needed
path = sys.argv[1]
# Getting the MIME type
ishttp = path.startswith('http')
buf = None
if ishttp:
buf = urllib.request.urlopen(path)
chunk = buf.read(1024)
mime = magic.from_buffer(chunk, mime=True)
else:
assert os.path.isfile(path), f"Not a file: {path}"
path = os.path.realpath(path)
mime = magic.from_file(path, mime=True)
mime = tuple(mime.split('/'))
assert len(mime) == 2
2019-10-17 12:44:30 +02:00
graphical = os.environ.get('DISPLAY')
2018-11-24 13:45:14 +01:00
# Some energumens
if mime[0] == "application" and mime[1] in ("json", "javascript"):
mime = ("text", mime[1])
# Determine stuff
ex = None # Executable needed to open the file
forcelocal = False # If we need to copy the file locally before opening it
2019-10-17 12:44:30 +02:00
isterm = False # Executable should run in a terminal
2018-11-24 13:45:14 +01:00
if mime[0] == "text":
if not ishttp:
ex = os.environ.get('VISUAL' if graphical else 'EDITOR', None)
isterm = True
elif mime[0] == "image":
ex = "feh"
elif mime[0] in ("audio", "video"):
ex = "mpv"
isterm = True
elif mime == ("application", "pdf"):
2019-10-17 12:44:30 +02:00
ex = "zathura"
2018-11-24 13:45:14 +01:00
forcelocal = True
# Open stuff
tmp = None
if ex:
if forcelocal and ishttp:
2019-10-17 12:44:30 +02:00
assert buf
2018-11-24 13:45:14 +01:00
tmp = tempfile.NamedTemporaryFile(prefix='o')
tmp.write(chunk)
tmp.write(buf.read())
path = tmp.name
else:
ex = 'xdg-open'
if ishttp:
ex = os.environ.get('BROWSER', ex)
if buf:
buf.close()
# TODO Launch a new terminal window for some
2019-10-17 12:44:30 +02:00
assert ex
2018-11-24 13:45:14 +01:00
p = subprocess.run([ex, path])
if tmp:
tmp.close()
sys.exit(p.returncode)