aboutsummaryrefslogtreecommitdiff
path: root/server.go
blob: 6eb46b6b1eb4adff4e4df1a48dba9433331b0013 (plain)
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package main

// Ideez instance code.

import (
	_ "embed"
	"encoding/gob"
	"errors"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"runtime/debug"
	"strconv"
	"time"
)

const (
	SERVER_ID_BYTES = 8
)

// This is the Object that should be paired to the Ideas.
type Ideez struct {
	Id   string
	Name string
}

// Represents an idea
// LastUpdated is a formatted date string
// out of 5 rating of the idea
// formatted time string with DateLayout
type Idea struct {
	Id          int
	Title       string
	Text        string
	Author      string
	LastUpdated string
}

// Data passed to the ideas_html template
type IdeasPageData struct {
	Name        string
	Ideas       []Idea
	Error       string
	RoutePrefix string
}

var (
	//go:embed templates/ideas.html
	ideas_html string
	//go:embed templates/edit.html
	idea_edit_html string
	// layout for how the date should be output in html
	DateLayout string = "02/01/2006 on 15:04"
)

func GetVersion() string {
	buildinfo, ok := debug.ReadBuildInfo()
	if !ok {
		panic("Could not read buildinfo to know package version.")
	}
	return buildinfo.Main.Version
}

