summaryrefslogtreecommitdiff
path: root/bin/serve.fnl
blob: 67c3d7dd63518418aed31264ca363d90d44e03f6 (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
(import-macros {: map : reduce} :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 "&lt;" "<")
    (string.gsub "&gt;" ">")
    (string.gsub "&quot;" "\"")
    (string.gsub "&amp;" "&"))))

(fn site-name-template [name]
  (if
   (= name "ipuer")
    [:a {:class "site-icon" :href "https://ipuer.ru"}
     [:img {:src "/static/ipuer.jpg"}]
     "Институт чая пуэр"]
   (= name "artoftea")
    [:a {:class "site-icon" :href "https://artoftea.ru"}
     [:img {:src "/static/artoftea.png"}]
     "Art of tea"]
   (= name "ozchai")
    [:a {:class "site-icon" :href "https://ozchai.ru"}
     [:img {:src "/static/ozchai.ico"}]
     "Чайная #OZCHAI"]
   ""))

(fn item-template [product]
  [:div {:class "tile"}
   [:a {:href product.url :style "display: block;"}
    [:img {:src product.image} ""]]
   (site-name-template product.site)
   [:a {:href product.url :style "text-decoration: none;"}
    [:NO-ESCAPE (.. "<h2>" (unescape product.title) "</h2>")]]
   [:div {:class "price"}
    (if product.price (.. product.price "₽") "")
    (if product.quantity (.. " за " product.quantity "г") "")
    (if (and product.price-per
             (< 0 product.price-per))
     [:NO-ESCAPE (.. " (" product.price-per "₽ за&nbsp;1г)")]
     "")]
   [:small {} (or product.description "")]])

(fn paginator-template [query page limit total]
  (local last-page (math.ceil (/ total limit)))

  (if (< limit total)
    [:div {:class "paginator"}
     [:div {:class "paginator-numbers"}
      (if (< 1 page)
       [:a {:href (.. "?page=" (- page 1) "&query=" query)} "<"]
       "")
      (faccumulate [res [:span {}] i 1 last-page]
       (do
         (table.insert
           res [:a {:href (.. "?page=" i "&query=" query)
                    :class (if (= page i) "paginator-active" "")}
                (tostring i)])
         res))
      (if (< page last-page)
       [:a {:href (.. "?page=" (+ page 1) "&query=" query)} ">"]
       "")]
     [:div {} "Всего результатов: " [:strong {} (string.format "%d" total)]]]
    ""))

(fn base-template [query sort page total ...]
  (local paginator (paginator-template query 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 {:class "aside"}
       [:div {:class "aside-content"}
        [:a {:href "/" :style "display: block;"}
         [:img {:class "logo" :src "static/logo.svg" :alt "Логотип meicha.ru"}]]
        [:form {:class "form"}
         [:input {:type :search :name :query :value query
                  :autofocus true :placeholder "enter search query"}]
         [:button {:type :submit} "Искать"]]
        paginator]]
      [:section {}
       [:div {:class "list"} ...]
       [:footer {} paginator]]]]]])

(fn random-products [limit]
  (assert (< 0 limit) "limit must be > 0")
  (luna.db.query*
    db
    "SELECT id,
            site,
            title,
            description,
            image,
            url,
            price,
            weight,
            price_per AS \"price-per\",
            year
      FROM products
      ORDER BY RANDOM()
      LIMIT ?"
    [limit]))

(fn query-products [page query sorters]
  (local query
   (table.concat
    (map (fn [_ q]
           (if (. query-synonyms q)
             (.. "(" q "* OR " (. query-synonyms q) "*)")
             (.. q "*")))
         (str.split query))
    " "))
  (local total
   (luna.db.query
    db
    "SELECT count(*)
     FROM search
     WHERE search.`table` = 'products'
     AND search.name MATCH ?"
    [query]))

  {:results
    (luna.db.query*
        db
        "SELECT products.id,
                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
         FROM search
         INNER JOIN products ON search.fid = products.id
         WHERE search.`table` = 'products'
         AND search.name MATCH ?
         ORDER BY rank
         LIMIT 48 OFFSET ?"
        [query (* (- page 1) 48)])
   :total (if (< 0 (# total))
           (. total 1 1)
           0)})

(fn root-handler [{: path : query}]
  (if (= path "/")
    (let [headers {:content-type "text/html"}
          page (or (tonumber query.page) 1)
          search (or query.query "")
          sort "ASC"
          {: results : total}
            (if (~= "" search)
              (query-products page search sort)
              {:total 48 :results (random-products 48)})]
      (values
        200 headers
        (html.render
          (base-template
            search sort 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/")