-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathper-url-browser-session.py
More file actions
executable file
·58 lines (52 loc) · 2.51 KB
/
per-url-browser-session.py
File metadata and controls
executable file
·58 lines (52 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/python3
import sys
import pathlib
import argparse
import subprocess
import configparser
import shlex
import re
# FIXME: Check system path too? Subdirectories? $XDG_..._DIR?
user_apps_path = pathlib.Path('~/.local/share/applications/').expanduser()
argparser = argparse.ArgumentParser()
argparser.add_argument('url', nargs='*')
args, other_args = argparser.parse_known_args()
# FIXME: Extend this to other URI schemes?
mime_handlers = {}
mimeinfo = configparser.ConfigParser(interpolation=None)
mimeinfo.read_string((user_apps_path / 'mimeinfo.cache').read_text())
for key in mimeinfo['MIME Cache'].keys():
if key in ('x-scheme-handler/https', 'x-scheme-handler/http'):
# Value is ';' separated, and usually ends with a ';', so strip & split it.
mime_handlers[key.split('/', 1)[1]] = mimeinfo['MIME Cache'].get(key).strip(';').split(';')
# Compile dict of {regexp: command line}
# FIXME: Is there really no "run this .desktop file with this URI" command?
# I've found plenty for "run this .desktop file" (`gio launch` was my favourite) but none of them pass arguments through.
regexp_handlers = {}
# FIXME: Behaviour is undetermined if 2 .desktop files have the same regexp
for handler in set(h for sublist in mime_handlers.values() for h in sublist):
if not (user_apps_path / handler).exists(): continue
handler_config = configparser.ConfigParser(interpolation=None, allow_no_value=True)
handler_config.read_string((user_apps_path / handler).read_text())
for section in handler_config.sections():
if handler_config.has_option(section, 'X-Mijofa-URL-regexps') and handler_config.has_option(section, 'Exec'):
for r in handler_config.get(section, 'X-Mijofa-URL-regexps').strip(';').split(';'):
regexp_handlers[re.compile(r)] = shlex.split(handler_config.get(section, 'Exec'))
subprocesses = []
if args.url:
for url in args.url:
# Sort by length of regexp, longest first
for regexp in sorted(regexp_handlers, key=lambda r: len(r.pattern), reverse=True):
if regexp.fullmatch(url):
args = regexp_handlers[regexp].copy()
args[args.index('%u')] = url
subprocesses.append(subprocess.Popen(args))
break
else:
# Kinda surprised compiled re files are hashable, but this does work
args = regexp_handlers.get(re.compile('^.*$'), []).copy()
args.remove('%u')
subprocesses.append(subprocess.Popen(args))
# Wait for all subprocesses to return
for p in subprocesses:
p.wait()