115 lines
2.7 KiB
Nim
115 lines
2.7 KiB
Nim
import asyncdispatch, db_sqlite, jester, moustachu, os,
|
|
shorturl, strutils, tables, times, typetraits
|
|
|
|
const
|
|
baseTemplate*: string = staticRead "./templates/layout.mustache"
|
|
indexTemplate*: string = staticRead "./templates/index.mustache"
|
|
errorTemplate*: string = staticRead "./templates/error.mustache"
|
|
quoteTemplate*: string = staticRead "./templates/quote.mustache"
|
|
|
|
testTemplate*: string = """<p>hi!</p>"""
|
|
|
|
let
|
|
db = open("data/quotes.db", nil, nil, nil)
|
|
|
|
try:
|
|
db.exec(sql"""create table if not exists quotes (
|
|
id INTEGER PRIMARY KEY,
|
|
channel TEXT,
|
|
adder TEXT,
|
|
nick TEXT,
|
|
message TEXT,
|
|
time REAL,
|
|
deleted INTEGER DEFAULT 0)""")
|
|
|
|
except:
|
|
echo getCurrentExceptionMsg()
|
|
raise
|
|
|
|
template renderMustache*(title: string, templ: string, ctx: Context): expr =
|
|
var
|
|
layoutCtx = moustachu.newContext()
|
|
|
|
layoutCtx["title"] = title
|
|
layoutCtx["body"] = render(templ, ctx)
|
|
|
|
resp render(baseTemplate, layoutCtx)
|
|
|
|
template fail*(): expr =
|
|
var ctx = newContext()
|
|
ctx["exception"] = getCurrentExceptionMsg()
|
|
|
|
var
|
|
layoutCtx = moustachu.newContext()
|
|
|
|
layoutCtx["title"] = title
|
|
layoutCtx["body"] = render(templ, ctx)
|
|
|
|
halt render(baseTemplate, layoutCtx)
|
|
|
|
settings:
|
|
port = 5000.Port
|
|
bindAddr = "0.0.0.0"
|
|
|
|
routes:
|
|
get "/test":
|
|
renderMustache("test", testTemplate, newContext())
|
|
|
|
get "/":
|
|
let quotes = db.getAllRows(sql"SELECT * FROM quotes ORDER BY time desc LIMIT 20")
|
|
|
|
var
|
|
ctx = newContext()
|
|
quoteSeq = newSeq[Context]()
|
|
|
|
for quote in items(quotes):
|
|
var c = newContext()
|
|
|
|
c["listid"] = quote[0]
|
|
c["id"] = quote[0].parseInt().encodeURLSimple()
|
|
c["channel"] = quote[1]
|
|
c["channelsafe"] = quote[1].replace("#", "hashtag-")
|
|
c["nick"] = quote[2]
|
|
c["adder"] = quote[3]
|
|
c["message"] = quote[4]
|
|
c["time"] = parseInt(split(quote[5], '.')[0])
|
|
|
|
quoteSeq.add c
|
|
|
|
ctx["quotes"] = quoteSeq
|
|
|
|
renderMustache("most recent quotes", indexTemplate, ctx)
|
|
|
|
get "/quotes/@id":
|
|
var qid: int = 0
|
|
|
|
try:
|
|
qid = (@"id").parseInt
|
|
except:
|
|
qid = (@"id").decodeURLSimple()
|
|
redirect "/quotes/" & $qid
|
|
|
|
let quote = db.getRow(sql"SELECT * FROM quotes WHERE id = ?", qid)
|
|
|
|
if quote[1] == "":
|
|
halt Http404, "no such quote"
|
|
|
|
var
|
|
ctx = newContext()
|
|
|
|
ctx["listid"] = qid
|
|
ctx["id"] = quote[0].parseInt().encodeURLSimple()
|
|
ctx["channel"] = quote[1]
|
|
ctx["channelsafe"] = quote[1].replace("#", "hashtag-")
|
|
ctx["nick"] = quote[2]
|
|
ctx["adder"] = quote[3]
|
|
ctx["message"] = quote[4]
|
|
ctx["time"] = parseInt(split(quote[5], '.')[0])
|
|
|
|
ctx["last"] = qid - 1
|
|
ctx["next"] = qid + 1
|
|
|
|
renderMustache("quote #" & $qid & " by " & quote[2], quoteTemplate, ctx)
|
|
|
|
runForever()
|