This repository has been archived on 2023-01-27. You can view files and clone it, but cannot push or open issues or pull requests.
flask-wikipages/app/__init__.py

78 lines
2.6 KiB
Python
Raw Normal View History

2021-09-22 14:29:02 +03:00
from flask import Flask, url_for, render_template, abort
2021-08-26 21:51:26 +03:00
import os
import json
from app.config import PANDOC_LINK, PANDOC_PATH, WHITELIST_PATH
2021-09-22 14:29:02 +03:00
from app.hash_manager import hash_file_sha512
2021-08-26 21:51:26 +03:00
import subprocess
app = Flask(__name__)
@app.context_processor
def override_url_for():
return dict(url_for=dated_url_for)
#TODO: make instead of datetime hash of commit
def dated_url_for(endpoint, **values):
if endpoint == 'static':
filename = values.get('filename', None)
if filename:
file_path = os.path.join(app.root_path, endpoint, filename)
values['q'] = int(os.stat(file_path).st_mtime)
return url_for(endpoint, **values)
2021-09-22 14:29:02 +03:00
def render_page(page):
path = f'{PANDOC_PATH}/{page}'
whitelist = WHITELIST_PATH
with open(whitelist, 'r') as f:
2022-04-04 23:14:14 +03:00
lines = f.read().splitlines()
if page not in lines:
raise Exception("Page doesn't exist!")
2021-09-22 14:29:02 +03:00
if not os.path.exists(f'{path}'):
raise Exception("Page doesn't exist!")
in_filename = f'{path}/main.md'
out_filename = f'{path}/render.html'
os.system(f'pandoc {in_filename} --to html --mathjax --output {out_filename}')
print('Creating lock file')
os.system(f'echo {hash_file_sha512(in_filename)} > {out_filename}.lock')
2021-08-26 21:51:26 +03:00
@app.route(f'/{PANDOC_LINK}/<page>')
def get_pandoc_page(page):
2021-09-22 14:29:02 +03:00
path = f'{PANDOC_PATH}/{page}'
whitelist = WHITELIST_PATH
with open(whitelist, 'r') as f:
2022-04-04 23:14:14 +03:00
lines = f.read().splitlines()
if page not in lines:
print('Access to page not in list {page}')
return 'This page does not exist'
2021-09-22 14:29:02 +03:00
if not os.path.exists(f'{path}'):
2021-09-22 14:33:53 +03:00
# TODO: Add 404 handler
return 'This page does not exist'
2021-09-22 14:29:02 +03:00
with open(f'{path}/config.json') as f:
2021-08-26 21:51:26 +03:00
data = json.loads(f.read())
2021-09-22 14:29:02 +03:00
if not os.path.exists(f'{path}/render.html') or not os.path.exists(f'{path}/render.html.lock'):
print('Rendered page or lockfile for {page} does not exist! Rendering {page}')
render_page(page)
else:
with open(f'{path}/render.html.lock', 'r') as f:
rendered_hash = f.read().strip()
current_hash = hash_file_sha512(f'{path}/main.md')
if rendered_hash != current_hash:
print(f'CURRENT: {current_hash}, RENDERED: {rendered_hash}')
print('Integrity test failed, rendering {page}!')
render_page(page)
2021-08-26 21:51:26 +03:00
template = data['template']
2021-09-22 14:29:02 +03:00
with open(f'{path}/render.html', 'r') as f:
inserted = f.read()
2021-08-26 21:51:26 +03:00
return render_template(template, markdown=inserted)
@app.route('/')
def index():
return render_template('index.html')