this should work. added some icons and some more

This commit is contained in:
2025-09-23 09:57:44 +02:00
parent b668eb3d77
commit 32fc4dc119
14 changed files with 290 additions and 185 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
__pycache__ __pycache__
env

237
PyPost.py
View File

@@ -9,35 +9,29 @@ from marko.ext.gfm import GFM
from watchdog.observers import Observer from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler from watchdog.events import FileSystemEventHandler
from log.Logger import *
from hashes.obfuscation.Obfuscator import Obfuscator
from htmlhandler import htmlhandler as Handler
# Use absolute paths # Use absolute paths
ROOT = Path(os.path.abspath(".")) ROOT = Path(os.path.abspath("."))
MARKDOWN_DIR = ROOT / "markdown" MARKDOWN_DIR = ROOT / "markdown"
HTML_DIR = ROOT / "html" HTML_DIR = ROOT / "html"
# Create markdown parser with table support # Create markdown parser with table support
markdown_parser = marko.Markdown(extensions=[GFM]) markdown_parser = marko.Markdown(extensions=[GFM])
Logger = Logger()
# Long useless Lorem Ipsum comments # Global obfuscate flag, default True
LOREM_IPSUM_COMMENTS = [ obfuscate = True
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet.",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa.",
"gay furry pride >:3 OwO get rekt Charlie Kirk",
"Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.",
"Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias.",
"Nulla facilisi. Cras vehicula aliquet libero, sit amet lacinia nunc commodo eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae.",
"Proin euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl.",
"Vivamus euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl."
]
def render_markdown(md_path: Path): def render_markdown(md_path: Path):
"""Render a single markdown file to an obfuscated HTML file.""" """Render a single markdown file to an obfuscated HTML file."""
try: try:
text = md_path.read_text(encoding="utf-8") text = md_path.read_text(encoding="utf-8")
except Exception as e: except Exception as e:
print(f"Could not read {md_path}: {e}") Logger.log_error(f"Could not read {md_path}: {e}")
return return
html_body = markdown_parser.convert(text) html_body = markdown_parser.convert(text)
@@ -54,7 +48,7 @@ def render_markdown(md_path: Path):
from hashes.hashes import hash_list from hashes.hashes import hash_list
# Create clean HTML structure # Create clean HTML structure
clean_html = f"""<!doctype html> clean_html = f"""<!doctype html>
<html lang="en"> <html lang="en" style="height:100%; margin:0;">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>{title}</title> <title>{title}</title>
@@ -62,26 +56,34 @@ def render_markdown(md_path: Path):
<link rel="icon" type="image/x-icon" href="../css/favicon/favicon.ico"> <link rel="icon" type="image/x-icon" href="../css/favicon/favicon.ico">
<script src="../js/post/normal.js"></script> <script src="../js/post/normal.js"></script>
</head> </head>
<body> <body style="display:flex; flex-direction:column; min-height:100%; margin:0;">
<main class="container"> <main class="container" style="flex:1;">
<h1 onclick="window.location.href='/'" style="cursor:pointer">← {title}</h1> <h1 onclick="window.location.href='/'" style="cursor:pointer; display:flex; align-items:center; gap:8px; font-size:1.5em; margin:0;">
<div class="meta">Written@{time.asctime(time.localtime())}</div> <img src="../css/icons/back.png" width="32" height="32" alt="Back" style="display:block;" />
{title}
</h1>
<img src="../css/icons/written.png" width="32" height="32" alt="write_img" loading="lazy" style="vertical-align: middle;" />
<div class="meta" style="display: inline;">Written @{time.asctime(time.localtime())}</div>
<hr style="margin:10px 0;" /> <hr style="margin:10px 0;" />
{html_body} {html_body}
<footer style=" position: absolute;bottom: 0;width: 100%;">
<hr style="margin:10px 0;" />
{time.strftime("%Y-%m-%d %H:%M:%S")}<br/>
Hash 1 (<b>UTF-8</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("utf-8")).decode("utf-8")}</i><br />
Hash 2 (<b>ASCII</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("ascii")).decode("ascii")}</i><br />
<i>Decode Hashes to identify pages</i>
</footer>
</main> </main>
<footer style="margin-top:auto; width:100%;">
<hr style="margin:10px 0;" />
<img src="../css/icons/date.png" width="16" height="16" alt="date" loading="lazy" style="vertical-align: middle;" />
{time.strftime("%Y-%m-%d %H:%M:%S")}<br/>
<img src="../css/icons/magnifier.png" width="16" height="16" alt="Hash1" loading="lazy" style="display:inline; vertical-align:middle;" />
Hash 1 (<b>UTF-8</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("utf-8")).decode("utf-8")}</i><br />
<img src="../css/icons/magnifier.png" width="16" height="16" alt="Hash2" loading="lazy" style="display:inline; vertical-align:middle;" />
Hash 2 (<b>ASCII</b>)<i>:{base64.b64encode(random.choice(hash_list).encode("ascii")).decode("ascii")}</i><br />
<i>Decode Hashes to identify pages</i>
</footer>
</body> </body>
</html>""" </html>"""
# Obfuscate the HTML for browser output # Obfuscate the HTML for browser output
obfuscated_html = obfuscate_html(clean_html) obfuscated_html = Obfuscator.obfuscate_html(clean_html)
# Ensure html directory exists # Ensure html directory exists
HTML_DIR.mkdir(exist_ok=True) HTML_DIR.mkdir(exist_ok=True)
@@ -93,155 +95,28 @@ def render_markdown(md_path: Path):
# Create parent directories if needed # Create parent directories if needed
out_path.parent.mkdir(parents=True, exist_ok=True) out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(obfuscated_html, encoding="utf-8")
print(f"Rendered: {md_path} -> {out_path}")
if obfuscate:
out_path.write_text(obfuscated_html, encoding="utf-8")
else:
out_path.write_text(clean_html, encoding="utf-8")
def obfuscate_html(html_content): Logger.log_debug(f"Rendered: {md_path} -> {out_path}")
"""Working obfuscation that maintains functionality"""
import re
import random
# Generate random strings
def generate_random_string(length=8):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(random.choice(chars) for _ in range(length))
# Protect original content
protected_blocks = []
def protect_scripts(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_SCRIPT_{len(protected_blocks)-1} -->'
def protect_styles(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_STYLE_{len(protected_blocks)-1} -->'
# First pass: protect critical content
temp_html = re.sub(r'<script[^>]*>.*?</script>', protect_scripts, html_content, flags=re.DOTALL)
temp_html = re.sub(r'<style[^>]*>.*?</style>', protect_styles, temp_html, flags=re.DOTALL)
# Protect tables
def protect_tables(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_TABLE_{len(protected_blocks)-1} -->'
temp_html = re.sub(r'<table[^>]*>.*?</table>', protect_tables, temp_html, flags=re.DOTALL)
# Clean up HTML - remove extra whitespace
lines = []
for line in temp_html.split('\n'):
cleaned_line = ' '.join(line.split())
if cleaned_line:
lines.append(cleaned_line)
# Add comments between lines (but not too many)
obfuscated_lines = []
for i, line in enumerate(lines):
# Add comment before some lines
if line and not line.startswith('<!--') and random.random() > 0.7:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated_lines.append(line)
# Add comment after some lines
if line and not line.startswith('<!--') and random.random() > 0.8:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated = '\n'.join(obfuscated_lines)
# Inject random comments between SOME elements (not all)
def inject_some_comments(html):
# Only inject between certain safe elements
safe_patterns = [
(r'(</div>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</p>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</span>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h1>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h2>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h3>)', r'\1<!--' + generate_random_string(6) + '-->'),
]
for pattern, replacement in safe_patterns:
if random.random() > 0.5: # 50% chance to apply each pattern
html = re.sub(pattern, replacement, html)
return html
obfuscated = inject_some_comments(obfuscated)
# Add header comments (fewer to avoid breaking the document)
header_comments = [
'auto-obfuscated-' + generate_random_string(10),
'generated-' + generate_random_string(8),
]
header_block = '\n'.join([f'<!-- {comment} -->' for comment in header_comments])
obfuscated = header_block + '\n' + obfuscated
# Add footer comments
footer_comments = [
'end-' + generate_random_string(10),
'completed-' + generate_random_string(8),
]
footer_block = '\n'.join([f'<!-- {comment} -->' for comment in footer_comments])
obfuscated = obfuscated + '\n' + footer_block
# Minimal invisible characters - only in text content, not in tags
invisible_chars = ['\u200B', '\u200C']
def add_minimal_invisible(match):
text = match.group(1)
# NEVER obfuscate script-like content
if any(keyword in text for keyword in ['function', 'const ', 'var ', 'let ', 'document.', 'window.', 'getElement', 'querySelector', 'addEventListener']):
return '>' + text + '<'
# Only add to plain text content
if len(text) > 10: # Only on longer text blocks
result = []
for i, char in enumerate(text):
result.append(char)
# Very rarely add invisible chars
if i % 8 == 0 and i > 0 and random.random() > 0.8:
result.append(random.choice(invisible_chars))
return '>' + ''.join(result) + '<'
return '>' + text + '<'
obfuscated = re.sub(r'>([^<]+)<', add_minimal_invisible, obfuscated)
# Restore protected content exactly as-is
for i, protected_content in enumerate(protected_blocks):
obfuscated = obfuscated.replace(f'<!-- PROTECTED_SCRIPT_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_STYLE_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_TABLE_{i} -->', protected_content)
# Final cleanup - ensure no double newlines and remove extra spaces
obfuscated = re.sub(r'\n\n+', '\n', obfuscated)
obfuscated = re.sub(r'[ \t]+', ' ', obfuscated) # Remove extra spaces and tabs
return obfuscated
def remove_html(md_path: Path): def remove_html(md_path: Path):
relative_path = md_path.relative_to(MARKDOWN_DIR) relative_path = md_path.relative_to(MARKDOWN_DIR)
out_path = HTML_DIR / relative_path.with_suffix(".html") out_path = HTML_DIR / relative_path.with_suffix(".html")
if out_path.exists(): if out_path.exists():
out_path.unlink() out_path.unlink()
print(f"Removed: {out_path}") Logger.log_debug(f"Removed: {out_path}")
def initial_scan(markdown_dir: Path): def initial_scan(markdown_dir: Path):
print(f"Initial scan for markdown in {markdown_dir}...") Logger.log_info(f"Starting initial scan of markdown files in {markdown_dir}...")
for md in markdown_dir.rglob("*.md"): for md in markdown_dir.rglob("*.md"):
render_markdown(md) render_markdown(md)
"""
class Handler(FileSystemEventHandler): class Handler(FileSystemEventHandler):
def on_created(self, event): def on_created(self, event):
if not event.is_directory and event.src_path.endswith(".md"): if not event.is_directory and event.src_path.endswith(".md"):
@@ -262,20 +137,44 @@ class Handler(FileSystemEventHandler):
remove_html(src) remove_html(src)
if dest.suffix.lower() == ".md": if dest.suffix.lower() == ".md":
render_markdown(dest) render_markdown(dest)
"""
if __name__ == "__main__": if __name__ == "__main__":
if not MARKDOWN_DIR.exists(): if not MARKDOWN_DIR.exists():
print(f"Error: Markdown directory not found: {MARKDOWN_DIR}") alt_root = ROOT / "PyPost"
print("Please create a 'markdown' directory in the current working directory.") if alt_root.exists() and alt_root.is_dir():
sys.exit(1) Logger.log_warning(f"Default 'markdown' directory not found, switching ROOT to: {alt_root}")
ROOT = alt_root
MARKDOWN_DIR = ROOT / "markdown"
HTML_DIR = ROOT / "html"
else:
Logger.log_error(f"Markdown directory not found: {MARKDOWN_DIR}")
Logger.log_warning("Please create a 'markdown' directory or use a 'PyPost' directory with one inside it.")
sys.exit(1)
import argparse
parser = argparse.ArgumentParser(description="Monitor markdown directory and convert to HTML.")
# This stores True when passed, but means "no obfuscation"
parser.add_argument(
"--no-obfuscate",
action="store_false",
help="Disable HTML obfuscation."
)
args = parser.parse_args()
# Invert it to get the obfuscate flag
obfuscate = not args.no_obfuscate
Logger.log_obfuscation_info(f"Obfuscation is {'enabled' if obfuscate else 'disabled'}", obfuscate)
initial_scan(MARKDOWN_DIR) initial_scan(MARKDOWN_DIR)
event_handler = Handler() event_handler = Handler()
observer = Observer() observer = Observer()
observer.schedule(event_handler, str(MARKDOWN_DIR), recursive=True) observer.schedule(event_handler, str(MARKDOWN_DIR), recursive=True)
observer.start() observer.start()
print(f"Watching {MARKDOWN_DIR} for changes. Ctrl+C to stop.") Logger.log_info(f"Started monitoring {MARKDOWN_DIR} for changes.")
try: try:
while True: while True:
time.sleep(1) time.sleep(1)

BIN
css/icons/back.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

BIN
css/icons/date.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 382 KiB

BIN
css/icons/forward.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

BIN
css/icons/magnifier.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 KiB

BIN
css/icons/written.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

View File

@@ -16,3 +16,17 @@ hash_list = [
"aromantic armadillo", "aromantic armadillo",
"queer quokka", "queer quokka",
] ]
LOREM_IPSUM_COMMENTS = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.",
"Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet.",
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa.",
"gay furry pride >:3 OwO get rekt Charlie Kirk",
"Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.",
"Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias.",
"Nulla facilisi. Cras vehicula aliquet libero, sit amet lacinia nunc commodo eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae.",
"Proin euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl.",
"Vivamus euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl. Sed euismod, nisl sit amet ultricies lacinia, nisl nisl aliquam nisl, eget aliquam nisl nisl sit amet nisl."
]

View File

@@ -0,0 +1,131 @@
import random
import re
from hashes.hashes import LOREM_IPSUM_COMMENTS
class Obfuscator:
def obfuscate_html(html_content):
# Generate random strings
def generate_random_string(length=8):
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(random.choice(chars) for _ in range(length))
# Protect original content
protected_blocks = []
def protect_scripts(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_SCRIPT_{len(protected_blocks)-1} -->'
def protect_styles(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_STYLE_{len(protected_blocks)-1} -->'
# First pass: protect critical content
temp_html = re.sub(r'<script[^>]*>.*?</script>', protect_scripts, html_content, flags=re.DOTALL)
temp_html = re.sub(r'<style[^>]*>.*?</style>', protect_styles, temp_html, flags=re.DOTALL)
# Protect tables
def protect_tables(match):
protected_blocks.append(match.group(0))
return f'<!-- PROTECTED_TABLE_{len(protected_blocks)-1} -->'
temp_html = re.sub(r'<table[^>]*>.*?</table>', protect_tables, temp_html, flags=re.DOTALL)
# Clean up HTML - remove extra whitespace
lines = []
for line in temp_html.split('\n'):
cleaned_line = ' '.join(line.split())
if cleaned_line:
lines.append(cleaned_line)
# Add comments between lines (but not too many)
obfuscated_lines = []
for i, line in enumerate(lines):
# Add comment before some lines
if line and not line.startswith('<!--') and random.random() > 0.7:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated_lines.append(line)
# Add comment after some lines
if line and not line.startswith('<!--') and random.random() > 0.8:
lorem_comment = random.choice(LOREM_IPSUM_COMMENTS)
obfuscated_lines.append(f'<!-- {lorem_comment} -->')
obfuscated = '\n'.join(obfuscated_lines)
# Inject random comments between SOME elements (not all)
def inject_some_comments(html):
# Only inject between certain safe elements
safe_patterns = [
(r'(</div>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</p>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</span>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h1>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h2>)', r'\1<!--' + generate_random_string(6) + '-->'),
(r'(</h3>)', r'\1<!--' + generate_random_string(6) + '-->'),
]
for pattern, replacement in safe_patterns:
if random.random() > 0.5: # 50% chance to apply each pattern
html = re.sub(pattern, replacement, html)
return html
obfuscated = inject_some_comments(obfuscated)
# Add header comments (fewer to avoid breaking the document)
header_comments = [
'auto-obfuscated-' + generate_random_string(10),
'generated-' + generate_random_string(8),
]
header_block = '\n'.join([f'<!-- {comment} -->' for comment in header_comments])
obfuscated = header_block + '\n' + obfuscated
# Add footer comments
footer_comments = [
'end-' + generate_random_string(10),
'completed-' + generate_random_string(8),
]
footer_block = '\n'.join([f'<!-- {comment} -->' for comment in footer_comments])
obfuscated = obfuscated + '\n' + footer_block
# Minimal invisible characters - only in text content, not in tags
invisible_chars = ['\u200B', '\u200C']
def add_minimal_invisible(match):
text = match.group(1)
# NEVER obfuscate script-like content
if any(keyword in text for keyword in ['function', 'const ', 'var ', 'let ', 'document.', 'window.', 'getElement', 'querySelector', 'addEventListener']):
return '>' + text + '<'
# Only add to plain text content
if len(text) > 10: # Only on longer text blocks
result = []
for i, char in enumerate(text):
result.append(char)
# Very rarely add invisible chars
if i % 8 == 0 and i > 0 and random.random() > 0.8:
result.append(random.choice(invisible_chars))
return '>' + ''.join(result) + '<'
return '>' + text + '<'
obfuscated = re.sub(r'>([^<]+)<', add_minimal_invisible, obfuscated)
# Restore protected content exactly as-is
for i, protected_content in enumerate(protected_blocks):
obfuscated = obfuscated.replace(f'<!-- PROTECTED_SCRIPT_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_STYLE_{i} -->', protected_content)
obfuscated = obfuscated.replace(f'<!-- PROTECTED_TABLE_{i} -->', protected_content)
# Final cleanup - ensure no double newlines and remove extra spaces
obfuscated = re.sub(r'\n\n+', '\n', obfuscated)
obfuscated = re.sub(r'[ \t]+', ' ', obfuscated) # Remove extra spaces and tabs
return obfuscated

29
htmlhandler.py Normal file
View File

@@ -0,0 +1,29 @@
from pathlib import Path
from watchdog.events import FileSystemEventHandler
# this has to be like this. idk why. its ass
class htmlhandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
import PyPost
PyPost.render_markdown(Path(event.src_path))
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
import PyPost
PyPost.render_markdown(Path(event.src_path))
def on_deleted(self, event):
if not event.is_directory and event.src_path.endswith(".md"):
import PyPost
PyPost.remove_html(Path(event.src_path))
def on_moved(self, event):
src = Path(event.src_path)
dest = Path(event.dest_path)
import PyPost
if src.suffix.lower() == ".md":
PyPost.remove_html(src)
if dest.suffix.lower() == ".md":
PyPost.render_markdown(dest)

View File

@@ -1,9 +1,34 @@
import time
import colorama
colorama.init(autoreset=True)
class Logger: class Logger:
def log_error(self, message: str) -> None: @staticmethod
print(f"ERROR: {message}") def log_error(message: str) -> None:
def log_info(self, message: str) -> None: now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"INFO: {message}") print(f"{colorama.Fore.RED}[ ERROR@{now} ]: {message}{colorama.Style.RESET_ALL}")
def log_debug(self, message: str) -> None:
print(f"DEBUG: {message}") @staticmethod
def log_warning(self, message: str) -> None: def log_info(message: str) -> None:
print(f"WARNING: {message}") now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"{colorama.Fore.CYAN}[ INFO@{now} ]: {message}{colorama.Style.RESET_ALL}")
@staticmethod
def log_debug(message: str) -> None:
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"[ DEBUG@{now} ]: {message}")
@staticmethod
def log_warning(message: str) -> None:
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"{colorama.Fore.YELLOW}[ WARNING@{now} ]: {message}{colorama.Style.RESET_ALL}")
# yes we seriously needed this
@staticmethod
def log_obfuscation_info(message: str ,isenabled: bool) -> None:
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if isenabled:
print(f"[ INFO@{now} ]: {colorama.Fore.GREEN}{message}{colorama.Style.RESET_ALL}")
else:
print(f"[ INFO@{now} ]: {colorama.Fore.RED}{message}{colorama.Style.RESET_ALL}")

