dotfiles/config/scripts/o

83 lines
1.8 KiB
Plaintext
Raw 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")
2018-11-24 13:45:14 +01:00
buf = None
if ishttp:
buf = urllib.request.urlopen(path)
chunk = buf.read(1024)
fmagic = magic.detect_from_content(chunk)
2018-11-24 13:45:14 +01:00
else:
assert os.path.isfile(path), f"Not a file: {path}"
path = os.path.realpath(path)
fmagic = magic.detect_from_filename(path)
mime = tuple(fmagic.mime_type.split("/"))
2018-11-24 13:45:14 +01:00
assert len(mime) == 2
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)
2018-11-24 13:45:14 +01:00
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
tmp = tempfile.NamedTemporaryFile(prefix="o")
2018-11-24 13:45:14 +01:00
tmp.write(chunk)
tmp.write(buf.read())
path = tmp.name
else:
ex = "xdg-open"
2018-11-24 13:45:14 +01:00
if ishttp:
ex = os.environ.get("BROWSER", ex)
2018-11-24 13:45:14 +01:00
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)