lineageos-ota-server/main.go

171 lines
3.9 KiB
Go
Raw Normal View History

2023-06-04 05:07:55 +00:00
package main
import (
2023-06-04 15:32:23 +00:00
"crypto/sha256"
2023-06-04 05:07:55 +00:00
"encoding/json"
"fmt"
2023-06-04 15:32:23 +00:00
"io"
2023-06-04 05:07:55 +00:00
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"strings"
2023-06-04 18:32:18 +00:00
"sync"
2023-06-04 05:07:55 +00:00
)
// 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
2023-06-04 18:32:18 +00:00
type HTTPResponseJSON struct {
2023-06-04 05:07:55 +00:00
Response []LineageOSROM `json:"response"`
}
2023-06-04 18:32:18 +00:00
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() {
2023-06-04 18:41:22 +00:00
romCache = ROMCache{}
2023-06-04 18:35:27 +00:00
romCache.Cached = make(map[string]bool)
2023-06-04 18:32:18 +00:00
go updateROMCache("public")
}
2023-06-04 05:07:55 +00:00
// HTTP Routing
func main() {
//Public static files
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
// ROM list
2023-06-04 05:08:49 +00:00
http.HandleFunc("/", lineageOSROMListHandler)
2023-06-04 05:07:55 +00:00
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
2023-06-04 18:32:18 +00:00
func updateROMCache(romDirectory string) {
2023-06-04 05:07:55 +00:00
if _, err := os.Stat(romDirectory); os.IsNotExist(err) {
2023-06-04 18:32:18 +00:00
log.Printf("romDirectory '%s' does not exist", romDirectory)
return
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:32:18 +00:00
wg := sync.WaitGroup{}
2023-06-04 05:07:55 +00:00
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)
2023-06-04 18:32:18 +00:00
2023-06-04 05:07:55 +00:00
}
if filepath.Ext(d.Name()) != ".zip" {
return nil
}
2023-06-04 18:32:18 +00:00
// skip already cached files
romCache.Lock()
2023-06-04 18:41:22 +00:00
if _, ok := romCache.Cached[d.Name()]; ok {
2023-06-04 18:32:18 +00:00
romCache.Unlock()
return nil
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:32:18 +00:00
romCache.Unlock()
2023-06-04 05:07:55 +00:00
// Get information about file and populate rom
splitName := strings.Split(d.Name(), "-")
if len(splitName) != 5 {
2023-06-04 05:29:40 +00:00
log.Printf("ignoring zip file '%s', name is not formatted correctly", d.Name())
return nil
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:32:18 +00:00
wg.Add(1)
go func(d fs.DirEntry, wg *sync.WaitGroup) {
defer wg.Done()
fInfo, err := d.Info()
if err != nil {
log.Printf("failed to get file info '%s': %v", d.Name(), err)
return
}
fileHash, err := hashFile(fmt.Sprintf("%s/%s", romDirectory, d.Name()))
if err != nil {
log.Printf("ingore zip file '%s', failed to get sha256 hash: %v", d.Name(), err)
return
}
lineageOSROM := LineageOSROM{
Datetime: int(fInfo.ModTime().Unix()),
Filename: d.Name(),
ID: fileHash,
Romtype: "nightly",
Size: int(fInfo.Size()),
URL: fmt.Sprintf("https://lineageos-ota.deadbeef.codes/public/%s", d.Name()),
Version: splitName[1],
}
romCache.Lock()
romCache.ROMs = append(romCache.ROMs, lineageOSROM)
romCache.Cached[d.Name()] = true
romCache.Unlock()
}(d, &wg)
2023-06-04 05:07:55 +00:00
return nil
})
if err != nil {
2023-06-04 18:32:18 +00:00
log.Printf("failed to walk romDirectory '%s': %v", romDirectory, err)
return
2023-06-04 05:07:55 +00:00
}
}
// 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) {
2023-06-04 18:32:18 +00:00
romCache.Lock()
lineageOSROMs := romCache.ROMs
romCache.Unlock()
2023-06-04 05:07:55 +00:00
2023-06-04 18:32:18 +00:00
httpResponseJSON := &HTTPResponseJSON{Response: lineageOSROMs}
2023-06-04 05:07:55 +00:00
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)
2023-06-04 18:32:18 +00:00
go updateROMCache("public")
2023-06-04 05:07:55 +00:00
}
2023-06-04 15:32:23 +00:00
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)
}
2023-06-04 18:32:18 +00:00
return fmt.Sprintf("%x", h.Sum(nil)), nil
2023-06-04 15:32:23 +00:00
}