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
|
(import-macros {: map : reduce : filter} :lib.macro)
(tset package :path (.. package.path ";./vendor/lpeglj/?.lua"))
(local io (require :io))
(local math (require :math))
(local fennel (require :vendor.fennel))
(local html (require :vendor.html))
(local json (require :vendor.json))
(local array (require :lib.array))
(local str (require :lib.string))
(local ozchai (require :parser.ozchai))
(local ipuer (require :parser.ipuer))
(local artoftea (require :parser.artoftea))
(when _G.unpack
(tset table :unpack _G.unpack))
(local db (luna.db.open "file:var/db.sqlite?_journal=WAL&_sync=NORMAL"))
(local query-synonyms {
"шэн" "шен"
"шен" "шэн"
"доска" "чабань"
"чабань" "доска"
"термос" "бутылка"
"бутылка" "термос"})
(fn unescape [s]
(assert (= (type s) :string) "s must be string")
(pick-values 1
(-> s
(string.gsub "<" "<")
(string.gsub ">" ">")
(string.gsub """ "\"")
(string.gsub "&" "&"))))
(fn random-products [limit]
(assert (< 0 limit) "limit must be > 0")
(luna.db.query*
db
"SELECT site,
title,
description,
image,
url,
price,
weight,
price_per AS \"price-per\",
year
FROM products
ORDER BY RANDOM()
LIMIT ?"
[limit]))
(fn all-tags []
(map
(fn [_ v] (. v 1))
(luna.db.query
db
"SELECT title FROM tags ORDER BY creation_time"
[])))
(fn query-products [page query tags]
(local tags (or tags []))
(var where-conds [])
(var where-vars [])
(when (< 0 (# tags))
(each [_ tag (pairs tags)]
(table.insert where-conds "product_tags.tag = ?")
(table.insert where-vars tag)))
(when (and query (< 0 (# query)))
(table.insert where-conds "search.title MATCH ?")
(table.insert where-vars
(array.join
(map (fn [_ q]
(if (. query-synonyms q)
(.. "(" q "* OR " (. query-synonyms q) "*)")
(.. q "*")))
(str.split query))
" AND ")))
(local where-sql (array.join where-conds "\nAND "))
(local total
(luna.db.query
db
(string.format
"SELECT count(*)
FROM search
LEFT JOIN product_tags ON product_tags.product = search.fid
WHERE search.`table` = 'products'
AND %s" where-sql)
where-vars))
{:results
(luna.db.query*
db
(string.format
"SELECT highlight(search, 0, '<i>', '</i>') AS \"title\",
products.site,
products.description,
products.image,
products.url,
products.price,
products.weight,
products.price_per AS \"price-per\",
products.year,
products.archived,
products.creation_time AS \"creation-time\"
FROM search
INNER JOIN products ON search.fid = products.url
LEFT JOIN product_tags ON product_tags.product = products.url
WHERE search.`table` = 'products'
AND %s
ORDER BY rank
LIMIT 48 OFFSET ?" where-sql)
(array.concat where-vars [(* (- page 1) 48)]))
:total (if (< 0 (# total))
(. total 1 1)
0)})
(fn site-name-template [name]
(if
(= name "ipuer")
[:a {:class "site-icon" :href "https://ipuer.ru"
:alt "Логотип Институт чай пуэр"}
[:img {:src "/static/ipuer.jpg"}]
"Институт чая пуэр"]
(= name "artoftea")
[:a {:class "site-icon" :href "https://artoftea.ru"
:alt "Логотип Art of tea"}
[:img {:src "/static/artoftea.png"}]
"Art of tea"]
(= name "ozchai")
[:a {:class "site-icon" :href "https://ozchai.ru"
:alt "Логотип #OZCHAI"}
[:img {:src "/static/ozchai.ico"}]
"Чайная #OZCHAI"]
(= name "clubcha")
[:a {:class "site-icon" :href "https://clubcha.ru"
:alt "Логотип Железный Феникс"}
[:img {:src "/static/clubcha.png"}]
"Железный Феникс"]
(= name "chaekshop")
[:a {:class "site-icon" :href "https://chaekshop.ru"
:alt "Логотип Интернет-магазин фермерского китайского чая «Чаёк»"}
[:img {:src "/static/chaekshop.svg"}]
"Интернет-магазин «Чаёк»"]
""))
(fn item-template [product]
[:div {:class "tile"}
[:a {:href product.url :style "display: block;" :rel "nofollow"}
[:img {:src product.image :title product.title :alt product.title} ""]]
(site-name-template product.site)
[:a {:href product.url :style "text-decoration: none;" :rel "nofollow"}
[:NO-ESCAPE (.. "<h2>" (unescape product.title) "</h2>")]]
[:div {:class "price"}
(if product.price (.. product.price "₽") "")
(if (< 0 product.weight)
[:NO-ESCAPE (.. "за " product.weight " гр.")]
"")
(if (and (< 1 product.weight)
product.price-per
(< 0 product.price-per))
[:NO-ESCAPE (.. " (" product.price-per "₽ за 1 гр.)")]
"")]
;; FIXME: security issue
[:small {} [:NO-ESCAPE (unescape (str.truncate product.description 200))]]])
(fn paginator-template [query tags page limit total]
(local last-page (math.ceil (/ total limit)))
(fn make-url [page query tags]
(.. "?page=" (tostring page)
"&query=" query
"&"
(array.join
(array.flatten
(map (fn [_ tag] (.. "tags=" tag))
tags))
"&")))
(if (< limit total)
[:div {:class "paginator"}
[:div {:class "paginator-numbers"}
(if (< 1 page)
[:a {:href (make-url (- page 1) query tags)} "←"]
"")
(faccumulate [res [:span {}] i 1 last-page]
(do
(table.insert
res [:a {:href (make-url i query tags)
:class (if (= page i) "paginator-active" "")}
(tostring i)])
res))
(if (< page last-page)
[:a {:href (make-url (+ page 1) query tags)} "→"]
"")]
[:div {} "Всего результатов: " [:strong {} (string.format "%d" total)]]]
""))
(fn aside-template [query tags paginator]
[:aside {:class "aside"}
[:div {:class "aside-content"}
(if (or (~= query "") (< 0 (# tags)))
[:a {:href "/" :style "display: block;"}
[:img {:class "logo" :src "static/logo.svg"
:alt "Логотип meicha.ru" :title "Логотип meicha.ru"}]]
[:img {:class "logo" :src "static/logo.svg"
:alt "Логотип meicha.ru" :title "Логотип meicha.ru"}])
[:form {:class "form"}
[:input {:type :search :name :query :value query
:autofocus true :placeholder "Поисковый запрос"}]
[:div {:class "form-tags"}
[:select {:class "form-tag" :name "tags"}
[:option {:value ""} "~ Категория ~"]
(table.unpack
(map
(fn [_ tag]
[:option {:value tag
:selected (if (array.contains tags tag) "selected" nil)}
tag])
(all-tags)))]]
[:button {:type :submit} "Искать"]]
paginator]])
(fn base-template [query tags page total ...]
(local paginator (paginator-template query tags page 48 total))
[:html {:lang "en"}
[:head {}
[:meta {:charset "UTF-8"}]
[:link {:rel :stylesheet :href "static/style.css"}]
[:title {} "A new cool web server for lua"]]
[:body {}
[:div {:class "container"}
[:div {:class "content"}
(aside-template query tags paginator)
[:section {}
[:div {:class "list"} ...]
[:footer {} paginator]]]]]])
(fn get-query-string [query key]
(if (and query
(. query key)
(. query key 1)
(< 0 (# (. query key 1))))
(. query key 1)
nil))
(fn get-query-number [query key]
(if (and query
(. query key)
(. query key 1))
(tonumber (. query key 1))
nil))
(fn root-handler [{: path : query}]
(if (= path "/")
(let [headers {:content-type "text/html"}
page (or (get-query-number query "page") 1)
search (str.trim (or (get-query-string query "query") ""))
tags (filter #(~= "" $2) (or query.tags []))
{: results : total}
(if (or (~= "" search) (< 0 (# tags)))
(query-products page search tags)
{:total 48 :results (random-products 48)})]
(values
200 headers
(html.render
(base-template
search tags page total
(table.unpack (map #(item-template $2) results)))
true)))
(values 404 {} "not found")))
(luna.router.route "GET /" root-handler)
(luna.router.static "GET /static/" "static/")
|