forked from thomiceli/opengist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
216 lines (176 loc) · 5.19 KB
/
util.go
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
package web
import (
"context"
"errors"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
"github.com/thomiceli/opengist/internal/config"
"github.com/thomiceli/opengist/internal/db"
"github.com/thomiceli/opengist/internal/i18n"
"html/template"
"net/http"
"strconv"
"strings"
)
type dataTypeKey string
const dataKey dataTypeKey = "data"
func setData(ctx echo.Context, key string, value any) {
data := ctx.Request().Context().Value(dataKey).(echo.Map)
data[key] = value
ctxValue := context.WithValue(ctx.Request().Context(), dataKey, data)
ctx.SetRequest(ctx.Request().WithContext(ctxValue))
}
func getData(ctx echo.Context, key string) any {
data := ctx.Request().Context().Value(dataKey).(echo.Map)
return data[key]
}
func dataMap(ctx echo.Context) echo.Map {
return ctx.Request().Context().Value(dataKey).(echo.Map)
}
func html(ctx echo.Context, template string) error {
return htmlWithCode(ctx, 200, template)
}
func htmlWithCode(ctx echo.Context, code int, template string) error {
setErrorFlashes(ctx)
return ctx.Render(code, template, ctx.Request().Context().Value(dataKey))
}
func redirect(ctx echo.Context, location string) error {
return ctx.Redirect(302, config.C.ExternalUrl+location)
}
func plainText(ctx echo.Context, code int, message string) error {
return ctx.String(code, message)
}
func notFound(message string) error {
return errorRes(404, message, nil)
}
func errorRes(code int, message string, err error) error {
return &echo.HTTPError{Code: code, Message: message, Internal: err}
}
func getUserLogged(ctx echo.Context) *db.User {
user := getData(ctx, "userLogged")
if user != nil {
return user.(*db.User)
}
return nil
}
func setErrorFlashes(ctx echo.Context) {
sess, _ := flashStore.Get(ctx.Request(), "flash")
setData(ctx, "flashErrors", sess.Flashes("error"))
setData(ctx, "flashSuccess", sess.Flashes("success"))
_ = sess.Save(ctx.Request(), ctx.Response())
}
func addFlash(ctx echo.Context, flashMessage string, flashType string) {
sess, _ := flashStore.Get(ctx.Request(), "flash")
sess.AddFlash(flashMessage, flashType)
_ = sess.Save(ctx.Request(), ctx.Response())
}
func getSession(ctx echo.Context) *sessions.Session {
sess, _ := userStore.Get(ctx.Request(), "session")
return sess
}
func saveSession(sess *sessions.Session, ctx echo.Context) {
_ = sess.Save(ctx.Request(), ctx.Response())
}
func deleteSession(ctx echo.Context) {
sess := getSession(ctx)
sess.Options.MaxAge = -1
sess.Values["user"] = nil
saveSession(sess, ctx)
}
func setCsrfHtmlForm(ctx echo.Context) {
if csrfToken, ok := ctx.Get("csrf").(string); ok {
setData(ctx, "csrfHtml", template.HTML(`<input type="hidden" name="_csrf" value="`+csrfToken+`">`))
}
}
func deleteCsrfCookie(ctx echo.Context) {
ctx.SetCookie(&http.Cookie{Name: "_csrf", Path: "/", MaxAge: -1})
}
func loadSettings(ctx echo.Context) error {
settings, err := db.GetSettings()
if err != nil {
return err
}
for key, value := range settings {
s := strings.ReplaceAll(key, "-", " ")
s = title.String(s)
setData(ctx, strings.ReplaceAll(s, " ", ""), value == "1")
}
return nil
}
func getPage(ctx echo.Context) int {
page := ctx.QueryParam("page")
if page == "" {
page = "1"
}
pageInt, err := strconv.Atoi(page)
if err != nil {
pageInt = 1
}
setData(ctx, "currPage", pageInt)
return pageInt
}
func paginate[T any](ctx echo.Context, data []*T, pageInt int, perPage int, templateDataName string, urlPage string, labels int, urlParams ...string) error {
lenData := len(data)
if lenData == 0 && pageInt != 1 {
return errors.New("page not found")
}
if lenData > perPage {
if lenData > 1 {
data = data[:lenData-1]
}
setData(ctx, "nextPage", pageInt+1)
}
if pageInt > 1 {
setData(ctx, "prevPage", pageInt-1)
}
if len(urlParams) > 0 {
setData(ctx, "urlParams", template.URL(urlParams[0]))
}
switch labels {
case 1:
setData(ctx, "prevLabel", tr(ctx, "pagination.previous"))
setData(ctx, "nextLabel", tr(ctx, "pagination.next"))
case 2:
setData(ctx, "prevLabel", tr(ctx, "pagination.newer"))
setData(ctx, "nextLabel", tr(ctx, "pagination.older"))
}
setData(ctx, "urlPage", urlPage)
setData(ctx, templateDataName, data)
return nil
}
func tr(ctx echo.Context, key string) template.HTML {
l := getData(ctx, "locale").(*i18n.Locale)
return l.Tr(key)
}
func parseSearchQueryStr(query string) (string, map[string]string) {
words := strings.Fields(query)
metadata := make(map[string]string)
var contentBuilder strings.Builder
for _, word := range words {
if strings.Contains(word, ":") {
keyValue := strings.SplitN(word, ":", 2)
if len(keyValue) == 2 {
key := keyValue[0]
value := keyValue[1]
metadata[key] = value
}
} else {
contentBuilder.WriteString(word + " ")
}
}
content := strings.TrimSpace(contentBuilder.String())
return content, metadata
}
func addMetadataToSearchQuery(input, key, value string) string {
content, metadata := parseSearchQueryStr(input)
metadata[key] = value
var resultBuilder strings.Builder
resultBuilder.WriteString(content)
for k, v := range metadata {
resultBuilder.WriteString(" ")
resultBuilder.WriteString(k)
resultBuilder.WriteString(":")
resultBuilder.WriteString(v)
}
return strings.TrimSpace(resultBuilder.String())
}