forked from gerow/sbserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsbserv.go
436 lines (374 loc) · 9.47 KB
/
sbserv.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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package main
import (
"archive/zip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"syscall"
)
type FileRef struct {
Path string
Name string
ModTime string
Size int64
Glyphicon string
Type string
IsDir bool `json:"-"`
VideoType string `json:"-"`
Extra map[string]interface{}
}
type Id3Extra struct {
Title string
Artist string
Album string
Year string
Genre string
Comments []string
}
type Page struct {
Path string
FileRefs []FileRef `json:"Files"`
VHash string
}
var cwd string
var dirListingTemplate *template.Template
var vhash string
var fileServerHandler http.Handler
var fileCache *FileCache
var id3Cache *Id3Cache
type ByName []FileRef
func (a ByName) Len() int {
return len(a)
}
func (a ByName) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByName) Less(i, j int) bool {
return a[i].Name < a[j].Name
}
func MakeFileRef(leadingPath string, f os.FileInfo) FileRef {
var fr FileRef
fr.Name = f.Name()
fr.Path = path.Join(leadingPath, f.Name())
const layout = "2006-01-02 15:04:05"
fr.ModTime = string(f.ModTime().Format(layout))
fr.Size = f.Size()
fr.Glyphicon = "glyphicon-file"
fr.Extra = make(map[string]interface{})
if f.Mode().IsDir() {
fr.Glyphicon = "glyphicon-folder-open"
fr.IsDir = true
fr.Type = "directory"
} else {
fr.IsDir = false
fr.Type = "file"
ext := filepath.Ext(fr.Path)
switch {
case ext == ".mp3":
fallthrough
case ext == ".ogg":
fallthrough
case ext == ".flac":
fr.Glyphicon = "glyphicon-music"
case ext == ".jpg":
fallthrough
case ext == ".jepg":
fallthrough
case ext == ".png":
fallthrough
case ext == ".bmp":
fallthrough
case ext == ".gif":
fr.Glyphicon = "glyphicon-picture"
case ext == ".avi":
fallthrough
case ext == ".flv":
fallthrough
case ext == ".mpeg":
fallthrough
case ext == ".mpg":
fallthrough
case ext == ".mpe":
fallthrough
case ext == ".ogv":
fallthrough
case ext == ".mkv":
fr.Glyphicon = "glyphicon-film"
case ext == ".mov":
fallthrough
case ext == ".m4v":
fallthrough
case ext == ".mp4":
fr.VideoType = "video/mp4"
fr.Glyphicon = "glyphicon-film"
case ext == ".zip":
fallthrough
case ext == ".tar":
fallthrough
case ext == ".gz":
fallthrough
case ext == ".rar":
fr.Glyphicon = "glyphicon-compressed"
case ext == ".epub":
fallthrough
case ext == ".mobi":
fallthrough
case ext == ".pdf":
fr.Glyphicon = "glyphicon-book"
}
if ext == ".mp3" {
extra, err := id3Cache.Get(path.Join(cwd, fr.Path))
if err == nil {
fr.Extra["id3"] = *extra
}
}
}
return fr
}
func handleDir(file *os.File, p string, w http.ResponseWriter, r *http.Request) {
// Read the directory
fi, err := file.Readdir(-1)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var page Page
page.Path = r.URL.Path
page.VHash = vhash
for _, f := range fi {
fr := MakeFileRef(r.URL.Path, f)
page.FileRefs = append(page.FileRefs, fr)
}
sort.Sort(ByName(page.FileRefs))
if r.FormValue("format") == "json" {
w.Header().Set("Content-Type", "application/json")
jsonForm, err := json.Marshal(page)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, string(jsonForm))
} else {
dirListingTemplate.Execute(w, page)
}
}
func writeDir(file *os.File, p string, prefix string, zw *zip.Writer, w http.ResponseWriter) {
log.Printf("Creating dir from %s with prefix %s\n", p, prefix)
fi, err := file.Readdir(-1)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, fiEntry := range fi {
f, err := os.Open(path.Join(p, fiEntry.Name()))
if err != nil {
log.Println(err.Error())
continue
}
defer f.Close()
if fiEntry.IsDir() {
log.Printf("Creating subdirectory for %v\n", fiEntry)
writeDir(f, path.Join(p, fiEntry.Name()), path.Join(prefix, fiEntry.Name()), zw, w)
continue
}
fileWriter, err := zw.Create(path.Join(prefix, fiEntry.Name()))
if err != nil {
log.Println(err.Error())
continue
}
io.Copy(fileWriter, f)
}
}
func handleDownloadDir(file *os.File, p string, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/zip")
zw := zip.NewWriter(w)
defer zw.Close()
f, err := os.Open(p)
defer f.Close()
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
writeDir(f, p, "", zw, w)
}
func handleFile(file *os.File, p string, w http.ResponseWriter, r *http.Request, fi os.FileInfo) {
//io.Copy(w, file)
//fileServerHandler.ServeHTTP(w, r)
etagBytes := sha256.Sum256([]byte(fi.ModTime().String()))
etag := hex.EncodeToString(etagBytes[:len(etagBytes)])
w.Header().Set("ETag", etag)
http.ServeContent(w, r, p, fi.ModTime(), file)
}
func handleStatic(p string, w http.ResponseWriter, r *http.Request) {
p = strings.TrimPrefix(p, "/_static/"+vhash)
log.Printf("Got request for static asset %s", p)
assetPath := path.Join("data/static/", p)
log.Printf("Using path %s", assetPath)
assetBytes, err := Asset(assetPath)
if err != nil {
log.Println("Received request for static file we don't have")
http.Error(w, "No such static asset", http.StatusNotFound)
return
}
log.Printf("Using extension %s", filepath.Ext(p))
switch ext := filepath.Ext(p); {
case ext == ".css":
w.Header().Set("Content-Type", "text/css")
case ext == ".js":
w.Header().Set("Content-Type", "text/javascript")
case ext == ".png":
w.Header().Set("Content-Type", "image/png")
}
// Don't ever expire
w.Header().Set("Cache-Control", "public")
// Or at least don't expire until the AI machines take over. They
// can deal with fixing this.
w.Header().Set("Expires", "Sun, 17-Jan-2038 19:14:07 GMT")
fmt.Fprint(w, string(assetBytes))
}
func handleSearch(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println(err)
http.Error(w, "Invalid form data", http.StatusBadRequest)
return
}
queries, ok := r.Form["query"]
if !ok {
log.Println("Received search request without query argument")
http.Error(w, "Search requires query argument", http.StatusBadRequest)
return
}
if len(queries) != 1 {
log.Println("Received multiple query arguments")
http.Error(w, "Search requires one and only one query argument", http.StatusBadRequest)
return
}
query := queries[0]
log.Printf("got search request for \"%s\"", query)
fileRefs, err := fileCache.Search(query)
if err != nil {
log.Println(err)
http.Error(w, "invalid regex", http.StatusBadRequest)
return
}
page := Page{
Path: "/_search query: " + query,
FileRefs: fileRefs,
VHash: vhash,
}
if r.FormValue("format") == "json" {
w.Header().Set("Content-Type", "application/json")
jsonForm, err := json.Marshal(page)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, string(jsonForm))
return
}
dirListingTemplate.Execute(w, page)
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("Dumping header values:")
for k, v := range r.Header {
log.Printf("%s - %s\n", k, v)
}
p := path.Join(cwd, r.URL.Path)
p = path.Clean(p)
if !strings.HasPrefix(p, cwd) {
log.Println("Received request for file outside serve root.")
http.Error(w, "Refusing to serve path outside serve root.", http.StatusBadRequest)
return
}
// determine if this is a request for assets
if strings.HasPrefix(r.URL.Path, "/_static/") {
handleStatic(r.URL.Path, w, r)
return
}
// determine if this is a search request
if r.URL.Path == "/_search" {
handleSearch(w, r)
return
}
file, err := os.Open(p)
defer file.Close()
if err != nil {
log.Println(err.Error())
if (err.(*os.PathError)).Err == syscall.ENOENT {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
fi, err := file.Stat()
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
switch mode := fi.Mode(); {
case mode.IsDir():
log.Printf("Handling %s as a directory\n", p)
if r.FormValue("dldir") == "true" {
handleDownloadDir(file, p, w, r)
} else {
handleDir(file, p, w, r)
}
case mode.IsRegular():
log.Printf("Handling %s as a regular file\n", p)
handleFile(file, p, w, r, fi)
default:
log.Println("Received attempt to serve non-regular file")
http.Error(w, "Refusing to read a non-regular file.", http.StatusBadRequest)
return
}
}
func main() {
var err error
log.Printf("starting")
cwd, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
// Parse the dir listing template
dirListingBytes, err := Asset("data/templates/dir_listing.html")
if err != nil {
log.Fatal(err)
}
dirListingTemplate, err = template.New("dir_listing.html").Parse(string(dirListingBytes))
if err != nil {
log.Fatal(err)
}
vhashBytes, err := Asset("data/version_hash")
if err != nil {
log.Fatal(err)
}
vhash = string(vhashBytes)
if len(os.Args) != 2 {
log.Fatal("must specify bind address")
}
bindAddress := os.Args[1]
fileServerHandler = http.FileServer(http.Dir(cwd))
// Start the id3 cache daemon
id3Cache = NewId3Cache()
// Start the file cache daemon
fileCache = NewFileCache(cwd)
http.HandleFunc("/", handler)
http.ListenAndServe(bindAddress, nil)
}