diff --git a/src/routes/index.py b/src/routes/index.py index 6e0add2..84439b9 100644 --- a/src/routes/index.py +++ b/src/routes/index.py @@ -1,8 +1,6 @@ -from os import path as os_path - from config import Config from flask import Blueprint, flash, redirect, render_template, request -from utils.misc import get_posts, post_filename +from utils.misc import create_post, fresh_file_id, get_posts from werkzeug import Response name = __name__.split(".")[-1] @@ -26,23 +24,15 @@ def new_post() -> Response: if Config.is_logged(): content = request.form.get("p") if content: - # finding all posts - paths = get_posts() - # finding an appropriate filename - filename = 0 - if len(paths) > filename: - filename = paths.index(max(iter(paths), key=os_path.getmtime)) + 1 + filename = fresh_file_id() - # creating the post - with open( - post_filename(filename), - "w", - encoding="utf-8", - ) as f: - f.write(content) + # create/update the post + update = create_post(filename, content) - flash(f"post created.") + flash( + f"post {'updated' if update else 'created'}." + ) else: flash(f"invalid post: {content}") else: diff --git a/src/utils/misc.py b/src/utils/misc.py index ca6ad52..af8c54a 100644 --- a/src/utils/misc.py +++ b/src/utils/misc.py @@ -5,7 +5,7 @@ from os import remove as os_remove from config import Config -def post_filename(number: int): +def post_filename(number: int) -> str: """get filename of post""" return f"{Config.data_dir}/{number}.txt" @@ -37,3 +37,37 @@ def delete_post(filename: str) -> bool: else: os_remove(filename) return True + + +def fresh_file_id() -> int: + # finding all posts + paths = get_posts() + + # use the latest file as the reference and increment the ID + filename = 0 + if len(paths) > filename: + chosen = max(iter(paths), key=os_path.getmtime) + + # add 1 to the chosen id + filename = int(chosen.split("/")[-1][:-4]) + 1 + return filename + + +def exist_post(file_id: int) -> bool: + try: + open(post_filename(file_id)) + return True + except FileNotFoundError: + return False + + +def create_post(file_id: int, content: str) -> bool: + """create a post""" + # check if the file already exists + update = exist_post(file_id) + + # write into the file + with open(post_filename(file_id), "w", encoding="utf-8") as f: + f.write(content) + + return update