lineageos-ota-server/main.go
Steven Polley 8ef8b3d1be
All checks were successful
continuous-integration/drone/push Build is passing
do not recursively walk directories
2023-06-04 12:56:58 -06:00

172 lines
3.9 KiB
Go

package main
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"os"
"strings"
"sync"
)
// 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"`
}
type ROMCache struct {
ROMs []LineageOSROM
Cached map[string]bool // to quickly lookup if a file is already cached
sync.Mutex
}
var (
romCache ROMCache
)
// Preload cached list of files and hashes
func init() {
romCache = ROMCache{}
romCache.Cached = make(map[string]bool)
go updateROMCache("public")
}
// 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 updateROMCache(romDirectory string) {
f, err := os.Open(romDirectory)
if err != nil {
log.Printf("failed to open ROM directory: %v", err)
return
}
files, err := f.ReadDir(0)
if err != nil {
log.Printf("failed to read files in directory: %v", err)
return
}
for i, v := range files {
// skip directories
if v.Type().IsDir() {
continue
}
// skip non .zip files
if !strings.HasSuffix(v.Name(), ".zip") {
continue
}
// skip already cached files
romCache.Lock()
if _, ok := romCache.Cached[v.Name()]; ok {
romCache.Unlock()
continue
}
romCache.Unlock()
// Parse filename and skip files that can't be parsed
splitName := strings.Split(v.Name(), "-")
if len(splitName) != 5 {
continue
}
go func(v fs.DirEntry) {
fInfo, err := v.Info()
if err != nil {
log.Printf("failed to get file info '%s': %v", v.Name(), err)
return
}
fileHash, err := hashFile(fmt.Sprintf("%s/%s", romDirectory, v.Name()))
if err != nil {
log.Printf("ingore zip file '%s', failed to get sha256 hash: %v", v.Name(), err)
return
}
lineageOSROM := LineageOSROM{
Datetime: int(fInfo.ModTime().Unix()),
Filename: v.Name(),
ID: fileHash,
Romtype: "nightly",
Size: int(fInfo.Size()),
URL: fmt.Sprintf("https://lineageos-ota.deadbeef.codes/public/%s", v.Name()),
Version: splitName[1],
}
romCache.Lock()
if _, ok := romCache.Cached[v.Name()]; ok { // it's possible another goroutine was already working to cache the file, so we check at the end
romCache.Unlock()
return
}
romCache.ROMs = append(romCache.ROMs, lineageOSROM)
romCache.Cached[v.Name()] = true
romCache.Unlock()
}(files[i])
}
}
// 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) {
romCache.Lock()
lineageOSROMs := romCache.ROMs
romCache.Unlock()
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)
go updateROMCache("public")
}
func hashFile(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", fmt.Errorf("failed to open file '%s': %v: ", filename, err)
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", fmt.Errorf("failed to copy data from file to hash function: %v", err)
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}