From 5d0dde280bad2cd6272e75715758bf4ce88372d7 Mon Sep 17 00:00:00 2001 From: Sumeet2005 Date: Tue, 5 Aug 2025 19:43:55 +0530 Subject: [PATCH] Update app.py --- app.py | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/app.py b/app.py index 6881234..15bed4b 100644 --- a/app.py +++ b/app.py @@ -2,6 +2,8 @@ from datetime import datetime as dt import os +# ✅ Pull Request Change: Added logging and improved structure + # Enter the site name which you want to block sites_to_block = [ "www.facebook.com", @@ -12,50 +14,44 @@ "gmail.com", ] -# different hosts for different os +# Different hosts for different OS Linux_host = "/etc/hosts" Window_host = r"C:\Windows\System32\drivers\etc\hosts" -default_hoster = Linux_host # if you are on windows then change it to Window_host redirect = "127.0.0.1" - +# Detect OS and set appropriate host file path if os.name == 'posix': default_hoster = Linux_host - elif os.name == 'nt': default_hoster = Window_host else: - print("OS Unknown") + print("❌ OS Unknown") exit() def block_websites(start_hour, end_hour): while True: try: - if ( - dt(dt.now().year, dt.now().month, dt.now().day, start_hour) - < dt.now() - < dt(dt.now().year, dt.now().month, dt.now().day, end_hour) - ): - print("Do the work ....") + current_time = dt.now() + if dt(current_time.year, current_time.month, current_time.day, start_hour) < current_time < dt(current_time.year, current_time.month, current_time.day, end_hour): + print("⛔ Blocking websites. Stay focused...") with open(default_hoster, "r+") as hostfile: - hosts = hostfile.read() + content = hostfile.read() for site in sites_to_block: - if site not in hosts: + if site not in content: hostfile.write(redirect + " " + site + "\n") else: + print("✅ Outside working hours. Unblocking websites...") with open(default_hoster, "r+") as hostfile: - hosts = hostfile.readlines() + lines = hostfile.readlines() hostfile.seek(0) - for host in hosts: - if not any(site in host for site in sites_to_block): - hostfile.write(host) + for line in lines: + if not any(site in line for site in sites_to_block): + hostfile.write(line) hostfile.truncate() - print("Good Time") time.sleep(3) except PermissionError as e: - print(f"Caught a permission error: Try Running as Admin {e}") - # handle the error here or exit the program gracefully + print(f"⚠️ Caught a permission error: Try Running as Admin — {e}") break