import uuid
import os
from datetime import datetime
from pathlib import Path
import html2image
import click
import frontmatter
html = """
{date}
James Ravenscroft
@jamesravey@fosstodon.org
"""
@click.command()
@click.option('--input-file', '-i', required=True, type=click.Path(exists=True))
@click.option('--workspace-path', '-w', required=True, type=click.Path(exists=True))
def main(input_file, workspace_path):
front_matter = frontmatter.load(input_file)
title = front_matter.get('title')
date = front_matter.get('date', datetime.now().isoformat())
if title and date:
parsed_date = datetime.fromisoformat(
date).strftime("%b %d, %Y")
parsed_html = html.replace(
"{title}", title).replace("{date}", parsed_date)
file_name = f"{uuid.uuid4()}.png"
hti = html2image.Html2Image()
output_path = Path(workspace_path) / \
"static" / "social" / file_name
hti.temp_path = Path(workspace_path) / "tmp"
if not os.path.exists(hti.temp_path):
os.mkdir(hti.temp_path)
files = hti.screenshot(
html_str=[parsed_html], save_as=file_name, size=[(1128, 600)])
# move from tmp location to workspace folder
output_path = output_path.absolute().as_posix()
os.rename(files[0], output_path)
front_matter['preview'] = f"/social/{file_name}"
frontmatter.dump(front_matter, input_file)
if __name__ == "__main__":
main()