-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsillysimple.py
More file actions
430 lines (359 loc) · 14.8 KB
/
sillysimple.py
File metadata and controls
430 lines (359 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# needs to be first; unnecessary after Python 3.14
from __future__ import annotations
from flask import Flask, flash, request, redirect, url_for, Response
from werkzeug.utils import secure_filename
from pathlib import Path
from jinja2 import Environment, BaseLoader, DictLoader
import ulid
import os
import subprocess
import re
import concurrent.futures
import threading
import time
from datetime import date, datetime
import logging, logging.config
from enum import IntEnum, unique
from importlib import reload
import params
import notifier
# I currently assume that NGINX will proxy to /. The HTMX
# requests have to send requests to correct URL though.
# That's what URL_PREFIX is for.
URL_PREFIX = "/comments"
HDR_FROM = "from_name"
HDR_FROM_CONTACT = "from_contact"
HDR_FROM_CONTACT_HIDE = "from_hide_contact"
HDR_CONTENT_SPLITTER = "---"
def reload_params():
global params
def get_ts() -> int:
return int(Path("params.py").stat().st_mtime)
period = 60 * 10
timestamp = get_ts()
app_log.info(f"I'll reload params.py every {period}s")
time.sleep(5)
while True:
timestamp_fresh = get_ts()
if timestamp_fresh > timestamp:
app_log.info("Reloading params.py")
timestamp = timestamp_fresh
params = reload(params)
time.sleep(period)
def create_app():
app = Flask(__name__, static_url_path="/static")
thr_params_reload = threading.Thread(target=reload_params, daemon=True)
thr_params_reload.start()
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return env.get_template("templ_index").render(remote=params.REMOTE_URL)
# I guess this could be a way to disable rendering an entire website.
# So a release mode solution?
# return redirect(url_for(URL_PREFIX))
return "no"
@app.route("/comments", methods=["GET", "POST", "OPTIONS"])
def comments_for_article():
app_log.info(request.args)
# Let's handle the preflight request.
if request.method == "OPTIONS":
ret = Response("")
ret.headers["Access-Control-Allow-Origin"] = "*"
ret.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT"
# This was important to set to '*'. 'Content-Type' was used before
# and it didn't work.
ret.headers["Access-Control-Allow-Headers"] = "*"
ret.headers["Access-Control-Max-Age"] = "300"
return ret
which = request.values.get("for", None)
app_log.info(f"request values: {request.values}")
# The request path might look like ?for=project/a_project, to support putting
# comments in a more complex filesystem structure.
which_list = [x for x in which.split("/") if len(x) > 0]
which = which_list[-1]
which_path = which_list[:-1]
app_log.info(f"path: {Path(*which_path)}, slug: {which}")
if which in params.KNOWN_SLUGS:
if request.method == "GET":
if which:
comments = get_comments_for_slug(which, which_path)
else:
comments = ""
# Need to use the remote URL, since the comment submit form needs to
# know where to send the request.
ret = Response(
env.get_template("templ_comments").render(
remote=params.REMOTE_URL,
endpoint=URL_PREFIX,
which="/".join(which_list),
comments=comments,
)
)
# Needs to be present in OPTIONS response and here.
ret.headers["Access-Control-Allow-Origin"] = "*"
return ret
if request.method == "POST":
form = request.form.to_dict()
try:
comment = Comment()
comment.created_by = form.get("comment_author").strip()
comment.created_by_contact = form.get("comment_contact").strip()
# Existence of 'hide' key implies that it's checked. Otherwise the form doesn't
# even send it.
if form.get("hide"):
pass
else:
comment.contact_hide = False
comment.paragraphs = form.get("comment").strip().replace("\r\n", "\n").split("\n\n")
comment_fname = str(ulid.new())
app_log.info(f"Got form: {form}{comment}")
notifier.notify(f"{form}")
comment.dump_into_file(which_list, comment_fname)
except ValueError:
app_log.error(
f"Failed to extract the author's name and email from {form}"
)
comments = get_comments_for_slug(which, which_path)
ret = Response(
env.get_template("templ_comments").render(
remote=params.REMOTE_URL,
endpoint=URL_PREFIX,
which="/".join(which_list),
comments=comments
)
)
# Needs to be present in OPTIONS response and here.
ret.headers["Access-Control-Allow-Origin"] = "*"
return ret
else:
app_log.error(f"Slug '{which}' not known, check params.py!")
return "no"
return app
logging.config.dictConfig(
{
"version": 1,
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
}
},
"handlers": {
"wsgi": {
"class": "logging.StreamHandler",
"stream": "ext://flask.logging.wsgi_errors_stream",
"formatter": "default",
},
"log_file": {
"class": "logging.handlers.RotatingFileHandler",
"filename": "sillysimple.log",
"formatter": "default",
"mode": "a",
"maxBytes": 10 * 1024,
"backupCount": 1,
},
},
"loggers": {
"root": {"level": "INFO", "handlers": ["wsgi"]},
"my_logger": {
"level": "INFO",
"handlers": ["wsgi", "log_file"],
"propagate": False,
},
},
}
)
app_log = logging.getLogger("my_logger")
app_log.info("------------------ Started the app ------------------")
class Comment:
def __init__(self):
self.created_on_ts = 0
self.created_on_dt = 0
self.created_by = None
self.created_by_contact = None
self.contact_hide = True
self.paragraphs = list()
def __repr__(self):
ret = f"{self.created_by},{self.created_by_contact},{self.contact_hide},{self.paragraphs}"
return ret
@classmethod
def from_path(cls, fpath: Path) -> Optional[Comment]:
"""
Constructor for Comment, from a comment file.
"""
if not fpath.exists():
return None
# I assume that a comment paragraph can be split over multiple lines.
# Need to concat those lines but still keep the comment split into
# paragraphs.
comment_raw = fpath.read_text()
comment_meta, comment_content = comment_raw.split(HDR_CONTENT_SPLITTER, maxsplit=1)
comment_paragraphs = list()
for paragraph in [x.strip() for x in comment_content.split("\n\n")]:
comment_paragraphs.append(paragraph.replace("\n", ""))
c = Comment()
# The ULID generates a 26 char long hashes.
if len(fpath.stem) == 26:
c.created_on_ts = ulid.parse(fpath.stem).timestamp().int
c.created_on_dt = datetime.fromtimestamp(c.created_on_ts / 1000)
else:
app_log.warn(f"Skipping file {fpath} (len {len(fpath.stem)})")
return None
meta_lines = [l.strip() for l in comment_meta.split("\n") if len(l) > 0]
for line in meta_lines:
key, val = line.split(":", 1)
if HDR_FROM in key:
c.created_by = val
elif HDR_FROM_CONTACT in key:
c.created_by_contact = val
elif HDR_FROM_CONTACT_HIDE in key:
c.contact_hide = True if val == "True" else False
c.paragraphs = comment_paragraphs[1:]
return c
def dump_into_file(self, fpath: list[str], fname: str) -> Optional[Path]:
if self.created_by is None:
return None
app_log.info(f"Creating new comment:")
app_log.info(f" {self.created_by}")
app_log.info(f" {self.created_by_contact}")
app_log.info(f" {Path(*fpath, fname)}")
# Create the folder structure in the root of params.COMMENTS_DIR.
if not Path(params.COMMENTS_DIR, *fpath).exists():
Path(params.COMMENTS_DIR, *fpath).mkdir(parents=True)
p = Path(params.COMMENTS_DIR, *fpath, fname).with_suffix(".txt")
try:
with p.open(mode="x") as new_comment_file:
new_comment_file.write(f"{HDR_FROM}:{self.created_by}\n")
new_comment_file.write(f"{HDR_FROM_CONTACT}:{self.created_by_contact}\n")
new_comment_file.write(f"{HDR_FROM_CONTACT_HIDE}:{self.contact_hide}\n")
new_comment_file.write(f"\n{HDR_CONTENT_SPLITTER}\n")
for par in self.paragraphs:
new_comment_file.write("\n")
new_comment_file.write(par)
new_comment_file.write("\n")
app_log.info(f"Comment saved to {p}")
except FileExistsError:
app_log.error(f"File {p} already exists, skipping comment!")
return p
# - HTML functions --------------------------------------------------------------------------------
# The \ avoids the empty line.
html_index = """\
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="static/main.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Serif+Pro&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400&family=Source+Serif+Pro&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Rubik:wght@900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Rubik&display=swap" rel="stylesheet">
<script src="https://unpkg.com/htmx.org@1.8.0"></script>
<script>
// This is a very small function which is supposed to grab the changed
// value from an input elements and copy it onto label element.
function update_name() {
var from = arguments[0];
var to = arguments[1];
to.innerHTML = from.files[0].name;
}
</script>
<title>Silly comments demo...</title>
</head>
<body>
<div class="wrapper">
<div class="left" style="grid-row: 1; margin-top: 0em;">
<p style="margin-top: 0em;">
Just wanted to make a comment system...
</p>
</ul>
</div>
<!-- swap self for comments, for this article -->
<div style="grid-row: 1" hx-get="{{ remote }}/comments" hx-vals='{"for": "example"}' hx-swap="innerHTML" hx-trigger="load">
</div>
</div>
</body>
</html>
"""
"""
<link rel="stylesheet" href="static/silly.css">
"""
html_comments = """\
<div id="comments">
<div class="comments">
{%- import 'templ_comment' as comment -%}
{%- for c in comments %}
{{ comment.comment(c) -}}
{%- endfor -%}
</div>
<div class="comment-submit">
<form hx-post="{{ remote }}/{{ endpoint }}" hx-vals='{"for": "{{ which }}" }' hx-target="#comments" hx-swap="outerHTML" enctype="multipart/form-data">
<input type="text" id="comment_author" name="comment_author" placeholder="Name" required><br>
<div>
<input type="text" id="comment_contact" name="comment_contact" placeholder="e-mail or other contact info">
<input type="checkbox" id="comment_contact_hide" name="hide" checked>
<label for="comment_contact_hide">Hide contact info</label>
</div>
<textarea id="comment" name="comment" placeholder="Comment..." required></textarea><br>
<button id="submit" class="custom-file-upload" type="submit">Submit</button>
</form>
</div>
</div>
"""
load = DictLoader(
{
"templ_comments": html_comments,
"templ_index": html_index,
"templ_comment": """
{% macro comment(cobject) -%}
<div class="comment">
<div class="comment-meta">
<div class="comment-author">
<span>{{ cobject.created_by | e }}</span>
{%- if cobject.contact_hide -%}
{%- else -%}
{%- if cobject.created_by_contact | length -%}
<span>,</span>
<span>{{ cobject.created_by_contact | e }}</span>
{%- endif -%}
{%- endif -%}
</div>
<div class="comment-date">
<span>{{ cobject.created_on_dt.date() }}</span>
<span>{{ '%02d' % cobject.created_on_dt.hour }}</span><span>{{ '%02d' % cobject.created_on_dt.minute }}</span><span class="comment-date-seconds">{{ '%02d' % cobject.created_on_dt.second }}</span>
</div>
</div>
<div class="comment-content">
{%- for p in cobject.paragraphs %}
<p>
{{ p | e }}
</p>
{%- endfor %}
</div>
</div>
{%- endmacro %}
"""
}
)
env = Environment(loader=load)
# - end --- HTML functions ------------------------------------------------------------------------
def get_comments_for_slug(slug: str, path: list = []):
"""
Parameters
----------
slug : str
The leaf directory name, which stores the comment files.
path : list
List of directories that build the path to the slug directory.
There's params.COMMENTS_DIR prepended to that list.
"""
paths = list(Path(params.COMMENTS_DIR, *path, slug).glob("*.txt"))
comments = list()
app_log.info(f"Reading comments from {Path(params.COMMENTS_DIR, slug)}")
app_log.info(f"{paths}")
for comment_file in paths:
c = Comment.from_path(comment_file)
if c:
comments.append(c)
# TODO(michalc): might be better to move this to when we create a new comment.
comments = sorted(comments, key=lambda c: c.created_on_ts)
return comments