// This function intializes a server for use it
// 1. Imports the data file for its ID, or creates one if it does not exist
// 2. Creates a SIGINT handler to save the data
// 3. Creates the html templates
// 4. Registers the routes to mux passed
// Returns a new server so that the manager can add it to the list of servers
func NewIdeez(mux *http.ServeMux, name, id string) Ideez {
	var logger = log.New(os.Stdout, "NewIdeez: ", log.Ldate)
	logger.Printf("New server %s[%s]\n", name, id)

	// Ideas for this server
	var Ideas []Idea
	// version number used for debugging compatibility with the .data file
	version := GetVersion()
	// Prefix that should be prepended before each route
	routePrefix := "/server/" + id
	// File for persistent storage
	dataFilename := DataDir + "/" + id + ".data"
	// Counter that goes up each time a new idea is created
	idCounter := 0

	// If the .data file does not exist, create it in the cache directory
	{
		f, err := os.Open(dataFilename)
		if errors.Is(err, os.ErrNotExist) {
			// The file does not exist, so create one with only Version encoded
			logger.Println("Datafile does not exist.  Creating", dataFilename)
			f, err = os.Create(dataFilename)
			if err != nil {
				logger.Fatalln("Error while creating data file:", err)
			}

			enc := gob.NewEncoder(f)
			if err := enc.Encode(version); err != nil {
				logger.Fatalln("Error while encoding Version:", err)
			}
		} else if err != nil {
			logger.Fatalln("Error while opening data file:", err)
		} else {
			dec := gob.NewDecoder(f)

			// Check the version
			var v string
			if err := dec.Decode(&v); err != io.EOF && err != nil {
				logger.Fatalln("Error while decoding version:", err)
			}
			if v != version {
				logger.Fatalf("Version mismatch for datafile@%s != package@%s\n", v, version)
			}

			// Decode the data and import it into Ideas
			if err := dec.Decode(&name); err != nil && err != io.EOF {
				logger.Fatalln("Error while decoding name:", err)
			}
			if err := dec.Decode(&Ideas); err != nil && err != io.EOF {
				logger.Fatalln("Error while decoding ideas:", err)
			}
			logger.Printf("Imported @%s: %d ideas\n", v, len(Ideas))
			if err := f.Close(); err != nil {
				logger.Fatalln("Error while closing file:", err)
			}
		}

	}

	// Data was succesfully imported
	logger.SetPrefix("Ideez(" + name + ") ")

	// Handle SIGINT
	// Save all Ideas into the data file
	// NOTE (Luca): This system might seem dumb, but it only adds overhead at startup
	// and exit of the program which is fine.
	go func() {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt)
		<-c

		f, err := os.Create(dataFilename)
		if err != nil {
			logger.Fatalln(err)
		}
		defer f.Close()

		enc := gob.NewEncoder(f)
		if err := enc.Encode(version); err != nil {
			logger.Fatalln(err)
		}
		if err := enc.Encode(name); err != nil {
			logger.Fatalln(err)
		}
		if err := enc.Encode(Ideas); err != nil {
			logger.Fatalln("Error while saving ideas:", err)
		}

		logger.Println("data saved.")
		os.Exit(0)
	}()

	// Creating templates
	tmpl, err := template.New("ideas").Parse(ideas_html)
	if err != nil {
		logger.Fatalln(err)
	}
	_, err = tmpl.New("edit").Parse(idea_edit_html)
	if err != nil {
		logger.Fatalln(err)
	}

	// Register http handlers
	{
		mux.HandleFunc("GET "+routePrefix+"/{$}", func(w http.ResponseWriter, r *http.Request) {
			tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "", routePrefix})
		})

		mux.HandleFunc("POST "+routePrefix+"/idea/create/", func(w http.ResponseWriter, r *http.Request) {
			i := Idea{
				Title:       r.FormValue("title"),
				Author:      r.FormValue("author"),
				LastUpdated: time.Now().Format(DateLayout),
				Text:        r.FormValue("text"),
				Id:          idCounter,
			}
			if i.Title == "" || i.Author == "" || i.Text == "" {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "All fields are required", routePrefix})
				return
			}

			Ideas = append(Ideas, i)
			idCounter++

			logger.Printf("Added new idea: %#v\n", i)
			http.Redirect(w, r, routePrefix+"/", http.StatusMovedPermanently)
		})

		// A page to edit the idea, this page should lead to POST /idea/edit for confirming the edit. If
		// the user cancels they should be redirected to the start page.  This is done in the html.
		mux.HandleFunc("GET "+routePrefix+"/idea/edit/", func(w http.ResponseWriter, r *http.Request) {
			id := r.URL.Query().Get("id")
			if id == "" {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "You must provide an Idea ID.", routePrefix})
				return
			}
			idInt, err := strconv.Atoi(id)
			if err != nil {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, id + " is not a valid Idea ID.", routePrefix})
				return
			}

			for _, i := range Ideas {
				if i.Id == idInt {
					tmpl.ExecuteTemplate(w, "edit", struct {
						Idea        Idea
						RoutePrefix string
					}{i, routePrefix})
					return
				}
			}
			tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "No idea with id '" + id + "'.", routePrefix})
		})

		// Perform the edit action on the idea
		mux.HandleFunc("POST "+routePrefix+"/idea/edit/", func(w http.ResponseWriter, r *http.Request) {
			id := r.FormValue("id")
			if id == "" {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "You must provide an Idea ID.", routePrefix})
				return
			}

			idInt, err := strconv.Atoi(id)
			if err != nil {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, id + " is not a valid Idea ID.", routePrefix})
				return
			}

			var i *Idea
			for j := range Ideas {
				if Ideas[j].Id == idInt {
					i = &Ideas[j]
					break
				}
			}

			if i == nil {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "No idea with id '" + id + "'.", routePrefix})
				return
			}

			i.Title = r.FormValue("title")
			i.Text = r.FormValue("text")
			i.LastUpdated = time.Now().Format(DateLayout) + " (edit)"

			logger.Printf("Edited %#v\n", i)

			http.Redirect(w, r, routePrefix+"/", http.StatusMovedPermanently)
		})

		mux.HandleFunc("POST "+routePrefix+"/idea/delete/", func(w http.ResponseWriter, r *http.Request) {
			id := r.FormValue("id")
			if id == "" {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "You must provide an Idea ID.", routePrefix})
				return
			}

			idInt, err := strconv.Atoi(id)
			if err != nil {
				tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, id + " is not a valid Idea ID.", routePrefix})
				return
			}

			for i, v := range Ideas {
				if idInt == v.Id {
					Ideas = append(Ideas[:i], Ideas[i+1:]...)
					logger.Printf("Deleted: %#v\n", v)
					http.Redirect(w, r, routePrefix+"/", http.StatusMovedPermanently)
					return
				}
			}
			tmpl.ExecuteTemplate(w, "ideas", IdeasPageData{name, Ideas, "No idea with id '" + id + "'.", routePrefix})
		})
	}

	return Ideez{Name: name, Id: id}
}