downloads.go

70 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
package controllers

import (
	"fmt"
	"net/http"
	"path/filepath"

	"congo.gg/pkg/application"
)

const downloadsDir = "/usr/local/share/congo/downloads"

func Downloads() (string, *DownloadsController) {
	return "downloads", &DownloadsController{}
}

type DownloadsController struct {
	application.BaseController
}

type Platform struct {
	OS       string
	Arch     string
	Label    string
	Filename string
}

var platforms = []Platform{
	{OS: "darwin", Arch: "arm64", Label: "macOS (Apple Silicon)", Filename: "congo-darwin-arm64.tar.gz"},
	{OS: "darwin", Arch: "amd64", Label: "macOS (Intel)", Filename: "congo-darwin-amd64.tar.gz"},
	{OS: "linux", Arch: "amd64", Label: "Linux (x86_64)", Filename: "congo-linux-amd64.tar.gz"},
	{OS: "linux", Arch: "arm64", Label: "Linux (ARM64)", Filename: "congo-linux-arm64.tar.gz"},
	{OS: "windows", Arch: "amd64", Label: "Windows (x86_64)", Filename: "congo-windows-amd64.zip"},
}

var validFiles = map[string]bool{
	"congo-darwin-arm64.tar.gz": true,
	"congo-darwin-amd64.tar.gz": true,
	"congo-linux-amd64.tar.gz":  true,
	"congo-linux-arm64.tar.gz":  true,
	"congo-windows-amd64.zip":   true,
}

func (c *DownloadsController) Setup(app *application.App) {
	c.BaseController.Setup(app)
	http.Handle("GET /download", app.Serve("download.html", nil))
	http.Handle("GET /download/{filename}", app.Method(c, "ServeFile", nil))
}

func (c DownloadsController) Handle(r *http.Request) application.Controller {
	c.Request = r
	return &c
}

func (c *DownloadsController) Platforms() []Platform {
	return platforms
}

func (c *DownloadsController) ServeFile(w http.ResponseWriter, r *http.Request) {
	filename := r.PathValue("filename")

	if !validFiles[filename] {
		http.NotFound(w, r)
		return
	}

	path := filepath.Join(downloadsDir, filename)
	w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
	http.ServeFile(w, r, path)
}