All checks were successful
		
		
	
	continuous-integration/drone/push Build is passing
				
			
		
			
				
	
	
		
			171 lines
		
	
	
		
			3.9 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			171 lines
		
	
	
		
			3.9 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package main
 | |
| 
 | |
| import (
 | |
| 	"crypto/sha256"
 | |
| 	"encoding/json"
 | |
| 	"fmt"
 | |
| 	"io"
 | |
| 	"io/fs"
 | |
| 	"log"
 | |
| 	"net/http"
 | |
| 	"os"
 | |
| 	"path/filepath"
 | |
| 	"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) {
 | |
| 
 | |
| 	if _, err := os.Stat(romDirectory); os.IsNotExist(err) {
 | |
| 		log.Printf("romDirectory '%s' does not exist", romDirectory)
 | |
| 		return
 | |
| 	}
 | |
| 	wg := sync.WaitGroup{}
 | |
| 
 | |
| 	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
 | |
| 		}
 | |
| 
 | |
| 		// skip already cached files
 | |
| 		romCache.Lock()
 | |
| 		if _, ok := romCache.Cached[d.Name()]; ok {
 | |
| 			romCache.Unlock()
 | |
| 			return nil
 | |
| 		}
 | |
| 		romCache.Unlock()
 | |
| 
 | |
| 		// Get information about file and populate rom
 | |
| 		splitName := strings.Split(d.Name(), "-")
 | |
| 		if len(splitName) != 5 {
 | |
| 			log.Printf("ignoring zip file '%s', name is not formatted correctly", d.Name())
 | |
| 			return nil
 | |
| 		}
 | |
| 
 | |
| 		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)
 | |
| 
 | |
| 		return nil
 | |
| 	})
 | |
| 	if err != nil {
 | |
| 		log.Printf("failed to walk romDirectory '%s': %v", romDirectory, err)
 | |
| 		return
 | |
| 	}
 | |
| }
 | |
| 
 | |
| // 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
 | |
| }
 |