Terminate blockers that are already running.
This commit is contained in:
45
blocker.py
45
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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user