cleaned up some code

This commit is contained in:
BroodjeAap 2020-07-06 19:49:48 +00:00
parent 7a8a7dc631
commit bd69f7b914

64
main.go
View file

@ -10,6 +10,7 @@ import (
"os"
"path/filepath"
"text/template"
"time"
"gocv.io/x/gocv"
)
@ -46,26 +47,17 @@ func stream(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Content-Type", "image/jpeg")
URL := r.FormValue("URL")
resp, err := http.Get(URL)
if err != nil {
log.Fatal(err)
}
img, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
img := getStreamInstant(URL)
// TODO async for this?
saveStreamInstant(URL, img)
h := sha256.New()
h.Write([]byte(URL))
streamDir := base64.URLEncoding.EncodeToString(h.Sum(nil))
streamDir := URLToBase64(URL)
streamStoreDir := filepath.Join(".", "streams", string(streamDir))
previousStreamInstantPath := filepath.Join(streamStoreDir, "previous.jpg")
_, err = os.Stat(previousStreamInstantPath)
previousExists := !os.IsNotExist(err)
if previousExists {
if fileExists(previousStreamInstantPath) {
newMat := gocv.NewMat()
mat, err := gocv.IMDecode(img, gocv.IMReadColor)
@ -91,24 +83,33 @@ func stream(w http.ResponseWriter, r *http.Request) {
w.Write(img)
}
func getStreamInstant(URL string) []byte {
resp, err := http.Get(URL)
if err != nil {
log.Fatal(err)
}
img, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
return img
}
func saveStreamInstant(URL string, img []byte) {
h := sha256.New()
h.Write([]byte(URL))
streamDir := base64.URLEncoding.EncodeToString(h.Sum(nil))
streamDir := URLToBase64(URL)
streamStoreDir := filepath.Join(".", "streams", string(streamDir))
os.MkdirAll(streamStoreDir, os.ModePerm)
currentStreamInstantPath := filepath.Join(streamStoreDir, "current.jpg")
_, err := os.Stat(currentStreamInstantPath)
swap := !os.IsNotExist(err)
swap := fileExists(streamStoreDir)
if swap {
currentStreamInstantPath = filepath.Join(streamStoreDir, "next.jpg")
}
err = ioutil.WriteFile(currentStreamInstantPath, img, os.ModePerm)
err := ioutil.WriteFile(currentStreamInstantPath, img, os.ModePerm)
if err != nil {
log.Fatal("Can't write latest stream instant.")
}
if swap {
previousStreamInstantPath := filepath.Join(streamStoreDir, "previous.jpg")
nextStreamInstantPath := currentStreamInstantPath
@ -119,7 +120,7 @@ func saveStreamInstant(URL string, img []byte) {
}
}
func main() {
func listenAndServe() {
staticFileServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", staticFileServer))
@ -127,3 +128,26 @@ func main() {
http.HandleFunc("/stream", stream)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func backend() {
for {
time.Sleep(time.Second)
}
}
func main() {
go listenAndServe()
backend()
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
func URLToBase64(URL string) (hash string) {
h := sha256.New()
h.Write([]byte(URL))
return base64.URLEncoding.EncodeToString(h.Sum(nil))
}