-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.go
121 lines (102 loc) · 2.58 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
116
117
118
119
120
121
package application
import (
"net/http"
"os"
"path/filepath"
"github.com/fatih/set"
"github.com/tympanix/supper/api"
"github.com/tympanix/supper/list"
"github.com/tympanix/supper/media"
"github.com/tympanix/supper/provider"
"github.com/tympanix/supper/types"
"github.com/urfave/cli"
"golang.org/x/text/language"
)
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
context *cli.Context
}
func New(context *cli.Context) types.App {
app := &Application{
Provider: provider.Subscene(),
ServeMux: http.NewServeMux(),
context: context,
}
static := context.String("static")
api := api.New(app)
app.ServeMux.Handle("/api/", http.StripPrefix("/api", api))
fs := WebAppHandler(static)
app.ServeMux.Handle("/", fs)
return app
}
// Context returns the CLI context of the application (e.g. flags, args ect.)
func (a *Application) Context() *cli.Context {
return a.context
}
func (a *Application) Languages() set.Interface {
// Parse all language flags into slice of tags
lang := set.New()
for _, tag := range a.Context().GlobalStringSlice("lang") {
_lang, err := language.Parse(tag)
if err != nil {
os.Exit(5)
}
lang.Add(_lang)
}
return lang
}
// 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)
}
})
}
func fileIsMedia(f os.FileInfo) bool {
for _, ext := range filetypes {
if ext == filepath.Ext(f.Name()) {
return true
}
}
return false
}
// 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.IsDir() {
return nil
}
if !fileIsMedia(f) {
return nil
}
_media, err := media.New(filepath)
if err != nil {
return nil
}
if media.IsSample(_media) {
return nil
}
medialist = append(medialist, _media)
return nil
})
if err != nil {
return nil, err
}
}
return list.NewLocalMedia(medialist...), nil
}