diff options
| author | TheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com> | 2025-02-11 03:10:06 +0900 |
|---|---|---|
| committer | TheSiahxyz <164138827+TheSiahxyz@users.noreply.github.com> | 2025-02-11 03:10:06 +0900 |
| commit | 13d4d6752b2086c0bf9ff38d1fa8408f4a5aae5f (patch) | |
| tree | de2b5e3b26e7d00b1fcf53fe761ae58e880e3823 | |
| parent | e79f665eba1fd69aa56162e826313ce1c7446ed4 (diff) | |
modified qutebrowser/config.py, modified bin/bookmarks, deleted bin/umpv, created userscripts/
| -rw-r--r-- | ar/.config/qutebrowser/config.py | 33 | ||||
| -rwxr-xr-x | ar/.config/qutebrowser/userscripts/add-nextcloud-bookmarks | 173 | ||||
| -rwxr-xr-x | ar/.config/qutebrowser/userscripts/add-nextcloud-cookbook | 131 | ||||
| -rwxr-xr-x | ar/.config/qutebrowser/userscripts/qute-pass | 411 | ||||
| -rwxr-xr-x | ar/.config/qutebrowser/userscripts/translate | 116 | ||||
| -rwxr-xr-x | ar/.local/bin/bookmarks | 7 | ||||
| -rwxr-xr-x | ar/.local/bin/umpv | 103 |
7 files changed, 860 insertions, 114 deletions
diff --git a/ar/.config/qutebrowser/config.py b/ar/.config/qutebrowser/config.py index ce9caef..cdf1b91 100644 --- a/ar/.config/qutebrowser/config.py +++ b/ar/.config/qutebrowser/config.py @@ -2421,13 +2421,6 @@ config.bind("<Ctrl-C>", "cmd-set-text :") # config.bind('{{', 'navigate prev -t') # config.bind('}}', 'navigate next -t') -config.bind(",d", "spawn qndl -v {url}") -config.bind(",D", "hint links spawn qndl -v {hint-url}") -config.bind(",m", "spawn mpv -quiet --loop {url}") -config.bind(",M", "hint links spawn mpv -quiet --loop {hint-url}") -config.bind(",v", "spawn umpv {url}") -config.bind(",V", "hint links spawn umpv {hint-url}") - ## Bindings for caret mode # config.bind('$', 'move-to-end-of-line', mode='caret') # config.bind('0', 'move-to-start-of-line', mode='caret') @@ -2551,3 +2544,29 @@ config.bind("<Ctrl-]>", "command-history-prev", mode="command") # config.bind('Y', 'prompt-accept --save yes', mode='yesno') # config.bind('n', 'prompt-accept no', mode='yesno') # config.bind('y', 'prompt-accept yes', mode='yesno') + +## userscripts +config.bind(",b", "spawn --userscript add-nextcloud-bookmarks") +config.bind(",B", "hint links userscript add-nextcloud-bookmarks") +config.bind(",c", "spawn --userscript add-nextcloud-cookbook") +config.bind(",C", "hint links userscript add-nextcloud-cookbook") +config.bind(",d", "spawn qndl -v {url}") +config.bind(",D", "hint links spawn qndl -v {hint-url}") +config.bind(",gd", "spawn --userscript translate") +config.bind(",gk", "spawn --userscript translate --target_lang ko") +config.bind(",gd", "spawn --userscript translate", mode="caret") +config.bind(",gk", "spawn --userscript translate --target_lang ko", mode="caret") +config.bind(",help", "open -t qute://help/index.html") +config.bind(",msg", "open -t qute://log/?level=info") +config.bind(",oc", "open -t qute://help/commands.html#cmd-repeat") +config.bind( + ",pp", + "spawn --userscript qute-pass --dmenu-invocation passmenu2 --unfiltered", +) +config.bind( + ",pn", + 'spawn --userscript qute-pass --dmenu-invocation passmenu2 --unfiltered --username-pattern "name: (.+)"', +) +config.bind(",rs", "restart") +config.bind(",v", "spawn mpv -quiet --loop {url}") +config.bind(",V", "hint links spawn mpv -quiet --loop {hint-url}") diff --git a/ar/.config/qutebrowser/userscripts/add-nextcloud-bookmarks b/ar/.config/qutebrowser/userscripts/add-nextcloud-bookmarks new file mode 100755 index 0000000..2a480cc --- /dev/null +++ b/ar/.config/qutebrowser/userscripts/add-nextcloud-bookmarks @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 + +""" +Behavior: + A qutebrowser userscript that creates bookmarks in Nextcloud's Bookmarks app. + +Requirements: + requests + +userscript setup: + Optionally create ~/.config/qutebrowser/add-nextcloud-bookmarks.ini like: + +[nextcloud] +HOST=https://nextcloud.example.com +USER=username +;PASSWORD=lamepassword +DESCRIPTION=None +;TAGS=just-one +TAGS=read-me-later,added-by-qutebrowser, Another-One + + If settings aren't in the configuration file, the user will be prompted during + bookmark creation. If DESCRIPTION and TAGS are set to None, they will be left + blank. If the user does not want to be prompted for a password, it is recommended + to set up an 'app password'. See the following for instructions: + https://docs.nextcloud.com/server/latest/user_manual/en/session_management.html#managing-devices # noqa: E501 + +qutebrowser setup: + add bookmark via hints + config.bind('X', 'hint links userscript add-nextcloud-bookmarks') + + add bookmark of current URL + config.bind('X', 'spawn --userscript add-nextcloud-bookmarks') + +troubleshooting: + Errors detected within this userscript will have an exit of 231. All other + exit codes will come from requests. +""" + +import configparser +from json import dumps +from os import environ, path +from sys import argv, exit + +from PyQt6.QtWidgets import QApplication, QInputDialog, QLineEdit +from requests import get, post +from requests.auth import HTTPBasicAuth + + +def get_text(name, info): + """Get input from the user.""" + _app = QApplication(argv) # noqa: F841 + if name == "password": + text, ok = QInputDialog.getText( + None, + "add-nextcloud-bookmarks userscript", + "Please enter {}".format(info), + QLineEdit.EchoMode.Password, + ) + else: + text, ok = QInputDialog.getText( + None, "add-nextcloud-bookmarks userscript", "Please enter {}".format(info) + ) + if not ok: + message("info", "Dialog box canceled.") + exit(0) + return text + + +def message(level, text): + """display message""" + with open(environ["QUTE_FIFO"], "w") as fifo: + fifo.write( + 'message-{} "add-nextcloud-bookmarks userscript: {}"\n'.format(level, text) + ) + fifo.flush() + + +if "QUTE_FIFO" not in environ: + print( + "This script is designed to run as a qutebrowser userscript, " + "not as a standalone script." + ) + exit(231) + +if "QUTE_CONFIG_DIR" not in environ: + if "XDG_CONFIG_HOME" in environ: + QUTE_CONFIG_DIR = environ["XDG_CONFIG_HOME"] + "/qutebrowser" + else: + QUTE_CONFIG_DIR = environ["HOME"] + "/.config/qutebrowser" +else: + QUTE_CONFIG_DIR = environ["QUTE_CONFIG_DIR"] + +config_file = QUTE_CONFIG_DIR + "/add-nextcloud-bookmarks.ini" +if path.isfile(config_file): + config = configparser.ConfigParser() + config.read(config_file) + settings = dict(config.items("nextcloud")) +else: + settings = {} + +settings_info = [ + ("host", "host information.", "required"), + ("user", "username.", "required"), + ("password", "password.", "required"), + ("description", "description or leave blank", "optional"), + ("tags", "tags (comma separated) or leave blank", "optional"), +] + +# check for settings that need user interaction and clear optional setting if need be +for setting in settings_info: + if setting[0] not in settings: + userInput = get_text(setting[0], setting[1]) + settings[setting[0]] = userInput + if setting[2] == "optional": + if settings[setting[0]] == "None": + settings[setting[0]] = "" + +tags = settings["tags"].split(",") + +QUTE_URL = environ["QUTE_URL"] +api_url = settings["host"] + "/index.php/apps/bookmarks/public/rest/v2/bookmark" + +auth = HTTPBasicAuth(settings["user"], settings["password"]) +headers = {"Content-Type": "application/json"} +params = {"url": QUTE_URL} + +# check if there is already a bookmark for the URL +r = get( + api_url, + auth=auth, + headers=headers, + params=params, + timeout=(3.05, 27), +) +if r.status_code != 200: + message( + "error", + "Could not connect to {} with status code {}".format( + settings["host"], r.status_code + ), + ) + exit(r.status_code) + +try: + r.json()["data"][0]["id"] +except IndexError: + pass +else: + message("info", "bookmark already exists for {}".format(QUTE_URL)) + exit(0) + +if environ["QUTE_MODE"] == "hints": + QUTE_TITLE = QUTE_URL +else: + QUTE_TITLE = environ["QUTE_TITLE"] + +# JSON format +# https://nextcloud-bookmarks.readthedocs.io/en/latest/bookmark.html#create-a-bookmark +dict = { + "url": QUTE_URL, + "title": QUTE_TITLE, + "description": settings["description"], + "tags": tags, +} +data = dumps(dict) + +r = post(api_url, data=data, headers=headers, auth=auth, timeout=(3.05, 27)) + +if r.status_code == 200: + message("info", "bookmark {} added".format(QUTE_URL)) +else: + message("error", "something went wrong {} bookmark not added".format(QUTE_URL)) + exit(r.status_code) diff --git a/ar/.config/qutebrowser/userscripts/add-nextcloud-cookbook b/ar/.config/qutebrowser/userscripts/add-nextcloud-cookbook new file mode 100755 index 0000000..1510907 --- /dev/null +++ b/ar/.config/qutebrowser/userscripts/add-nextcloud-cookbook @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 + +""" +Behavior: + A qutebrowser userscript that adds recipes to Nextcloud's Cookbook app. + +Requirements: + requests + +userscript setup: + Optionally create ~/.config/qutebrowser/add-nextcloud-cookbook.ini like: + +[nextcloud] +HOST=https://nextcloud.example.com +USER=username +;PASSWORD=lamepassword + + If settings aren't in the configuration file, the user will be prompted. + If the user does not want to be prompted for a password, it is recommended + to set up an 'app password' with 'Allow filesystem access' enabled. + See the following for instructions: + https://docs.nextcloud.com/server/latest/user_manual/en/session_management.html#managing-devices # noqa: E501 + +qutebrowser setup: + add recipe via hints + config.bind('X', 'hint links userscript add-nextcloud-cookbook') + + add recipe of current URL + config.bind('X', 'spawn --userscript add-nextcloud-cookbook') + +troubleshooting: + Errors detected within this userscript will have an exit of 231. All other + exit codes will come from requests. +""" + +import configparser +from os import environ, path +from sys import argv, exit + +from PyQt6.QtWidgets import QApplication, QInputDialog, QLineEdit +from requests import post +from requests.auth import HTTPBasicAuth + + +def get_text(name, info): + """Get input from the user.""" + _app = QApplication(argv) # noqa: F841 + if name == "password": + text, ok = QInputDialog.getText( + None, + "add-nextcloud-cookbook userscript", + "Please enter {}".format(info), + QLineEdit.EchoMode.Password, + ) + else: + text, ok = QInputDialog.getText( + None, "add-nextcloud-cookbook userscript", "Please enter {}".format(info) + ) + if not ok: + message("info", "Dialog box canceled.") + exit(0) + return text + + +def message(level, text): + """display message""" + with open(environ["QUTE_FIFO"], "w") as fifo: + fifo.write( + "message-{} 'add-nextcloud-cookbook userscript: {}'\n".format(level, text) + ) + fifo.flush() + + +if "QUTE_FIFO" not in environ: + print( + "This script is designed to run as a qutebrowser userscript, " + "not as a standalone script." + ) + exit(231) + +if "QUTE_CONFIG_DIR" not in environ: + if "XDG_CONFIG_HOME" in environ: + QUTE_CONFIG_DIR = environ["XDG_CONFIG_HOME"] + "/qutebrowser" + else: + QUTE_CONFIG_DIR = environ["HOME"] + "/.config/qutebrowser" +else: + QUTE_CONFIG_DIR = environ["QUTE_CONFIG_DIR"] + +config_file = QUTE_CONFIG_DIR + "/add-nextcloud-cookbook.ini" +if path.isfile(config_file): + config = configparser.ConfigParser() + config.read(config_file) + settings = dict(config.items("nextcloud")) +else: + settings = {} + +settings_info = [ + ("host", "host information.", "required"), + ("user", "username.", "required"), + ("password", "password.", "required"), +] + +# check for settings that need user interaction +for setting in settings_info: + if setting[0] not in settings: + userInput = get_text(setting[0], setting[1]) + settings[setting[0]] = userInput + +api_url = settings["host"] + "/index.php/apps/cookbook/import" +headers = {"Content-Type": "application/x-www-form-urlencoded"} +auth = HTTPBasicAuth(settings["user"], settings["password"]) +data = "url=" + environ["QUTE_URL"] + +message("info", "starting to process {}".format(environ["QUTE_URL"])) + +r = post(api_url, data=data, headers=headers, auth=auth, timeout=(3.05, 27)) + +if r.status_code == 200: + message("info", "recipe from {} added.".format(environ["QUTE_URL"])) + exit(0) +elif r.status_code == 500: + message("warning", "Cookbook app reports {}".format(r.text)) + exit(0) +else: + message( + "error", + "Could not connect to {} with status code {}".format( + settings["host"], r.status_code + ), + ) + exit(r.status_code) diff --git a/ar/.config/qutebrowser/userscripts/qute-pass b/ar/.config/qutebrowser/userscripts/qute-pass new file mode 100755 index 0000000..6b071b8 --- /dev/null +++ b/ar/.config/qutebrowser/userscripts/qute-pass @@ -0,0 +1,411 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: Chris Braun (cryzed) <cryzed@googlemail.com> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +""" +Insert login information using pass and a dmenu-compatible application (e.g. dmenu, rofi -dmenu, ...). A short +demonstration can be seen here: https://i.imgur.com/KN3XuZP.gif. +""" + +USAGE = """The domain of the site has to appear as a segment in the pass path, +for example: "github.com/cryzed" or "websites/github.com". Alternatively the +parameter `--unfiltered` may be used to get a list of all passwords. How the +username and password are determined is freely configurable using the CLI +arguments. As an example, if you instead store the username as part of the +secret (and use a site's name as filename), instead of the default configuration, +use `--username-target secret` and `--username-pattern "username: (.+)"`. + +The login information is inserted by emulating key events using qutebrowser's +fake-key command in this manner: [USERNAME]<Tab>[PASSWORD], which is compatible +with almost all login forms. + +If you use gopass with multiple mounts, use the CLI switch --mode gopass to switch to gopass mode. + +Suggested bindings similar to Uzbl's `formfiller` script: + + config.bind('<z><l>', 'spawn --userscript qute-pass') + config.bind('<z><u><l>', 'spawn --userscript qute-pass --username-only') + config.bind('<z><p><l>', 'spawn --userscript qute-pass --password-only') + config.bind('<z><o><l>', 'spawn --userscript qute-pass --otp-only') +""" + +EPILOG = """Dependencies: tldextract (Python 3 module), pass, pass-otp (optional). + +WARNING: The login details are viewable as plaintext in qutebrowser's debug log (qute://log) and might be shared if +you decide to submit a crash report!""" + +import argparse +import enum +import fnmatch +import functools +import os +import re +import shlex +import subprocess +import sys +import unicodedata +from urllib.parse import urlparse + +import idna +import tldextract + + +def expanded_path(path): + # Expand potential ~ in paths, since this script won't be called from a shell that does it for us + expanded = os.path.expanduser(path) + # Add trailing slash if not present + return os.path.join(expanded, "") + + +argument_parser = argparse.ArgumentParser( + description=__doc__, usage=USAGE, epilog=EPILOG +) +argument_parser.add_argument("url", nargs="?", default=os.getenv("QUTE_URL")) +argument_parser.add_argument( + "--password-store", + "-p", + default=expanded_path(os.getenv("PASSWORD_STORE_DIR", default="~/.password-store")), + help="Path to your pass password-store (only used in pass-mode)", + type=expanded_path, +) +argument_parser.add_argument( + "--mode", + "-M", + choices=["pass", "gopass"], + default="pass", + help="Select mode [gopass] to use gopass instead of the standard pass.", +) +argument_parser.add_argument( + "--prefix", + type=str, + help="Search only the given subfolder of the store (only used in gopass-mode)", +) +argument_parser.add_argument( + "--username-pattern", + "-u", + default=r".*/(.+)", + help="Regular expression that matches the username", +) +argument_parser.add_argument( + "--username-target", + "-U", + choices=["path", "secret"], + default="path", + help="The target for the username regular expression", +) +argument_parser.add_argument( + "--password-pattern", + "-P", + default=r"(.*)", + help="Regular expression that matches the password", +) +argument_parser.add_argument( + "--dmenu-invocation", + "-d", + default="dmenu", + help="Invocation used to execute a dmenu-provider", +) +argument_parser.add_argument( + "--no-insert-mode", + "-n", + dest="insert_mode", + action="store_false", + help="Don't automatically enter insert mode", +) +argument_parser.add_argument( + "--io-encoding", + "-i", + default="UTF-8", + help="Encoding used to communicate with subprocesses", +) +argument_parser.add_argument( + "--merge-candidates", + "-m", + action="store_true", + help="Merge pass candidates for fully-qualified and registered domain name", +) +argument_parser.add_argument( + "--extra-url-suffixes", + "-s", + default="", + help="Comma-separated string containing extra suffixes (e.g local)", +) +argument_parser.add_argument( + "--unfiltered", + dest="unfiltered", + action="store_true", + help="Show an unfiltered selection of all passwords in the store", +) +argument_parser.add_argument( + "--always-show-selection", + dest="always_show_selection", + action="store_true", + help="Always show selection, even if there is only a single match", +) +group = argument_parser.add_mutually_exclusive_group() +group.add_argument( + "--username-only", "-e", action="store_true", help="Only insert username" +) +group.add_argument( + "--password-only", "-w", action="store_true", help="Only insert password" +) +group.add_argument("--otp-only", "-o", action="store_true", help="Only insert OTP code") + +stderr = functools.partial(print, file=sys.stderr) + + +class ExitCodes(enum.IntEnum): + SUCCESS = 0 + FAILURE = 1 + # 1 is automatically used if Python throws an exception + NO_PASS_CANDIDATES = 2 + COULD_NOT_MATCH_USERNAME = 3 + COULD_NOT_MATCH_PASSWORD = 4 + + +class CouldNotMatchUsername(Exception): + pass + + +class CouldNotMatchPassword(Exception): + pass + + +def qute_command(command): + with open(os.environ["QUTE_FIFO"], "w") as fifo: + fifo.write(command + "\n") + fifo.flush() + + +# Encode candidate string parts as Internationalized Domain Name, doing +# Unicode normalization before. This allows to properly match (non-ASCII) +# pass entries with the corresponding domain names. +def idna_encode(name): + # Do Unicode normalization first, we use form NFKC because: + # 1. Use the compatibility normalization because these sequences have "the same meaning in some contexts" + # 2. idna.encode() below requires the Unicode strings to be in normalization form C + # See https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms + unicode_normalized = unicodedata.normalize("NFKC", name) + # Empty strings can not be encoded, they appear for example as empty + # parts in split_path. If something like this happens, we just fall back + # to the unicode representation (which may already be ASCII then). + try: + idna_encoded = idna.encode(unicode_normalized) + except idna.IDNAError: + idna_encoded = unicode_normalized + return idna_encoded + + +def find_pass_candidates(domain, unfiltered=False): + candidates = [] + + if arguments.mode == "gopass": + gopass_args = ["gopass", "list", "--flat"] + if arguments.prefix: + gopass_args.append(arguments.prefix) + all_passwords = ( + subprocess.run(gopass_args, stdout=subprocess.PIPE) + .stdout.decode("UTF-8") + .splitlines() + ) + + for password in all_passwords: + if unfiltered or domain in password: + candidates.append(password) + else: + idna_domain = idna_encode(domain) + for path, directories, file_names in os.walk( + arguments.password_store, followlinks=True + ): + secrets = fnmatch.filter(file_names, "*.gpg") + if not secrets: + continue + + # Strip password store path prefix to get the relative pass path + pass_path = path[len(arguments.password_store) :] + split_path = pass_path.split(os.path.sep) + idna_split_path = [idna_encode(part) for part in split_path] + for secret in secrets: + secret_base = os.path.splitext(secret)[0] + idna_secret_base = idna_encode(secret_base) + if not unfiltered and idna_domain not in ( + idna_split_path + [idna_secret_base] + ): + continue + + # Append the unencoded Unicode path/name since this is how pass uses them + candidates.append(os.path.join(pass_path, secret_base)) + return candidates + + +def _run_pass(pass_arguments): + # The executable is conveniently named after it's mode [pass|gopass]. + pass_command = [arguments.mode] + env = os.environ.copy() + env["PASSWORD_STORE_DIR"] = arguments.password_store + process = subprocess.run( + pass_command + pass_arguments, env=env, stdout=subprocess.PIPE + ) + return process.stdout.decode(arguments.io_encoding).strip() + + +def pass_(path): + return _run_pass(["show", path]) + + +def pass_otp(path): + if arguments.mode == "gopass": + return _run_pass(["otp", "-o", path]) + return _run_pass(["otp", path]) + + +def dmenu(items, invocation): + command = shlex.split(invocation) + process = subprocess.run( + command, + input="\n".join(items).encode(arguments.io_encoding), + stdout=subprocess.PIPE, + ) + return process.stdout.decode(arguments.io_encoding).strip() + + +def fake_key_raw(text): + for character in text: + # Escape all characters by default, space requires special handling + sequence = '" "' if character == " " else r"\{}".format(character) + qute_command("fake-key {}".format(sequence)) + + +def extract_password(secret, pattern): + match = re.match(pattern, secret) + if not match: + raise CouldNotMatchPassword("Pattern did not match target") + try: + return match.group(1) + except IndexError: + raise CouldNotMatchPassword( + "Pattern did not contain capture group, please use capture group. Example: (.*)" + ) + + +def extract_username(target, pattern): + match = re.search(pattern, target, re.MULTILINE) + if not match: + raise CouldNotMatchUsername("Pattern did not match target") + try: + return match.group(1) + except IndexError: + raise CouldNotMatchUsername( + "Pattern did not contain capture group, please use capture group. Example: (.*)" + ) + + +def main(arguments): + if not arguments.url: + argument_parser.print_help() + return ExitCodes.FAILURE + + extractor = tldextract.TLDExtract( + extra_suffixes=arguments.extra_url_suffixes.split(",") + ) + extract_result = extractor(arguments.url) + + # Try to find candidates using targets in the following order: fully-qualified domain name (includes subdomains), + # the registered domain name, the IPv4 address if that's what the URL represents and finally the private domain + # (if a non-public suffix was used), and the URL netloc. + candidates = set() + attempted_targets = [] + + private_domain = "" + if not extract_result.suffix: + private_domain = ( + ".".join((extract_result.subdomain, extract_result.domain)) + if extract_result.subdomain + else extract_result.domain + ) + + netloc = urlparse(arguments.url).netloc + + for target in filter( + None, + [ + extract_result.fqdn, + extract_result.registered_domain, + extract_result.ipv4, + private_domain, + netloc, + ], + ): + attempted_targets.append(target) + target_candidates = find_pass_candidates( + target, unfiltered=arguments.unfiltered + ) + if not target_candidates: + continue + + candidates.update(target_candidates) + if not arguments.merge_candidates: + break + else: + if not candidates: + stderr( + "No pass candidates for URL {!r} found! (I tried {!r})".format( + arguments.url, attempted_targets + ) + ) + return ExitCodes.NO_PASS_CANDIDATES + + if len(candidates) == 1 and not arguments.always_show_selection: + selection = candidates.pop() + else: + selection = dmenu(sorted(candidates), arguments.dmenu_invocation) + + # Nothing was selected, simply return + if not selection: + return ExitCodes.SUCCESS + + # If username-target is path and user asked for username-only, we don't need to run pass. + # Or if using otp-only, it will run pass on its own. + secret = None + if ( + not (arguments.username_target == "path" and arguments.username_only) + and not arguments.otp_only + ): + secret = pass_(selection) + username_target = selection if arguments.username_target == "path" else secret + try: + if arguments.username_only: + fake_key_raw(extract_username(username_target, arguments.username_pattern)) + elif arguments.password_only: + fake_key_raw(extract_password(secret, arguments.password_pattern)) + elif arguments.otp_only: + otp = pass_otp(selection) + fake_key_raw(otp) + else: + # Enter username and password using fake-key and <Tab> (which seems to work almost universally), then switch + # back into insert-mode, so the form can be directly submitted by hitting enter afterwards + fake_key_raw(extract_username(username_target, arguments.username_pattern)) + qute_command("fake-key <Tab>") + fake_key_raw(extract_password(secret, arguments.password_pattern)) + except CouldNotMatchPassword as e: + stderr("Failed to match password, target: secret, error: {}".format(e)) + return ExitCodes.COULD_NOT_MATCH_PASSWORD + except CouldNotMatchUsername as e: + stderr( + "Failed to match username, target: {}, error: {}".format( + arguments.username_target, e + ) + ) + return ExitCodes.COULD_NOT_MATCH_USERNAME + + if arguments.insert_mode: + qute_command("mode-enter insert") + + return ExitCodes.SUCCESS + + +if __name__ == "__main__": + arguments = argument_parser.parse_args() + sys.exit(main(arguments)) diff --git a/ar/.config/qutebrowser/userscripts/translate b/ar/.config/qutebrowser/userscripts/translate new file mode 100755 index 0000000..25c66dd --- /dev/null +++ b/ar/.config/qutebrowser/userscripts/translate @@ -0,0 +1,116 @@ +#! /usr/bin/env python3 + +import argparse +import json +import os +import sys +import urllib.parse + +import requests + + +def js(message): + return f""" + (function() {{ + var box = document.createElement('div'); + box.style.position = 'fixed'; + box.style.bottom = '10px'; + box.style.right = '10px'; + box.style.backgroundColor = 'white'; + box.style.color = 'black'; + box.style.borderRadius = '8px'; + box.style.padding = '10px'; + box.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; + box.style.zIndex = '10000'; + box.innerText = decodeURIComponent("{message}"); + document.body.appendChild(box); + + function removeBox(event) {{ + if (!box.contains(event.target)) {{ + box.remove(); + document.removeEventListener('click', removeBox); + }} + }} + document.addEventListener('click', removeBox); + }})(); + """ + + +def translate_google(text, target_lang): + encoded_text = urllib.parse.quote(text) + response = requests.get( + f"https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl={target_lang}&dt=t&q={encoded_text}" + ) + response_json = json.loads(response.text) + translated_text = "" + for i in response_json[0]: + translated_text += i[0] + return translated_text + + +def translate_libretranslate(text, url, key, target_lang): + response = requests.post( + f"{url}/translate", + data={"q": text, "source": "auto", "target": target_lang, "api_key": key}, + ) + return response.json()["translatedText"] + + +def main(): + parser = argparse.ArgumentParser( + description="Translate text using different providers." + ) + parser.add_argument( + "--provider", + choices=["google", "libretranslate"], + required=False, + default="google", + help="Translation provider to use", + ) + parser.add_argument( + "--libretranslate_url", + required=False, + default="https://libretranslate.com", + help="URL for LibreTranslate API", + ) + parser.add_argument( + "--libretranslate_key", + required=False, + default="", + help="API key for LibreTranslate", + ) + parser.add_argument( + "--target_lang", + required=False, + default="en", + help="Target language for translation", + ) + args = parser.parse_args() + + qute_fifo = os.getenv("QUTE_FIFO") + if not qute_fifo: + sys.stderr.write( + f"Error: {sys.argv[0]} can not be run as a standalone script.\n" + ) + sys.stderr.write( + "It is a qutebrowser userscript. In order to use it, call it using 'spawn --userscript' as described in qute://help/userscripts.html\n" + ) + sys.exit(1) + + text = os.getenv("QUTE_SELECTED_TEXT", "") + + if args.provider == "google": + translated_text = translate_google(text, args.target_lang) + elif args.provider == "libretranslate": + translated_text = translate_libretranslate( + text, args.libretranslate_url, args.libretranslate_key, args.target_lang + ) + + js_code = js(urllib.parse.quote(translated_text)).replace("\n", " ") + + with open(qute_fifo, "a") as fifo: + fifo.write(f"jseval -q {js_code}\n") + + +if __name__ == "__main__": + main() diff --git a/ar/.local/bin/bookmarks b/ar/.local/bin/bookmarks index c365095..1e5cfbf 100755 --- a/ar/.local/bin/bookmarks +++ b/ar/.local/bin/bookmarks @@ -122,10 +122,9 @@ openinbrowser() { case "$BROWSER" in *qutebrowser*) sqlite_query=" - SELECT DISTINCT h.title - FROM History h - WHERE h.redirect=1 - ORDER BY h.atime DESC + SELECT substr(h.title, 1, $cols) || ' | ' || h.url AS bookmark + FROM CompletionHistory h + ORDER BY h.last_atime DESC LIMIT 100; " ;; diff --git a/ar/.local/bin/umpv b/ar/.local/bin/umpv deleted file mode 100755 index da4a767..0000000 --- a/ar/.local/bin/umpv +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python3 - -""" -This script emulates "unique application" functionality. When starting -playback with this script, it will try to reuse an already running instance of -mpv (but only if that was started with umpv). Other mpv instances (not started -by umpv) are ignored, and the script doesn't know about them. - -This only takes filenames as arguments. Custom options can't be used; the script -interprets them as filenames. If mpv is already running, the files passed to -umpv are appended to mpv's internal playlist. If a file does not exist or is -otherwise not playable, mpv will skip the playlist entry when attempting to -play it (from the GUI perspective, it's silently ignored). - -If mpv isn't running yet, this script will start mpv and let it control the -current terminal. It will not write output to stdout/stderr, because this -will typically just fill ~/.xsession-errors with garbage. - -mpv will terminate if there are no more files to play, and running the umpv -script after that will start a new mpv instance. - -Note: you can supply custom mpv path and options with the MPV environment - variable. The environment variable will be split on whitespace, and the - first item is used as path to mpv binary and the rest is passed as options - _if_ the script starts mpv. If mpv is not started by the script (i.e. mpv - is already running), this will be ignored. -""" - -import os -import shlex -import socket -import string -import subprocess -import sys -from collections.abc import Iterable -from typing import BinaryIO - - -def is_url(filename: str) -> bool: - parts = filename.split("://", 1) - if len(parts) < 2: - return False - # protocol prefix has no special characters => it's an URL - allowed_symbols = string.ascii_letters + string.digits + "_" - prefix = parts[0] - return all(c in allowed_symbols for c in prefix) - -def get_socket_path() -> str: - if os.name == "nt": - return r"\\.\pipe\umpv" - - base_dir = ( - os.getenv("UMPV_SOCKET_DIR") or - os.getenv("XDG_RUNTIME_DIR") or - os.getenv("HOME") or - os.getenv("TMPDIR") - ) - - if not base_dir: - raise Exception("Could not determine a base directory for the socket. " - "Ensure that one of the following environment variables is set: " - "UMPV_SOCKET_DIR, XDG_RUNTIME_DIR, HOME or TMPDIR.") - - return os.path.join(base_dir, ".umpv") - -def send_files_to_mpv(conn: socket.socket | BinaryIO, files: Iterable[str]) -> None: - try: - send = conn.send if isinstance(conn, socket.socket) else conn.write - for f in files: - f = f.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") - send(f'raw loadfile "{f}" append-play\n'.encode()) - except Exception: - print("mpv is terminating or the connection was lost.", file=sys.stderr) - sys.exit(1) - -def start_mpv(files: Iterable[str], socket_path: str) -> None: - mpv = "mpv" if os.name != "nt" else "mpv.exe" - mpv_command = shlex.split(os.getenv("MPV", mpv)) - mpv_command.extend([ - "--profile=builtin-pseudo-gui", - f"--input-ipc-server={socket_path}", - "--", - ]) - mpv_command.extend(files) - subprocess.Popen(mpv_command, start_new_session=True) - -def main() -> None: - files = (os.path.abspath(f) if not is_url(f) else f for f in sys.argv[1:]) - socket_path = get_socket_path() - - try: - if os.name == "nt": - with open(socket_path, "r+b", buffering=0) as pipe: - send_files_to_mpv(pipe, files) - else: - with socket.socket(socket.AF_UNIX) as sock: - sock.connect(socket_path) - send_files_to_mpv(sock, files) - except (FileNotFoundError, ConnectionRefusedError): - start_mpv(files, socket_path) - -if __name__ == "__main__": - main() |
