Skip to content

Update app.py #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 16 additions & 20 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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


Expand Down