0
readme.md Normal file
View File

BIN
requirements.txt Normal file

Binary file not shown.

View File

@@ -6,6 +6,8 @@ from http.server import BaseHTTPRequestHandler, HTTPServer
import mimetypes import mimetypes
from jsmin import jsmin # pip install jsmin from jsmin import jsmin # pip install jsmin
from log.Logger import *
logger = Logger()
import PyPost import PyPost
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
@@ -82,7 +84,7 @@ class MyHandler(BaseHTTPRequestHandler):
try: try:
content = jsmin(content.decode("utf-8")).encode("utf-8") content = jsmin(content.decode("utf-8")).encode("utf-8")
except Exception as e: except Exception as e:
print(f"Error minifying JS file {file_path}: {e}") logger.log_error(f"Error minifying JS file {file_path}: {e}")
self.send_response(200) self.send_response(200)
self.send_header("Content-type", mime_type) self.send_header("Content-type", mime_type)
@@ -100,11 +102,15 @@ def run_pypost():
subprocess.run([sys.executable, script]) subprocess.run([sys.executable, script])
if __name__ == "__main__": if __name__ == "__main__":
threading.Thread(target=run_pypost, daemon=True).start() try:
print("Started PyPost.py in background watcher thread.") threading.Thread(target=run_pypost, daemon=True).start()
logger.log_debug("Started PyPost.py in background watcher thread.")
server_address = ("localhost", 8000) server_address = ("localhost", 8000)
httpd = HTTPServer(server_address, MyHandler) httpd = HTTPServer(server_address, MyHandler)
print("Serving on http://localhost:8000") logger.log_info(f"Serving on http://{server_address[0]}:{server_address[1]}")
httpd.serve_forever() httpd.serve_forever()
except (Exception, KeyboardInterrupt) as e:
logger.log_info(f"Shutting down server.\n Reason: {e}")
httpd.server_close()