From f6f0715cb34375b96024386447c30235200b61d5 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Thu, 14 Oct 2021 14:32:19 -0400 Subject: [PATCH] Blocker script sends notification before killing a program. --- blocker.py | 52 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 10 deletions(-) mode change 100644 => 100755 blocker.py diff --git a/blocker.py b/blocker.py old mode 100644 new mode 100755 index 9d84edb..e97bb75 --- a/blocker.py +++ b/blocker.py @@ -8,11 +8,9 @@ import sys import time -XDOTOOL_CMD = ["xdotool", "getactivewindow", "getwindowname", "getwindowpid"] +BLOCKED_BROWSER_WORDS = ["mogelpower", "nitter", "spon"] -BLOCKED_BROWSER_WORDS = [] - def is_window_blocked(window_name, blocked): for b in blocked: if type(b) is str and b == window_name: @@ -22,19 +20,53 @@ def is_window_blocked(window_name, blocked): return False +def get_active_window_name_and_pid(): + CMD = ["xdotool", "getactivewindow", "getwindowname", "getwindowpid"] + p = subprocess.run(CMD, capture_output=True) + if p.returncode != 0: + return "", "" + window_name, window_pid, _ = p.stdout.decode().split("\n") + return window_name, window_pid + + +def find_window_name(window_name): + CMD = ["xdotool", "search", window_name, "getwindowpid"] + p = subprocess.run(CMD, capture_output=True) + if p.returncode != 0: + return "" + l = p.stdout.decode().split("\n") + print(l) + + +def init_kill_sequence(blocked): + count = 5 + while True: + window_name, window_pid = get_active_window_name_and_pid() + if not is_window_blocked(window_name, blocked): + notify(f"{window_name} is okay. Return from kill sequence.") + return + notify(f"{window_name} is blocked. Kill in {count} seconds.") + if count == 0: + p = psutil.Process(int(window_pid)) + p.kill() + return + time.sleep(1) + count -= 1 + + +def notify(message): + CMD = ["runuser", "-u", "felixm", "notify-send", message] + p = subprocess.run(CMD) + + def main(): blocked = [re.compile(f"{word}.*(Firefox|Chromium)", flags=re.IGNORECASE) for word in BLOCKED_BROWSER_WORDS] while True: time.sleep(1) - p = subprocess.run(XDOTOOL_CMD, capture_output=True) - if p.returncode != 0: - continue - window_name, window_pid, _ = p.stdout.decode().split("\n") + window_name, window_pid = get_active_window_name_and_pid() if is_window_blocked(window_name, blocked): - p = psutil.Process(int(window_pid)) - p.kill() - print(f"Kill {window_name}") + init_kill_sequence(blocked) if __name__ == "__main__":