-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.go
115 lines (96 loc) · 2.52 KB
/
app.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
package app
import (
"errors"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/spf13/viper"
"github.com/tympanix/supper/api"
"github.com/tympanix/supper/cfg"
"github.com/tympanix/supper/list"
"github.com/tympanix/supper/media"
"github.com/tympanix/supper/types"
)
var filetypes = []string{
".avi", ".mkv", ".mp4", ".m4v", ".flv", ".mov", ".wmv", ".webm", ".mpg", ".mpeg",
}
// Application is an configuration instance of the application
type Application struct {
types.Provider
*http.ServeMux
cfg types.Config
scrapers []types.Scraper
}
// New returns a new application from the cli context
func New(cfg types.Config) *Application {
app := &Application{
Provider: cfg.Providers()[0],
cfg: cfg,
ServeMux: http.NewServeMux(),
scrapers: cfg.Scrapers(),
}
static := viper.GetString("static")
api := api.New(app)
app.ServeMux.Handle("/api/", http.StripPrefix("/api", api))
fs := WebAppHandler(static)
app.ServeMux.Handle("/", fs)
return app
}
// NewFromDefault construct an application using the default config
func NewFromDefault() types.App {
return New(cfg.Default)
}
// Config returns the configuration for the application
func (a *Application) Config() types.Config {
return a.cfg
}
// WebAppHandler serves a single-page web application
func WebAppHandler(path string) http.Handler {
files := http.FileServer(http.Dir(path))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uri := filepath.Join(path, r.URL.Path)
if _, err := os.Stat(uri); os.IsNotExist(err) {
http.ServeFile(w, r, filepath.Join(path, "index.html"))
} else {
files.ServeHTTP(w, r)
}
})
}
// Scrapers returns the list of supported scrapers
func (a *Application) Scrapers() []types.Scraper {
return a.scrapers
}
// FindMedia searches for media files
func (a *Application) FindMedia(roots ...string) (types.LocalMediaList, error) {
medialist := make([]types.LocalMedia, 0)
for _, root := range roots {
if _, err := os.Stat(root); os.IsNotExist(err) {
return nil, err
}
err := filepath.Walk(root, func(filepath string, f os.FileInfo, err error) error {
if f == nil {
return errors.New("invalid file path")
}
if f.IsDir() {
return nil
}
if strings.HasPrefix(f.Name(), ".") {
return nil
}
med, err := media.NewLocalFile(filepath)
if err != nil {
return nil
}
if media.IsSample(med) {
return nil
}
medialist = append(medialist, med)
return nil
})
if err != nil {
return nil, err
}
}
return list.NewLocalMedia(medialist...), nil
}