Created
March 10, 2024 16:43
-
-
Save jfacoustic/b8a9edfb83705c6de5daaddd1338bcaa to your computer and use it in GitHub Desktop.
Python UI Website Blocker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from PySide6.QtWidgets import ( | |
QApplication, | |
QMessageBox, | |
QWidget, | |
QLabel, | |
QPushButton, | |
QVBoxLayout, | |
QPlainTextEdit | |
) | |
app = QApplication([]) | |
app.setStyle('macos') | |
window = QWidget() | |
v_layout = QVBoxLayout() | |
cancelBtn = QPushButton('Cancel') | |
saveBtn = QPushButton('Save') | |
textBox = QPlainTextEdit() | |
f = open("/etc/hosts") | |
etc_contents = f.read() | |
f.close() | |
backup = open('/etc/.hosts_backup', 'a') | |
backup.truncate(0) | |
backup.write(etc_contents) | |
backup.close() | |
do_not_delete = etc_contents.split("# BLOCK_SITES\n")[0] | |
block_sites_segment = etc_contents.split("# BLOCK_SITES\n")[1] | |
blocked_sites_lines = block_sites_segment.split('\n') | |
def parse_urls(blocked_site_lines): | |
result = [] | |
for line in blocked_sites_lines: | |
if(line.startswith('127.0.0.1')): | |
result.append(line.split(' ')[1]) | |
return result | |
urls = parse_urls(blocked_sites_lines) | |
print(urls) | |
textBox.setPlainText('\n'.join(urls)) | |
v_layout.addWidget(QLabel('Block Sites')) | |
v_layout.addWidget(textBox) | |
v_layout.addWidget(cancelBtn) | |
v_layout.addWidget(saveBtn) | |
def on_cancel(): | |
QApplication.closeAllWindows() | |
def format_urls(urls): | |
result = [] | |
for url in urls: | |
result.append('127.0.0.1 ' + url + '\n') | |
result.append(url + ' 127.0.0.1 \n') | |
return result | |
def on_save(): | |
new_urls = textBox.toPlainText().split('\n') | |
new_contents = ''.join([do_not_delete, '# BLOCK_SITES\n', *format_urls(new_urls)]) | |
f = open('/etc/hosts', 'a') | |
f.truncate(0) | |
f.write(new_contents) | |
f.close() | |
alert = QMessageBox() | |
alert.setText('Saved Blocked Sites') | |
alert.exec() | |
cancelBtn.clicked.connect(on_cancel) | |
saveBtn.clicked.connect(on_save) | |
window.setLayout(v_layout) | |
window.show() | |
app.exec() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment