Skip to content

Instantly share code, notes, and snippets.

@timotree3
Created April 22, 2021 00:07
Show Gist options
  • Save timotree3/aade501f6a6bd875045a951954bc6865 to your computer and use it in GitHub Desktop.
Save timotree3/aade501f6a6bd875045a951954bc6865 to your computer and use it in GitHub Desktop.
Hanabi URL Handler
[Desktop Entry]
Name=HTTP URL handler
Comment=Open an HTTP/HTTPS URL with a particular browser
TryExec=http_url_handler.py
Exec=http_url_handler.py %u
X-MultipleArgs=false
Type=Application
Terminal=false
NoDisplay=true
MimeType=x-scheme-handler/http;x-scheme-handler/https
X-Desktop-File-Install-Version=0.24
#! /usr/bin/env python3
import subprocess
import logging
import argparse
import syslog
import sys
try :
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
import os.path
def http_url(url):
if url.startswith('http://'):
return url
if url.startswith('https://'):
return url
else:
syslog.syslog(syslog.LOG_ERR, sys.argv[0] + ": not an HTTP/HTTPS URL: '{}'".format(url))
raise argparse.ArgumentTypeError(
"not an HTTP/HTTPS URL: '{}'".format(url))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Handler for http/https URLs.'
)
parser.add_argument(
'-v',
'--verbose',
help='More verbose logging',
dest="loglevel",
default=logging.WARNING,
action="store_const",
const=logging.INFO,
)
parser.add_argument(
'-d',
'--debug',
help='Enable debugging logs',
action="store_const",
dest="loglevel",
const=logging.DEBUG,
)
parser.add_argument(
'url',
type=http_url,
help="URL starting with 'http://' or 'https://'",
)
args = parser.parse_args()
logging.basicConfig(level=args.loglevel)
logging.debug("args.url = '{}'".format(args.url))
parsed = urlparse(args.url)
logging.info("hostname = '{}'".format(parsed.hostname))
if parsed.hostname == 'hanab.live' or parsed.hostname == 'hanabi.live':
browser = 'chromium-browser'
else:
browser = 'firefox'
logging.info("browser = '{}'".format(browser))
cmd = [browser, args.url]
try :
status = subprocess.check_call(cmd)
except subprocess.CalledProcessError:
syslog.syslog(syslog.LOG_ERR, sys.argv[0] + "could not open URL with browser '{}': {}".format(browser, args.url))
raise
@timotree3
Copy link
Author

Script largely copied from here https://askubuntu.com/a/1164362
Put the python file somewhere in your PATH and mark it as executable. Put the .desktop file in .local/share/applications. Then run

gio mime x-scheme-handler/http  http-url-handler.desktop
gio mime x-scheme-handler/https http-url-handler.desktop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment