aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/handlers.go
blob: 661c411562919c4511fddebcb4867970b5fd9c56 (plain) (blame)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"riedstra.dev/mitch/steam-export/steam"
)

// HandleIndex takes care of rendering our embedded template
// and locks the steam library for each request.
func (a *App) HandleIndex(w http.ResponseWriter, r *http.Request) {
	// During rendering of the template I believe it's
	// mutating during the sort of keys, so Lib no longer
	// is an RWMutex and we're just locking this as if
	// we're writing to it
	a.Library.Lock()
	defer a.Library.Unlock()
	a.Status.Lock()
	defer a.Status.Unlock()

	err := a.Templates.ExecuteTemplate(w, "index",
		struct {
			Lib     *steam.Library
			Info    *statusInfo
			Local   bool
			HostIP  string
			Port    string
			Version string
		}{
			&a.Library.Library,
			a.Status,
			isLocal(r.RemoteAddr),
			GetHostIP(),
			getPort(),
			Version,
		})
	if err != nil {
		Logger.Printf("While Rendering template: %s", err)
	}
	Logger.Printf("Client %s Index page", r.RemoteAddr)
}

// HandleInstall takes the HTTP requests for installing a game from a URL
// or local file path
func (a *App) HandleInstall(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		Logger.Printf("Installer: While parsing form: %s", err)
		http.Error(w, fmt.Sprintf("Invalid form: %s", err), 400)
		return
	}

	uri := r.Form.Get("uri")

	if strings.HasPrefix(uri, "http") {
		_, err := url.Parse(uri)
		if err != nil {
			Logger.Printf("Installer: While parsing url: %s", err)
			http.Error(w, fmt.Sprintf("Invalid url: %s", err), 400)
			return
		}
	} else {
		fi, err := os.Stat(uri)
		if err != nil || !fi.Mode().IsRegular() {
			Logger.Printf("Installer: While parsing url/path: %s", err)
			http.Error(w, fmt.Sprintf("Invalid uri/path: %s", err), 400)
			return
		}
	}

	Logger.Printf("Installer: Sending request for: %s to channel", uri)
	a.download <- uri

	http.Redirect(w, r, "/", 302)
}

// HandleDownload takes care of exporting our games out to an HTTP request
func (a *App) HandleDownload(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	game := vars["game"]

	a.Library.Lock()
	g, ok := a.Library.Games[game]
	a.Library.Unlock()
	if !ok {
		Logger.Printf("Missing: %s", game)
		http.Error(w, "Game is missing", 404)
		return
	}

	w.Header().Add("Content-type", "application/tar")
	w.Header().Add("Estimated-size", fmt.Sprintf("%d", g.Size))

	Logger.Printf("Client %s is downloading: %s", r.RemoteAddr, game)

	// Invert the writer so we can break up the copy and get progress
	// information in here
	rdr, pwrtr := io.Pipe()
	go func() {
		err := g.Package(pwrtr)
		if err != nil {
			Logger.Println("Error in package writing: ", err)
		}
	}()

	var total int64
	start := time.Now()
	for {
		n, err := io.CopyN(w, rdr, 256*1024*1024)
		if err == io.EOF {
			break
		}
		if err != nil {
			Logger.Printf("Client %s Error Sending game: %s", r.RemoteAddr, err)
			// Headers already sent, don't bother sending an error
			return
		}
		total += n
		mb := float64(total / 1024 / 1024)
		rate := mb / time.Since(start).Seconds()

		Logger.Printf("Client %s is downloading %s: %0.1f%% done %.2f mb/s",
			r.RemoteAddr, game, float64(total)/float64(g.Size)*100, rate)
	}

	Logger.Printf("Client %s finished downloading: %s", r.RemoteAddr, game)
}

// HandleDelete removes the game in question, though it doesn't
// spawn any background processes it usually completes fast enough.
// TODO: Fix if the request taking too long becomes an issue
func (a *App) HandleDelete(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		Logger.Printf("Installer: While parsing form: %s", err)
		http.Error(w, fmt.Sprintf("Invalid form: %s", err), 400)
		return
	}

	game := r.PostForm.Get("name")

	if game == "" {
		Logger.Println("Deleter: No game specified")
		http.Error(w, "Game param required", 400)
		return
	}

	a.Library.Lock()
	g, ok := a.Library.Games[game]
	a.Library.Unlock()
	if !ok {
		Logger.Printf("Missing: %s", game)
		http.Error(w, "Game is missing", 404)
		return
	}

	err = g.Delete()
	if err != nil {
		Logger.Printf("Error removing game: %s", err)
		http.Error(w, fmt.Sprintf("Error removing game: %s", err), 500)
		return
	}
	Logger.Printf("Removed game: %s", game)

	a.LibraryReload()
	http.Redirect(w, r, "/", 302)
}

// HandleStats dumps out some internal statistics of installation which
// is then parsed by some JS for a progress bar and such
func (a *App) HandleStats(w http.ResponseWriter, r *http.Request) {
	a.Status.RLock()
	defer a.Status.RUnlock()

	w.Header().Add("Content-type", "application/json")

	enc := json.NewEncoder(w)

	err := enc.Encode(a.Status)
	if err != nil {
		Logger.Println("While encoding Status: ", err)
	}
	return
}

// HandleSetLib sets a new library path
func (a *App) HandleSetLib(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		Logger.Printf("Setlib: While parsing form: %s", err)
		http.Error(w, fmt.Sprintf("Invalid form: %s", err), 400)
		return
	}

	a.LibrarySet(r.Form.Get("path"))

	http.Redirect(w, r, "/", 302)
}

// HandleQuit just calls os.Exit after finishing the request
func HandleQuit(w http.ResponseWriter, r *http.Request) {
	Logger.Println("Quit was called, exiting")
	w.Header().Add("Content-type", "text/plain")
	w.Write([]byte("Shutting down... feel free to close this"))
	go func() {
		time.Sleep(time.Second * 2)
		os.Exit(0)
	}()
	return
}