lineageos-ota-server/main.go
Steven Polley 7b2fb2847b
Some checks failed
continuous-integration/drone/push Build is failing
add build badge
2023-06-03 23:08:49 -06:00

116 lines
2.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
// Information for a LineageOS ROM available for download
type LineageOSROM struct {
Datetime int `json:"datetime"`
Filename string `json:"filename"`
ID string `json:"id"`
Romtype string `json:"romtype"`
Size int `json:"size"`
URL string `json:"url"`
Version string `json:"version"`
}
// The HTTP response JSON should be a JSON array of lineageOSROMS available for download
type HttpResponseJSON struct {
Response []LineageOSROM `json:"response"`
}
// HTTP Routing
func main() {
//Public static files
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
// ROM list
http.HandleFunc("/", lineageOSROMListHandler)
log.Print("Service listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
// Reads the ROM files on the filesystem and populates a slice of linageOSROMs
func getLineageOSROMs(romDirectory string) ([]LineageOSROM, error) {
if _, err := os.Stat(romDirectory); os.IsNotExist(err) {
return nil, fmt.Errorf("romDirectory '%s' does not exist", romDirectory)
}
// Get all the zip files and populate romFileNames slice
var lineageOSROMs []LineageOSROM
err := filepath.WalkDir(romDirectory, func(s string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("walk error occured during file '%s': %v", d.Name(), err)
}
if filepath.Ext(d.Name()) != ".zip" {
return nil
}
fInfo, err := d.Info()
if err != nil {
return fmt.Errorf("failed to get file info '%s': %v", d.Name(), err)
}
// Get information about file and populate rom
splitName := strings.Split(d.Name(), "-")
if len(splitName) != 5 {
log.Printf("ignoring zip file '%d', name is not formatted correctly ")
}
lineageOSROM := LineageOSROM{
Datetime: int(fInfo.ModTime().Unix()),
Filename: d.Name(),
ID: "TBD",
Romtype: "nightly",
Size: int(fInfo.Size()),
URL: fmt.Sprintf("https://lineageos-updater.deadbeef.codes/public/%s", d.Name()),
Version: "TBD",
}
lineageOSROMs = append(lineageOSROMs, lineageOSROM)
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to walk romDirectory '%s': %v", romDirectory, err)
}
return lineageOSROMs, nil
}
// http - GET /
// Writes JSON response for the updater app to know what versions are available to download
func lineageOSROMListHandler(w http.ResponseWriter, r *http.Request) {
lineageOSROMs, err := getLineageOSROMs("public")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("failed to get lineageOSROMs: %v", err)
return
}
httpResponseJSON := &HttpResponseJSON{Response: lineageOSROMs}
b, err := json.Marshal(httpResponseJSON)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("failed to marshal lineageOSROMs to json: %v", err)
return
}
w.Write(b)
}