def format_host_meta(host, meta, terse=False): ips = meta.get('ips') if not ips: notify("[sshmenu]", "missing '{ips}' attribute for '{host}'", urgency=URGENCY_CRITICAL) sys.exit(1) ip = ips[0] user = meta.get("user") port = meta.get("port") result = f"{' -l ' + user if user else ''}{' -p ' + str(port) if port else ''} {ip}" if terse: result = f"{user + '@' if user else ''}{ip}{':' + str(port) if port else ''}" return result
def list_jump_hosts(host_meta, extra_hosts_data): result = [] meta = host_meta while True: jump = meta.get("jump") if not jump: break jump_meta = extra_hosts_data.get(jump) if not jump_meta: notify("[sshmenu]", "missing host definition for `{jump}`", urgency=URGENCY_CRITICAL) sys.exit(1) jump_meta.update({"host": jump}) result.insert(0, jump_meta) meta = jump_meta return result
def is_today_holiday(): # TODO: assert calendar is for intended year r = redis.Redis(host='localhost', port=6379, db=0) if not r.exists(args.cache_key_name): notify(f"[scheduling]", "no holidays data, update calendar beforehand", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) fcalendar = json.loads(r.get(args.cache_key_name)) today = date.today() if fcalendar["year"] != today.year: notify(f"[scheduling]", "wrong calendar year, update calendar correctly", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) is_holiday = False for month in fcalendar["months"]: if today.month == month["month"]: if today.day in month["days"]: is_holiday = True break return is_holiday
def issue_log_work(issue): unloddeg_dates = [ datetime.strftime(d, "%d/%m/%y") for d in issue_get_unlogged_dates(issue) ] date_to_log = get_selection(sorted(unloddeg_dates), 'date', case_insensitive=True, lines=15, font="@wmFontDmenu@") if not date_to_log: notify("[jira]", f"Cancelled logging work for `{issue.key}`", urgency=URGENCY_CRITICAL) sys.exit(1) started = datetime.combine(datetime.strptime(date_to_log, "%d/%m/%y"), datetime.now().time()) amount, comment = None, None while not comment: result = worklog_get_amount_and_comment() if result: amount, comment = result.split("|")[:-1] if not comment: notify("[jira]", f"comment in worklog is mandatory'", urgency=URGENCY_CRITICAL) else: break if amount and comment: tz = pytz.timezone("@systemTimeZone@") started_with_tz = tz.localize(started) wlog = client.add_worklog(issue, timeSpent=amount, started=started_with_tz, comment=comment) notify( "[jira]", f"Logged `{amount}` of work for `{issue.key}` at {date_to_log}'", urgency=URGENCY_NORMAL)
r.delete("system/services") sys.exit(0) if not r.exists("system/services"): r.lpush("system/services", *list_units()) service = get_selection(sorted( list( dict.fromkeys([ service.decode() for service in r.lrange("system/services", 0, -1) ]))), 'service', lines=20, font="@wmFontDmenu@") if not service: sys.exit(1) operation = get_selection(operations, '> ', lines=5, font="@wmFontDmenu@") if not operation: sys.exit(1) if operation in ["journal", "status"]: unit_show(service, operation, user=('user' in service), shell=["@defaultTerminal@", "-e"], tmux_session="@tmuxDefaultSession@") switch_desktop(1) else: unit_perform(service, operation, user=('user' in service)) notify(f"[srvctl :: {operation}]", f"{service}", timeout=5000)
import json import redis from pystdlib.uishim import notify, URGENCY_NORMAL, URGENCY_CRITICAL from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) macs = json.loads(r.get("networking/wireless/headsets")) notify(f"[BT battery]", "Please wait...", urgency=URGENCY_NORMAL, timeout=5000) result = [] for mac in sorted(macs): output = shell_cmd(f"bluetooth_battery {mac}").strip() if "offline" in output: result.append(f"{mac}: offline") else: result.append(f"{mac}: {output.split(' ')[-1]}") if result: notify(f"[BT battery]", "\n".join(result), urgency=URGENCY_NORMAL, timeout=3000) else: notify(f"[BT battery]", "error getting headset(s) battery level(s)", urgency=URGENCY_CRITICAL, timeout=3000)
session_name = get_selection([], "save as", lines=1, font="@wmFontDmenu@") if not session_name: sys.exit(1) page_content = urlopen(page_url) soup = BeautifulSoup(page_content, "html.parser") tags = soup.findAll("a", attrs={"href": re.compile("^https?://")}) org_content = [ f"#+TITLE: {soup.title.string}\n", f"#+PROPERTY: url {page_url}\n" ] for tag in tags: org_content.append(f"* {tag.get('href')}\n") with open(f"@firefoxSessionsPath@/{session_name}.org", "w") as f: f.writelines(org_content) notify("[scrape]", f"Scraped {len(org_content) - 2} links", timeout=5000) for line in org_content: print(line) else: print(page_url) notify("[scrape]", "Non-URL content in clipboard, skipping", timeout=5000) # TODO: add fallback/primary option of checking current window title for url regexp and treat any (first) # match as url to process
urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) is_holiday = False for month in fcalendar["months"]: if today.month == month["month"]: if today.day in month["days"]: is_holiday = True break return is_holiday if args.cmd == "update": update_calendar_cache(next_year=(args.update_year != "current")) if args.cmd == "check": if args.check_dry_run: is_holiday = is_today_holiday() notify(f"[scheduling]", f"Today is {'holiday' if is_holiday else 'not holiday'}", urgency=URGENCY_NORMAL, timeout=5000) sys.exit(0) if not args.check_cmd: notify(f"[scheduling]", "no command to wrap", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if not is_today_holiday(): shell_cmd(args.check_cmd, oneshot=True)
import argparse import sys from pystdlib.uishim import get_selection_rofi, notify, URGENCY_CRITICAL from pystdlib import shell_cmd from pystdlib.browser import collect_sessions, collect_sessions_with_size, \ collect_session_urls, init_mgmt_argparser, open_urls_firefox, rotate_sessions parser = init_mgmt_argparser() parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font") args = parser.parse_args() if not args.sessions_path: notify("[Firefox]", f"No sessions base path provided", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if args.save_session: session_name = get_selection_rofi([], "save as") if session_name: shell_cmd(f"dump_firefox_session {session_name}") elif args.open_session: session_name = get_selection_rofi(sorted(collect_sessions(args.sessions_path)), "open") if session_name: urls, _ = collect_session_urls(args.sessions_path, session_name) if len(urls) > 0: shell_cmd(f"emacsclient -c {args.sessions_path}/{session_name}") elif args.edit_session: session_name = get_selection_rofi(sorted(collect_sessions(args.sessions_path)), "edit") if session_name: shell_cmd(f"emacsclient -c {args.sessions_path}/{session_name}") elif args.delete_session:
import json import sys import redis from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL from pystdlib.shell import tmux_create_window from pystdlib import shell_cmd r = redis.Redis(host='localhost', port=6379, db=0) dbms_meta = json.loads(r.get("misc/dbms_meta")) extra_hosts_data = json.loads(r.get("net/extra_hosts")) if not len(dbms_meta): notify("[dbms]", "No entries", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) dbms_entry = get_selection(dbms_meta.keys(), "", lines=5, font="@wmFontDmenu@") if dbms_entry: dbms_pass = None if dbms_meta[dbms_entry].get("passwordPassPath"): # using pass dbms_pass = shell_cmd( f'pass {dbms_meta[dbms_entry]["passwordPassPath"]}', split_output="\n")[0] elif dbms_meta[dbms_entry].get("password"): # password in plaintext dbms_pass = dbms_meta[dbms_entry].get("password") else: notify("[dbms]", f"No password provided for '{dbms_entry}'", urgency=URGENCY_CRITICAL, timeout=5000)
from pystdlib.shell import tmux_create_window from pystdlib import shell_cmd service_modes = ["status", "logs"] r = redis.Redis(host='localhost', port=6379, db=0) extra_hosts_data = json.loads(r.get("net/extra_hosts")) swarm_meta = json.loads(r.get("virt/swarm_meta")) swarm = get_selection(swarm_meta.keys(), "swarm", case_insensitive=True, lines=5, font="@wmFontDmenu@") if not swarm: notify("[virt]", "No swarm selected") sys.exit(0) swarm_host = swarm_meta[swarm] os.environ["DOCKER_HOST"] = f"ssh://{swarm_host}" host_meta = extra_hosts_data.get(swarm_host, None) if not host_meta: notify("[docker]", f"Host '{swarm_host}' not found", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) host_vpn = host_meta.get("vpn", None) if host_vpn: shell_cmd(f"vpnctl --start {host_vpn}")
def stop_service(name, meta): result = False if meta["type"] == "ovpn": tun_path = IPV4_STATUS_PATH + meta["dev"] if not os.path.exists(tun_path): r.set(f"vpn/{name}/is_up", "no") result = True if args.verbose: notify("[VPN]", f"`{name}` is down") else: vpn_stop_task = subprocess.Popen(meta["down"], shell=True, stdout=subprocess.PIPE) if vpn_stop_task.wait() == 0: while os.path.exists(tun_path): time.sleep(1) r.set(f"vpn/{name}/is_up", "no") result = True if args.verbose: notify("[VPN]", f"`{name}` is down") else: r.set(f"vpn/{name}/is_up", "unk") result = False notify("[VPN]", f"error stopping `{name}`\n\n{vpn_stop_task.stdout.read().decode()}", urgency=URGENCY_CRITICAL, timeout=5000) elif meta["type"] == "ipsec": if not is_nm_vpn_up(name): r.set(f"vpn/{name}/is_up", "no") result = True if args.verbose: notify("[VPN]", f"`{name}` is down") else: vpn_stop_task = subprocess.Popen(meta["down"], shell=True, env={'LANGUAGE':'en_US.en'}, stdout=subprocess.PIPE, stderr=subprocess.PIPE) vpn_stop_result = vpn_stop_task.wait() if vpn_stop_result != 0: vpn_stderr = vpn_stop_task.stderr.read().decode().strip().split() if "not an active" in " ".join(vpn_stderr): r.set(f"vpn/{name}/is_up", "no") result = True if args.verbose: notify("[VPN]", f"`{name}` is down") else: r.set(f"vpn/{name}/is_up", "unk") result = False notify("[VPN]", f"error stopping `{name}`\n\n{' '.join(vpn_stderr)}", urgency=URGENCY_CRITICAL, timeout=5000) else: r.set(f"vpn/{name}/is_up", "no") result = True if args.verbose: notify("[VPN]", f"`{name}` is down") else: result = False notify("[VPN]", f"Unknown service type of '{name}': {meta['type']}", urgency=URGENCY_CRITICAL, timeout=5000) return result
return result def stop_running(omit=None): devdns_stop_task = subprocess.Popen("systemctl stop docker-devdns.service", shell=True, stdout=subprocess.PIPE) assert devdns_stop_task.wait() == 0 if omit: del vpn_meta[omit] for vpn, meta in vpn_meta.items(): stop_service(vpn, meta) if args.vpn_service_tag: meta = vpn_meta.get(args.vpn_service_tag, None) if not meta: notify("[VPN]", f"Cannot find {args.vpn_service_tag} service", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) if r.get(f"vpn/{args.vpn_service_tag}/is_up") != "yes": stop_running(omit=args.vpn_service_tag) start_service(args.vpn_service_tag, meta) elif args.stop_running: stop_running() elif args.vpn_status: statuses = {} for key in r.scan_iter("vpn/*/is_up"): value = r.get(key) statuses[key.decode().split("/")[1]] = value.decode() notify("[VPN]", "\n".join([f"{key}: {value}" for key, value in statuses.items()]), urgency=URGENCY_NORMAL, timeout=5000)
host_meta = extra_hosts_data[host] host_vpn = host_meta.get("vpn") if host_vpn: shell_cmd(f"vpn --start {host_vpn}") jump_hosts = list_jump_hosts(host_meta, extra_hosts_data) cmd = f"ssh {' '.join(['-J ' + format_host_meta(host_meta['host'], host_meta, terse=True) for host_meta in jump_hosts])} {format_host_meta(host, host_meta)}" if args.show_choices: command_choices = json.loads(r.get("net/command_choices")) choice = get_selection_rofi(command_choices, "execute") if choice: cmd += f" -t '{choice}'" else: sys.exit(1) if args.ignore_tmux: term_create_window(cmd, term_cmd=args.term_command) else: target_session = host_meta.get("tmux", args.tmux_session) result = tmux_create_window(cmd, session_name=target_session, window_title=f"ssh :: {host}", attach=False) if not result: notify("[sshmenu]", "error creating tmux window", urgency=URGENCY_CRITICAL) sys.exit(1) else: result = term_create_window(f"tmux attach -t {target_session}", term_cmd=args.term_command)
dest="dump_basename", default="firefox-session-auto", type=str, help="Dump basename") parser.add_argument( '--sessionstore', dest="sessionstore_path", default= f"{os.getenv('HOME')}/.mozilla/firefox/profile.default/sessionstore-backups", type=str, help="Session store path") args = parser.parse_args() if not args.dump_path: notify(f"[Firefox]", f"Cannot guess dump path, exiting...", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) session_previous = args.sessionstore_path + "/previous.jsonlz4" session_recovery = args.sessionstore_path + "/recovery.jsonlz4" session_dbfile = session_previous if os.path.exists(session_recovery) and os.path.isfile(session_recovery): session_dbfile = session_recovery session_dumpfile = args.dump_basename + f"-{datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')}.org" if args.dump_name: session_dumpfile = f"{args.dump_name}.org" result = []
import os import re import sys from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL pattern = "\(.*\)" deps_dict = {} go_mod_path = os.getcwd() + "/go.mod" if not (os.path.exists(go_mod_path) and os.path.isfile(go_mod_path)): notify("[modedit]", "No go.mod found", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) with open(go_mod_path, "r") as f: deps_list = re.search(pattern, f.read(), re.DOTALL).group(0).split("\n")[1:-1] deps_list = [dep for dep in deps_list if not dep.startswith("//")] deps_list = [dep for dep in deps_list if dep.startswith("\t")] for dep in deps_list: deps_dict[dep.split()[0]] = dep.split()[1] dep_path = get_selection(deps_dict.keys(), "replace", case_insensitive=True, lines=10, font="@wmFontDmenu@") if not dep_path: notify("[modedit]", "Nothing selected", timeout=5000) sys.exit(0) dep_path_local = "@globalWorkspaceRoot@/" + dep_path if dep_path_local.endswith(".git"): dep_path_local = dep_path_local[:-4]
import sys from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL from pystdlib.shell import tmux_create_window from pystdlib import shell_cmd keyword_result = get_selection([], 'keyword', font="@wmFontDmenu@") if not keyword_result: notify("[search repos]", "no keyword provided", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) matching_repos = shell_cmd(f"fd -t d -d @searchDepth@ {keyword_result} @searchReposRoot@", split_output="\n") selected_repo = get_selection(matching_repos, 'repo', case_insensitive=True, lines=10, font="@wmFontDmenu@") if not selected_repo: notify("[search repos]", "no repository selected", timeout=5000) sys.exit(0) elisp_cmd = f'(dired "{selected_repo}")' emacs_cmd = f'emacsclient -c -s /run/user/1000/emacs/server -e \'{elisp_cmd}\'' # TODO: make SPOT for socket path shell_cmd(emacs_cmd)
notify("[jira]", f"`View git branch` not implemented yet", urgency=URGENCY_CRITICAL) sys.exit(1) OPS = { "View in browser": issue_view_in_browser, "Log work": issue_log_work, "Change status": issue_make_transition, "View git branch": issue_view_git_branch } identity = select_identity() if not identity: notify("[jira]", "invalid identity", urgency=URGENCY_CRITICAL) sys.exit(1) client = get_client(server=identity["jira"]["server"], auth=tuple(identity["jira"]["creds"])) issues = get_issues(client, identity["jira"]["project"]) issue = select_issue(issues) if not issue: notify("[jira]", "No issue selected", urgency=URGENCY_NORMAL) sys.exit(0) op = get_selection(OPS.keys(), '>', case_insensitive=True, lines=5,
case_insensitive=True, lines=10, font="@wmFontDmenu@") if not selected_container: sys.exit(1) container_ip = shell_cmd( f"docker inspect {selected_container} --format='{ip_address_format}'") container_ports = shell_cmd( f"docker inspect {selected_container} --format='{ports_format}'", split_output="\n") port_result = None for port in container_ports_result: port_number = port.split("/")[0] if port_number in port_cmd_mapping: port_result = port_number break if not port_result: notify( "[docker]", f"No suitable port between exposed:\n{'\n'.join(container_ports_result)}", timeout=5000) sys.exit(0) shell_cmd( f"{port_cmd_mapping[port_result]} http://{container_ip_result}:{port_result}" )
def issue_make_transition(issue): # NOTE: for API details refer to chapter 2.1.7 (Transitions) of documentation notify("[jira]", f"`Change status` not implemented yet", urgency=URGENCY_CRITICAL) sys.exit(1)
def is_valid_url(url): return re.search(URL_REGEX, url) is not None def fetch_tags_cloud(): tags_cloud = shell_cmd("buku --np --st", split_output="\n") return [ " ".join(tag.strip().split(" ")[1:-1]) for tag in tags_cloud if tag ] bookmark_text = shell_cmd("xsel -o -b") if bookmark_text is not None: if not is_valid_url(bookmark_text): notify("error", "URL is not valid", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) result = get_selection([bookmark_text], 'bookmark', font="@wmFontDmenu@") if not result: notify("OK", "Aborted adding bookmark", timeout=5000) sys.exit(1) tags_cloud = fetch_tags_cloud() bookmark_tags = [] while True: tag = get_selection(tags_cloud, 'add tag', lines=15, font="@wmFontDmenu@") if tag: bookmark_tags.append(tag)
def issue_view_git_branch(task): # TODO: ensure correct vpn state, parameterize vpn name notify("[jira]", f"`View git branch` not implemented yet", urgency=URGENCY_CRITICAL) sys.exit(1)
help="Fallback browser") parser.add_argument('--selector-font', dest="selector_font", type=str, help="Selector font") args = parser.parse_args() port_cmd_mapping = { "80": args.default_browser, "8080": args.default_browser, "8000": args.default_browser } if not (args.default_browser and args.fallback_browser): notify(f"[containers]", f"Browsers not set, exiting...", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) ip_address_format = "{{range $network, $settings :=.NetworkSettings.Networks}}{{$settings.IPAddress}}{{end}}" ports_format = "{{range $port, $mappings :=.NetworkSettings.Ports}}{{$port}}{{end}}" if "DOCKER_HOST" in os.environ: del os.environ["DOCKER_HOST"] # ensure we cosidering only local containers container_names = shell_cmd("docker ps --format '{{.Names}}'", split_output="\n") selected_container = get_selection_rofi(container_names, "container") if not selected_container: sys.exit(1)
import re import sys import time import redis from pystdlib import shell_cmd from pystdlib.shell import tmux_create_window from pystdlib.uishim import get_selection, notify, URGENCY_CRITICAL from pystdlib.xlib import switch_named_desktop r = redis.Redis(host='localhost', port=6379, db=0) bookmarks = json.loads(r.get("nav/bookmarks")) if not len(bookmarks): notify("[bookmarks]", "No entries", urgency=URGENCY_CRITICAL, timeout=5000) sys.exit(1) bookmark = get_selection(bookmarks.keys(), "", lines=15, font="@wmFontDmenu@") if bookmark: meta = bookmarks[bookmark] path = meta["path"] shell = meta.get("shell", None) if shell: tmux_session = meta.get("tmux", "@tmuxDefaultSession@") tmux_create_window(None, tmux_session, window_title=path.split("/")[-1], attach=True, start_directory=path) elisp_cmd = f'(dired "{path}")'