From 718a3ce3eb25cebc6a45e09ef5bc88410fe4ee6f Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Tue, 19 Oct 2021 20:20:50 -0400 Subject: [PATCH] Terminate blockers that are already running. --- blocker.py | 45 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/blocker.py b/blocker.py index 3a1a41d..18aca70 100755 --- a/blocker.py +++ b/blocker.py @@ -7,7 +7,8 @@ import subprocess import sys import time - +BLOCKER = "blocker.py" +BLOCKER_CONFIG_DIR = "/home/{}/.config/focusfriend" BLOCKED_BROWSER_WORDS = ["mogelpower", "DER SPIEGEL", "nitter"] @@ -63,7 +64,44 @@ def notify(message): p = subprocess.run(CMD, env=env) -def main(): +def get_config_dir() -> str: + user = os.environ["SUDO_USER"] + config_dir = BLOCKER_CONFIG_DIR.format(user) + assert(os.path.isdir(config_dir)) + return config_dir + + +def write_pid_file() -> str: + p = psutil.Process() + pid_file = os.path.join(get_config_dir(), f"{p.pid}.pid") + with open(pid_file, "w") as f: + f.write(pid_file) + return pid_file + + +def terminate_existing_blocker() -> None: + this_pid = psutil.Process().pid + config_dir = get_config_dir() + pid_files = [f for f in os.listdir(config_dir) if f.endswith(".pid")] + for pid_file in pid_files: + pid = int(pid_file.replace(".pid", "")) + if this_pid == pid: + continue + try: + p = psutil.Process(pid) + p.terminate() + except psutil.NoSuchProcess: + pass + os.remove(os.path.join(config_dir, pid_file)) + + +def init() -> None: + terminate_existing_blocker() + write_pid_file() + + +def main() -> None: + init() blocked = [re.compile(f"{word}.*(Firefox|Chromium)", flags=re.IGNORECASE) for word in BLOCKED_BROWSER_WORDS] while True: @@ -79,6 +117,5 @@ if __name__ == "__main__": if newpid == 0: main() else: - cmd = ["sudo"] + sys.argv + cmd = ["sudo", BLOCKER] + sys.argv[1:] subprocess.Popen(cmd) -