Files
natalieee.net/srv/content/comments.hy

44 lines
1.5 KiB
Hy

(import urllib.parse [quote-plus urlparse])
(import os [mkdir])
(import os.path [isdir :as dir? isfile :as file? abspath])
(import datetime [datetime])
(import bleach [clean])
(import validators [domain :as domain?])
(require hyrule.destructure [setv+])
(defn create-comment [request]
(setv now (datetime.now))
(setv url-comment-dir (quote-plus (. request (get "route") (get "parameters") (get "route")) :safe ""))
(when (not (dir? "./www/data"))
(mkdir "./www/data"))
(when (not (dir? f"./www/data/comments"))
(mkdir "./www/data/comments"))
(when (not (dir? f"./www/data/comments/{url-comment-dir}"))
(mkdir f"./www/data/comments/{url-comment-dir}"))
(setv+ {{comment "comment" name "name" site "site"} "body"} request)
(when (.startswith site "//")
(setv site (.replace site "//" "")))
(setv [protocol domain path #* _] (urlparse
(if (in "://" site)
site
(+ "http://" site))))
(setv site-valid? (= (domain? domain) True))
(when (not protocol)
(setv protocol "//"))
(with [f (open f"./www/data/comments/{url-comment-dir}/{(.strftime now "%Y-%m-%d_%H:%M:%S_%f")}" "w")]
(.write f f"<div class=\"comment\"><span style=\"font-weight: bold\">{(if (and site site-valid?) f"<a href=\"{(clean protocol)}://{(clean domain)}{(clean path)}\">" "")}{(clean name)}{(if (and site site-valid?) "</a>" "")}</span> at {(.strftime now "%Y-%m-%d %H:%M:%S")}:<br><pre>{(clean comment)}</pre></div>"))
(return (dict
:code 303
:headers {"Location" (. request (get "headers") (get "Referer"))})))