99 lines
2.9 KiB
Python
99 lines
2.9 KiB
Python
import os
|
|
import csv
|
|
|
|
COMMENT_FILE = os.path.join(os.path.dirname(__file__), '../content/comments.csv')
|
|
MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024 # 5MB example
|
|
|
|
import datetime
|
|
|
|
def save_comment(post_id, author, content):
|
|
"""Handles the validation and saving of comments to the private CSV."""
|
|
# 1. Validation logic moved here
|
|
if not content or len(content) > 1000:
|
|
return False
|
|
|
|
author = (author or "Anonymous").strip()[:50]
|
|
content = content.strip()
|
|
|
|
# 2. Path & Size Checks
|
|
file_exists = os.path.isfile(COMMENT_FILE)
|
|
if file_exists and os.path.getsize(COMMENT_FILE) > MAX_FILE_SIZE_BYTES:
|
|
return False # Or raise a specific error
|
|
|
|
# 3. Write to CSV
|
|
with open(COMMENT_FILE, 'a', newline='', encoding='utf-8') as f:
|
|
writer = csv.DictWriter(f, fieldnames=['post_id', 'author', 'content', 'date'])
|
|
if not file_exists:
|
|
writer.writeheader()
|
|
|
|
writer.writerow({
|
|
'post_id': post_id,
|
|
'author': author,
|
|
'content': content,
|
|
'date': datetime.datetime.now().strftime("%B %d, %Y at %I:%M %p")
|
|
})
|
|
return True
|
|
|
|
|
|
|
|
def load_snippet(filename):
|
|
"""Helper to read HTML snippets from the data folder."""
|
|
base_path = os.path.join(os.path.dirname(__file__), 'data')
|
|
file_path = os.path.join(base_path, filename)
|
|
|
|
if os.path.exists(file_path):
|
|
with open(file_path, 'r', encoding='utf-8') as f:
|
|
return f.read()
|
|
return ""
|
|
|
|
def get_enriched_post(post_id, BLOG_POSTS):
|
|
post = next((p for p in BLOG_POSTS if p.get('id') == post_id), None)
|
|
from pathlib import Path
|
|
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
DATA_DIR = BASE_DIR / "content" / "data"
|
|
|
|
file_path_10 = DATA_DIR / "post_10_timeline.html"
|
|
|
|
|
|
|
|
# Mapping config: keeps logic.py tiny
|
|
configs = {
|
|
10: {
|
|
"template": "components/timeline.html",
|
|
"timeline_file": file_path_10
|
|
},
|
|
8: {
|
|
"template": "components/christmas_post.html",
|
|
"timeline": None
|
|
},
|
|
}
|
|
|
|
if post_id in configs:
|
|
conf = configs[post_id]
|
|
post_template = conf.get("template")
|
|
if post_template:
|
|
post["template"] = post_template
|
|
|
|
# Only load the file if a filename is provided
|
|
t_file = conf.get("timeline_file")
|
|
if t_file:
|
|
post["timeline"] = load_snippet(t_file)
|
|
|
|
return post
|
|
|
|
|
|
def get_comments_for_post(post_id):
|
|
comments = []
|
|
if not os.path.exists(COMMENT_FILE):
|
|
return comments
|
|
|
|
if os.path.getsize(COMMENT_FILE) > MAX_FILE_SIZE_BYTES:
|
|
return ["Comment section full."] # Handle error in app.py
|
|
|
|
with open(COMMENT_FILE, 'r', encoding='utf-8') as f:
|
|
reader = csv.DictReader(f)
|
|
for row in reader:
|
|
if row['post_id'] == str(post_id):
|
|
comments.append(row)
|
|
return comments |