motm/post.py

125 lines
4.1 KiB
Python

import time
from typing import Union, Optional
class Post:
def __init__(
self,
settings: dict,
post_type: str,
post_id: int,
timestamp: int,
path: str,
title: str,
text: str,
username: str,
cert_hash: str,
parent: str,
num_children: int,
children: Optional[list] = None,
current_page: Optional[int] = None,
) -> None:
self.settings: dict = settings
self.post_type: str = post_type
self.post_id: int = post_id
self.timestamp: int = timestamp
self.path: str = path
self.title: str = title
self.text: str = text
self.username: str = username
self.cert_hash: str = cert_hash
self.parent: str = parent
self.num_children: int = num_children
self.children: Optional[list] = children
self.current_page: Optional[int] = current_page
template_dir: str = self.settings["templateDir"]
template_name: str = self.settings["postTypes"][self.post_type]["template"]
mini_template_name: str = self.settings["postTypes"][self.post_type]["miniTemplate"]
with open(
"{}/{}.template".format(template_dir, template_name), "r"
) as template_file:
self.template = template_file.read()
if mini_template_name is not None:
with open(
"{}/{}.template".format(template_dir, mini_template_name), "r"
) as template_file:
self.mini_template = template_file.read()
def render_children(self) -> str:
rendered_children: str = ""
if self.children is None:
return ""
for child in self.children:
rendered_children += child.render(mini=True)
return rendered_children
def render(self, mini: bool = False) -> str:
hr_timestamp: str = time.strftime(
"%a, %d %b %Y %H:%M:%S +0000",
time.gmtime(int(self.timestamp) // 1000000000),
) # convert unix time in nanoseconds to human-readable utc time
basename: str = self.path.split("/")[-1]
cgi_safe_path: Union[list, str] = self.path.split("/")
if len(cgi_safe_path) > 2:
cgi_safe_path = cgi_safe_path[-2:]
cgi_safe_path = "/".join(cgi_safe_path)
if self.username is None:
self.username = "[no username]"
if self.text is None:
self.text = ""
if mini:
return self.mini_template.format(
post_id=self.post_id,
timestamp=hr_timestamp,
path=cgi_safe_path,
basename=basename,
title=self.title,
text=self.text,
username=self.username,
children=self.render_children(),
num_children=self.num_children,
)
elif self.current_page is not None:
next_page: int = self.current_page + 1
previous_page: int = (self.current_page - 1) if self.current_page > 1 else 1
return self.template.format(
post_id=self.post_id,
timestamp=hr_timestamp,
path=cgi_safe_path,
basename=basename,
title=self.title,
text=self.text,
username=self.username,
children=self.render_children(),
num_children=self.num_children,
current_page=self.current_page,
previous_page=previous_page,
next_page=next_page,
)
else:
return self.template.format(
post_id=self.post_id,
timestamp=hr_timestamp,
path=cgi_safe_path,
basename=basename,
title=self.title,
username=self.username,
text=self.text,
children=self.render_children(),
num_children=self.num_children,
current_page=1,
previous_page=1,
next_page=1,
)