-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.go
183 lines (164 loc) · 4.88 KB
/
server.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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
"os/exec"
"path"
"path/filepath"
"time"
"github.com/machinebox/sdk-go/facebox"
"github.com/matryer/way"
)
// Server is the app server.
type Server struct {
assets string
videos string
items *Items // here the video items on the filesystem
facebox *facebox.Client
router *way.Router
}
// NewServer makes a new Server.
func NewServer(assets string, videos string, facebox *facebox.Client) *Server {
srv := &Server{
assets: assets,
videos: videos,
items: LoadItemsFromPath(videos),
facebox: facebox,
router: way.NewRouter(),
}
srv.router.Handle(http.MethodGet, "/assets/", Static("/assets/", assets))
srv.router.Handle(http.MethodGet, "/videos/", Static("/videos/", videos))
srv.router.HandleFunc(http.MethodGet, "/stream", srv.stream)
srv.router.HandleFunc(http.MethodGet, "/check", srv.check)
srv.router.HandleFunc(http.MethodGet, "/all-videos/", srv.handleListVideos)
srv.router.HandleFunc(http.MethodGet, "/", srv.handleIndex)
return srv
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join(s.assets, "index.html"))
}
func (s *Server) handleListVideos(w http.ResponseWriter, r *http.Request) {
var res struct {
Items []Item `json:"items"`
}
res.Items = s.items.List()
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(res); err != nil {
log.Printf("[ERROR] encondig response %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
type Frame struct {
Frame int `json:"frame"`
Total int `json:"total"`
Millis int `json:"millis"`
Image string `json:"image"`
}
type VideoData struct {
Frame int `json:"frame,omitempty"`
TotalFrames int `json:"total_frames,omitempty"`
Seconds string `json:"seconds,omitempty"`
Complete bool `json:"complete,omitempty"`
Faces []facebox.Face `json:"faces,omitempty"`
Thumbnail *string `json:"thumbnail,omitempty"`
}
func (s *Server) check(w http.ResponseWriter, r *http.Request) {
var thumbnail *string
// sent the headers for Server Side Events
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
enc := json.NewEncoder(w)
// starts the video processing script
filename := r.URL.Query().Get("name")
flags := []string{"--path", path.Join(s.videos, filename), "--json", "True"}
cmd := exec.CommandContext(r.Context(), "./video.py", flags...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println("[ERROR] Getting the stdout pipe")
return
}
cmd.Start()
total := 0
dec := json.NewDecoder(stdout)
for {
var f Frame
err := dec.Decode(&f)
if err == io.EOF {
log.Println("[DEBUG] EOF", err)
break
}
if err != nil {
log.Println("[ERROR]", err)
break
}
imgDec, err := base64.StdEncoding.DecodeString(f.Image)
if err != nil {
log.Printf("[ERROR] Error decoding the image %v\n", err)
http.Error(w, "can not decode the image", http.StatusInternalServerError)
return
}
faces, err := s.facebox.Check(bytes.NewReader(imgDec))
total = f.Total
thumbnail = nil
for _, face := range faces {
if face.Matched {
thumbnail = &f.Image
}
}
SendEvent(w, enc, VideoData{
Frame: f.Frame,
TotalFrames: f.Total,
Seconds: (time.Duration(f.Millis/1000) * time.Second).String(),
Complete: false,
Faces: faces,
Thumbnail: thumbnail,
})
}
cmd.Wait()
SendEvent(w, enc, VideoData{
Frame: total,
TotalFrames: total,
Complete: true,
})
}
func SendEvent(w http.ResponseWriter, enc *json.Encoder, v interface{}) {
w.Write([]byte("data: "))
if err := enc.Encode(v); err != nil {
log.Printf("[ERROR] Error encoding json %v\n", err)
http.Error(w, "can not encode the json stream", http.StatusInternalServerError)
return
}
w.Write([]byte("\n\n"))
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
const boundary = "informs"
w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary="+boundary)
filename := r.URL.Query().Get("name")
flags := []string{"--path", path.Join(s.videos, filename)}
cmd := exec.CommandContext(r.Context(), "./video.py", flags...)
cmd.Stdout = w
err := cmd.Run()
if err != nil {
log.Println("[ERROR] streaming the video", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Static gets a static file server for the specified path.
func Static(stripPrefix, dir string) http.Handler {
h := http.StripPrefix(stripPrefix, http.FileServer(http.Dir(dir)))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
})
}