lineageos-ota-server/main.go

261 lines
5.8 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"
"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 19:28:36 +00:00
moveBuildArtifacts("out", "public")
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
log.Printf("updating ROM cache")
2023-06-04 18:56:58 +00:00
f, err := os.Open(romDirectory)
if err != nil {
log.Printf("failed to open ROM directory: %v", err)
return
}
2023-06-04 19:28:36 +00:00
defer f.Close()
2023-06-04 18:56:58 +00:00
files, err := f.ReadDir(0)
if err != nil {
log.Printf("failed to read files in directory: %v", err)
2023-06-04 18:32:18 +00:00
return
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:56:58 +00:00
for i, v := range files {
2023-06-04 18:32:18 +00:00
2023-06-04 18:56:58 +00:00
// skip directories
if v.Type().IsDir() {
continue
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:56:58 +00:00
// skip non .zip files
if !strings.HasSuffix(v.Name(), ".zip") {
continue
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:32:18 +00:00
// skip already cached files
romCache.Lock()
2023-06-04 18:56:58 +00:00
if _, ok := romCache.Cached[v.Name()]; ok {
2023-06-04 18:32:18 +00:00
romCache.Unlock()
2023-06-04 18:56:58 +00:00
continue
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
2023-06-04 18:56:58 +00:00
// Parse filename and skip files that can't be parsed
splitName := strings.Split(v.Name(), "-")
2023-06-04 05:07:55 +00:00
if len(splitName) != 5 {
2023-06-04 18:56:58 +00:00
continue
2023-06-04 05:07:55 +00:00
}
2023-06-04 18:56:58 +00:00
go func(v fs.DirEntry) {
fInfo, err := v.Info()
2023-06-04 18:32:18 +00:00
if err != nil {
2023-06-04 18:56:58 +00:00
log.Printf("failed to get file info '%s': %v", v.Name(), err)
2023-06-04 18:32:18 +00:00
return
}
2023-06-04 18:56:58 +00:00
fileHash, err := hashFile(fmt.Sprintf("%s/%s", romDirectory, v.Name()))
2023-06-04 18:32:18 +00:00
if err != nil {
2023-06-04 18:56:58 +00:00
log.Printf("ingore zip file '%s', failed to get sha256 hash: %v", v.Name(), err)
2023-06-04 18:32:18 +00:00
return
}
lineageOSROM := LineageOSROM{
Datetime: int(fInfo.ModTime().Unix()),
2023-06-04 18:56:58 +00:00
Filename: v.Name(),
2023-06-04 18:32:18 +00:00
ID: fileHash,
Romtype: "nightly",
Size: int(fInfo.Size()),
2023-06-04 18:56:58 +00:00
URL: fmt.Sprintf("https://lineageos-ota.deadbeef.codes/public/%s", v.Name()),
2023-06-04 18:32:18 +00:00
Version: splitName[1],
}
romCache.Lock()
2023-06-04 18:56:58 +00:00
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
}
2023-06-04 18:32:18 +00:00
romCache.ROMs = append(romCache.ROMs, lineageOSROM)
2023-06-04 18:56:58 +00:00
romCache.Cached[v.Name()] = true
2023-06-04 18:32:18 +00:00
romCache.Unlock()
2023-06-04 18:56:58 +00:00
}(files[i])
2023-06-04 05:07:55 +00:00
}
}
2023-06-04 19:28:36 +00:00
// returns true if new builds were moved
func moveBuildArtifacts(outDirectory, romDirectory string) bool {
f, err := os.Open(outDirectory)
2023-06-04 19:28:36 +00:00
if err != nil {
log.Printf("failed to open ROM directory: %v", err)
return false
}
defer f.Close()
files, err := f.ReadDir(0)
if err != nil {
log.Printf("failed to read files in directory: %v", err)
return false
}
var newROMs bool
for _, v := range files {
// skip directories
if v.Type().IsDir() {
continue
}
// skip non .zip files
if !strings.HasSuffix(v.Name(), ".zip") {
continue
}
// Parse filename and skip files that can't be parsed
splitName := strings.Split(v.Name(), "-")
if len(splitName) != 5 {
continue
}
newROMs = true
log.Printf("new build found - moving file %s", v.Name())
2023-06-04 19:42:44 +00:00
err := moveBuildFile(fmt.Sprintf("%s/%s", outDirectory, v.Name()), fmt.Sprintf("%s/%s", romDirectory, v.Name()))
2023-06-04 19:28:36 +00:00
if err != nil {
log.Printf("failed to move file '%s' from out to rom directory: %v", v.Name(), err)
continue
}
}
return newROMs
}
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
2023-06-04 19:28:36 +00:00
go func() {
newBuilds := moveBuildArtifacts("out", "public")
if newBuilds {
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
}
2023-06-04 19:42:44 +00:00
// A custom "move file" function because in docker container the mounted folders are different overlay filesystems
// Instead of os.Rename, we must copy and delete
func moveBuildFile(src, dst string) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
return fmt.Errorf("failed to copy file: %v", err)
}
err = os.Remove(src)
if err != nil {
return fmt.Errorf("failed to delete source file after copy: %v", err)
}
return nil
}