aboutsummaryrefslogtreecommitdiff
path: root/nawp.scm
blob: 5c6c214ff586aa0e86aa549229cef25f9a2ee913 (plain)
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
#!/usr/bin/csi -s
;;; NAWP (NAWP Ain't WordPress)
;;; Copyright (C) 2021 Chris Brannon.
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Affero General Public License as
;;; published by the Free Software Foundation, either version 3 of the License,
;;; or (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public License
;;; along with this program.  If not, see <https://www.gnu.org/licenses/>.
;;;
;;; Author's email: chris@the-brannons.com
;;;
(import
  anaphora
  atom
  (chicken format)
  (chicken io)
  (chicken pathname)
  (chicken port)
  (chicken process-context)
  (chicken time)
  (chicken time posix)
  crypt
  lowdown
  matchable
  rfc3339
  sql-de-lite
  srfi-1
  srfi-13
  sxml-transforms
  uri-common)

(define-anaphor avalues values #:cascade)

(define blog-title "Brannon's Banal Babblings")
(define blog-description "Insert clever description.")
(define atom-page-name "feed.atom")
(define blog-base-uri (uri-reference "https://the-brannons.com/blog/"))
(define posts-base-uri (uri-relative-to (uri-reference "posts/") blog-base-uri))
(define feed-uri (uri-relative-to (uri-reference atom-page-name) blog-base-uri))
(define db-file "/var/lib/nawp/blog.db")
(define default-author "Chris Brannon")

(define-record post id timestamp slug title author body)

(define (post-body-tree post)
  (with-input-from-string (post-body post) read))

(define (list-min l)
  (reduce min (car l) (cdr l)))
(define (list-max l)
  (reduce max (car l) (cdr l)))

(define (split-path p)
  (receive (_ _ parts) (decompose-directory p) (or parts '())))


(define (compare-crypted-passwords check against)
  (string=? (crypt check against) against))

(define (authenticated username password)
  (call-with-database
    db-file
    (lambda (db)
      (let ((res (query fetch
		   (sql db
		     "SELECT password FROM users where username = ?;")
		   username)))
	(and (pair? res) (compare-crypted-passwords password (car res)))))))

(define (db-queryer our-db-file)
  (lambda (statement . args)
    (call-with-database
      our-db-file
      (lambda (db)
	(apply query (cons fetch-alists (cons (sql db statement) args)))))))

(define (adjust-headings tree)
  (cond
    ((null? tree) tree)
    ((eq? tree 'h1) 'h2)
    ((eq? tree 'h2) 'h3)
    ((eq? tree 'h3) 'h4)
    ((eq? tree 'h4) 'h5)
    ((eq? tree 'h5) 'h6)
    ((not (list? tree)) tree)
    (else (cons (adjust-headings (car tree)) (adjust-headings (cdr tree))))))


(define (write-html-page blog-title blog-description canonical-uri feed-uri
          body #!key (page-title blog-title))
  (print "Content-type: text/html\n")
  (print "<!DOCTYPE html>")
  ;; I stole a lot of this boilerplate stuff from Jekyll.
  (SXML->HTML
    `(html
       (head
	 (meta (@ (charset "utf-8")))
	 (meta (@ (http-equiv "X-UA-Compatible")
		 (content "IE=edge")))
	 (meta (@ (name "viewport")
		 (content "width=device-width, initial-scale=1")))
	 (title ,page-title)
	 (meta (@ (name "description")
		 (content ,blog-description)))
	 (link (@ (rel "canonical") (href ,canonical-uri)))
	 (link (@ (rel "alternate")
		 (type "application/rss+xml")
		 (title ,blog-title)
		 (href ,feed-uri))))
       (body ,@body))))

(define (make-ahref uri text)
  `(a (@ (href ,uri)) ,text))

(define (format-post-date post)
  (time->string (seconds->local-time
		  (post-timestamp post)) "%a, %d %b %Y %H:%M:%S %z"))

(define (post-slug-uri post)
  (uri->string (uri-relative-to (uri-reference (post-slug post)) posts-base-uri)))

(define (format-post-link post #!key (in-list #t))
  (let ((link (post-slug-uri post)))
    (if in-list
      (list
	'li (make-ahref link
	      (sprintf "~a: ~a" (format-post-date post) (post-title post))))
      (make-ahref link (post-title post)))))

(define (transform-for-sxhtml post #!key h1)
  (cons
    (if h1
      (list 'h1 (post-title post))
      (list 'h2 (format-post-link post in-list: #f)))
    (cons
      (list 'p '(@ ("style" "font-size:14px;color:#828282;"))
	(sprintf "~a - ~a" (format-post-date post) (post-author post))) (post-body-tree post))))

(define (min-post-id)
  (let ((res
	  ((db-queryer db-file) "SELECT min(id) as m FROM blog_entries;")))
    (if (pair? res) (cdr (assoc 'm (car res))) 0)))

(define (latest-sxhtml #!key before)
  (receive (posts stop-offset)
    (avalues
      (fetch-latest-posts before)
      (and (pair? it) (list-min (map post-id it))))
    (let ((older-link
	    (if (and stop-offset  (> stop-offset (min-post-id))) (list (make-ahref (sprintf "?before=~s" stop-offset) "Older")) '())))
      (write-html-page
	blog-title blog-description (uri->string blog-base-uri)
	(uri->string feed-uri)
	(append (concatenate (map transform-for-sxhtml posts)) '((br)) older-link
	  '((br)) (list (make-ahref "all-post-links" "Links to all posts")))))))

(define (all-post-links)
  (write-html-page
    blog-title blog-description (uri->string blog-base-uri)
    (uri->string feed-uri)
    (list
      (cons 'ul
	(map (compose format-post-link row->post)
	  ((db-queryer db-file) "SELECT slug, title, author, timestamp FROM blog_entries;"))))
    page-title: (sprintf "~a -- Links to All Posts" blog-title)))

(define seconds->rfc3339-string (compose rfc3339->string seconds->rfc3339))

(define (SXML->HTMLSTRING sxml-expr)
  (with-output-to-string (lambda () (SXML->HTML sxml-expr))))

(define (atom-entry post)
  (make-entry
    id: (post-slug-uri post)
    updated: (seconds->rfc3339-string (post-timestamp post))
    title: (make-title (post-title post))
    content: (make-content (SXML->HTMLSTRING (post-body-tree post)) type: 'html)
    authors: (list (make-author name: (post-author post)))))

(define (latest-atom)
  (let ((posts (fetch-latest-posts)))
    ;; What should an empty feed look like?
    (when (null? posts) (http-fail 503 "Service unavailable."))
    (make-atom-doc
      (make-feed id: "foo" title: (make-title "foo")
	updated: (seconds->rfc3339-string (list-max (map post-timestamp posts)))
	entries: (map atom-entry posts)))))

(define (row->post row)
  (apply make-post
    (map
      (lambda (field) (aand (assoc field row) (cdr it)))
      '(id timestamp slug title author body))))

(define (fetch-latest-posts #!key before)
  ;; What I really want here is a composable sexp representation of SQL.
  (let* ((queryer (db-queryer db-file)))
    (map row->post
      (if before
	(queryer "SELECT * FROM blog_entries WHERE id < ? ORDER BY id DESC LIMIT 40;" before)
	(queryer "SELECT * from blog_entries ORDER BY id DESC LIMIT 40;")))))

(define (add-user username password display-name)
  (let ((crypted-password (crypt password (crypt-gensalt type: 'sha512))))
    (call-with-database
      db-file
      (lambda (db)
	(exec
	  (sql db
	    "INSERT INTO users (username, password, display_name) VALUES (?,?,?);")
	  username crypted-password display-name)))))

(define (add-post slug title author body-md)
  (let ((body-sxhtml-string (sprintf "~s" (adjust-headings (markdown->sxml body-md)))))
    (call-with-database
      db-file
      (lambda (db)
	(exec
	  (sql db
	    "INSERT INTO blog_entries (slug, title, author, body, timestamp) VALUES (?,?,?,?,?);")
	  slug title author body-sxhtml-string (current-seconds))))))

(define (form-field-value key form)
  (aand (assoc key form) (cdr it)))

(define (http-fail status message)
  (print "Content-type: text/html")
  (printf "Status: ~a\n\n" status)
  (printf "<html><head><title>Error</title></head><body>~a</body></html\n" message)
  (exit 0))

(define (http-redirect code uri)
  (printf "Status: ~a\nContent-type: text/html\nLocation: ~a\n\n"
    code uri)
  (printf "<html><head><title>Redirected</title></head><body><a href=\"~a\">click here</a>\n\n" uri)
  (exit 0))

(define (read-response)
  (form-urldecode (read-string 3333333)))

(define (send-one-post slug)
  (let ((post-l ((db-queryer db-file) "SELECT * FROM blog_entries WHERE slug = ?;" slug)))
    (when (null? post) (http-fail 404 "Post not known."))
    (let ((post (row->post (car post-l))))
      (write-html-page
	blog-title blog-description (uri->string blog-base-uri)
	(uri->string feed-uri)
	(transform-for-sxhtml post h1: #t)
	page-title: (post-title post)))))

(define (lookup-author-name username)
  (let ((res ((db-queryer db-file) "SELECT display_name FROM users WHERE username = ?" username)))
    (when (null? res) "unknown")
    (cdr (assoc 'display_name (car res)))))

(define (make-form-input name #!key (type "text"))
  (list (sprintf "~a:" (string-titlecase name))
    `(input (@ (type ,type) (name ,name)))
    '(br)))

(define post-form
  `(html
     (head (title "Write a Post"))
     (body
       (form (@ (method "post"))
	 ,@(make-form-input "username")
	 ,@(make-form-input "password" type: "password")
	 ,@(make-form-input "slug")
	 ,@(make-form-input "title")
	 "Content:"
	 (br)
	 (textarea (@ (name "body")))
	 (input (@ (type "submit")))))))

(define (route request-method path-info)
  (match
    (cons request-method path-info)
    (("GET")
      (latest-sxhtml
	before: (form-field-value
		  'before (form-urldecode
			    (get-environment-variable "QUERY_STRING")))))
    (("GET" "feed.atom")
      (print "Content-type: application/atom+xml\n")
      (write-atom-doc (latest-atom )))
    (("GET" "post-form")
      (print "Content-type: text/html\n")
      (SXML->HTML post-form))
    (("POST" "post-form")
      (let* ((response (read-response))
	      (username (form-field-value 'username response))
	      (password (form-field-value 'password response))
	      (slug (form-field-value 'slug response))
	      (title (form-field-value 'title response))
	      (author (lookup-author-name username))
	      (body (form-field-value 'body response)))
	(when (not (and username password slug title author body))
	  (http-fail 400 "Bad request."))
	(unless (authenticated username password)
	  (http-fail 403 "Bad credentials."))
	(add-post slug title author body)
	(http-redirect 303 (uri->string blog-base-uri))))
    (("GET" "posts" slug)
      (send-one-post slug))
    (("GET" "all-post-links") (all-post-links))
    (everything-else
      (http-fail 400 "Bad request."))))

(define (cgi-main)
  (let (
	 (path-info
	   (split-path (string-trim-both
			 (or (get-environment-variable "PATH_INFO") "/")
			 #\/)))
	 (request-method (get-environment-variable "REQUEST_METHOD")))
    (route request-method path-info)))

;; We should use stty for this, but the stty egg appears broken on musl
;; for now.  I use musl.
(define (read-password prompt)
  (display prompt)
  (flush-output)
  ;;  (with-stty '(not echo) read-line))
  (read-line))

(define (help)
  (let ((program-base (pathname-file (program-name))))
    (printf "Usage: ~a adduser USERNAME DISPLAY-NAME\n" program-base)
    (print "    adds a new user, prompting for the password.\n")
    (print "If this program is called without arguments, it operates in CGI mode.\n")))

(define (main)
  (match (command-line-arguments)
    (() (cgi-main))
    ((adduser username display-name)
      (add-user username (read-password "Password: ") display-name))
    (everything-else (help))))

(main)