/
web.go
242 lines (197 loc) · 5.12 KB
/
web.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
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
package web
import (
"bytes"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"path"
"time"
"golang.org/x/text/language"
ttemplate "text/template"
"github.com/alexedwards/scs"
"github.com/nicksnyder/go-i18n/i18n"
"github.com/pkg/errors"
"github.com/urandom/handler/lang"
"github.com/urandom/readeef/config"
"github.com/urandom/readeef/log"
)
const (
visitorKey = "visitor"
)
type e struct{}
func Mux(fs http.FileSystem, sessionManager *scs.Manager, config config.Config, log log.Log) (http.Handler, error) {
mux := http.NewServeMux()
if hasProxy(config) {
mux.Handle(
"/proxy",
http.TimeoutHandler(http.HandlerFunc(ProxyHandler(sessionManager)), 10*time.Second, ""),
)
}
fileServer := http.FileServer(fs)
mux.Handle("/", http.TimeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := sessionManager.Load(r)
err := session.PutBool(w, visitorKey, true)
if err != nil {
log.Printf("Error saving session: %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
current := path.Join("/", config.UI.Path, r.URL.Path)
path, err := closestParent(current, fs)
if err != nil {
log.Printf("Error getting file path for %s: %+v", r.URL.Path, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
r.URL.Path = path
// Firefox does not seem to be able to load its own cached files.
r.Header.Del("If-Modified-Since")
fileServer.ServeHTTP(w, r)
}), time.Second, ""))
return sessionManager.Use(mux), nil
}
func closestParent(p string, fs http.FileSystem) (string, error) {
f, err := fs.Open(p)
if err == nil {
stat, err := f.Stat()
f.Close()
if err != nil {
return "", errors.Wrapf(err, "getting file stat for %s", p)
}
if stat.IsDir() {
return p + "/", nil
}
return p, nil
}
return closestParent(path.Dir(p), fs)
}
func hasProxy(config config.Config) bool {
hasProxy := false
for _, p := range config.FeedParser.Processors {
if p == "proxy-http" {
hasProxy = true
break
}
}
if !hasProxy {
for _, p := range config.Content.Article.Processors {
if p == "proxy-http" {
hasProxy = true
break
}
}
}
return hasProxy
}
func requestFuncMaps(r *http.Request) template.FuncMap {
langData := lang.Data(r)
return template.FuncMap{
"__": func(message string, data ...interface{}) (template.HTML, error) {
if len(langData.Languages) == 0 {
return template.HTML(message), nil
}
return t(message, langData.Current.String(), "en-US", data...)
},
"url": func(url string, prefix ...string) string {
var p string
if len(prefix) > 0 {
p = prefix[0]
}
return lang.URL(url, p, langData)
},
}
}
func prepareTemplate(t *template.Template, fs http.FileSystem, paths ...string) (*template.Template, error) {
t = t.Funcs(template.FuncMap{
"__": func(message string, data ...interface{}) (template.HTML, error) {
return template.HTML(message), nil
},
"url": func(url string, prefix ...string) string {
return url
},
}).Delims("{%", "%}")
for _, path := range paths {
f, err := fs.Open(path)
if err != nil {
return nil, errors.Wrapf(err, "opening template %s", path)
}
t, err = parseTemplate(t, f)
if err != nil {
f.Close()
return nil, errors.WithMessage(err, fmt.Sprintf("parsing template %s", path))
}
if err = f.Close(); err != nil {
return nil, errors.Wrapf(err, "closing template %s", path)
}
}
return t, nil
}
func parseTemplate(t *template.Template, r io.Reader) (*template.Template, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.Wrap(err, "reading template data from reader")
}
if t, err = t.Parse(string(b)); err != nil {
return nil, errors.Wrap(err, "parsing template data")
}
return t, nil
}
func t(message, lang, fallback string, data ...interface{}) (template.HTML, error) {
var count interface{}
hasCount := false
if len(data)%2 == 1 {
if !isNumber(data[0]) {
return "", errors.New("The count argument must be a number")
}
count = data[0]
hasCount = true
data = data[1:]
}
dataMap := map[string]interface{}{}
for i := 0; i < len(data); i += 2 {
dataMap[data[i].(string)] = data[i+1]
}
T, err := i18n.Tfunc(lang, fallback)
if err != nil {
return "", err
}
var translated string
if hasCount {
translated = T(message, count, dataMap)
} else {
translated = T(message, dataMap)
}
if translated == message {
// Doesn't have a translation mapping, we have to do the template evaluation by hand
t, err := ttemplate.New("i18n").Parse(message)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := t.Execute(&buf, dataMap); err != nil {
return "", err
}
return template.HTML(buf.String()), nil
} else {
return template.HTML(translated), nil
}
}
func isNumber(n interface{}) bool {
switch n.(type) {
case int, int8, int16, int32, int64, string:
return true
}
return false
}
func languageTags(langs []string) []language.Tag {
tags := make([]language.Tag, 0, len(langs))
for _, l := range langs {
tag := language.Make(l)
if !tag.IsRoot() {
tags = append(tags, tag)
}
}
return tags
}