From b276970eb3cbdedc80bc81dc9465689a821d05aa Mon Sep 17 00:00:00 2001 From: Pawel Kos Date: Tue, 13 May 2025 14:11:33 +0200 Subject: [PATCH] app; Improve Modularity Refactor: Move OS detection and time check into reusable functions. -Replace inline OS host path logic with get_hosts_path() for clarity and reuse -Move datetime range check into is_work_time() to simplify main loop --- app.py | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/app.py b/app.py index 6881234..1a0dc68 100644 --- a/app.py +++ b/app.py @@ -2,6 +2,15 @@ from datetime import datetime as dt import os +def get_hosts_path(): + if os.name == 'posix': + return "/etc/hosts" + elif os.name == 'nt': + return r"C:\Windows\System32\drivers\etc\hosts" + else: + raise OSError("Unsupported operating system.") + + # Enter the site name which you want to block sites_to_block = [ "www.facebook.com", @@ -13,30 +22,24 @@ ] # 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 +default_hoster = get_hosts_path() #get the correct host path depending on if you're using linux or windows redirect = "127.0.0.1" -if os.name == 'posix': - default_hoster = Linux_host - -elif os.name == 'nt': - default_hoster = Window_host -else: - print("OS Unknown") - exit() +def is_work_time(start_hour, end_hour): + now = dt.now() + start = dt(now.year, now.month, now.day, start_hour) + end = dt(now.year, now.month, now.day, end_hour) + if start_hour < end_hour: + return start <= now < end + else: + return not (end <= now < start) # handles overnight shifts 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) - ): + if is_work_time(start_hour, end_hour): print("Do the work ....") with open(default_hoster, "r+") as hostfile: hosts = hostfile.read() @@ -59,5 +62,6 @@ def block_websites(start_hour, end_hour): break + if __name__ == "__main__": block_websites(9, 21)