-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
657 lines (531 loc) · 13.5 KB
/
main.go
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"github.com/julienschmidt/httprouter"
)
var (
songs_root = "./songs"
books_root = "./books"
)
func getSongFilename(file string) string {
return songs_root + "/" + file + ".song"
}
func main() {
//Follow symlinks if applicable
link, _ := os.Readlink(songs_root)
if link != "" {
songs_root = link
}
link, _ = os.Readlink(books_root)
if link != "" {
books_root = link
}
//basic sanity check
_, err := os.Stat(songs_root)
if os.IsNotExist(err) {
fmt.Printf("Error: Songs path (%s) does not exist.\n", songs_root)
return
}
_, err = os.Stat(books_root)
if os.IsNotExist(err) {
fmt.Printf("Error: Books path (%s) does not exist.\n", books_root)
return
}
//Load songs and books
err = loadSongs(songs_root)
if err != nil {
fmt.Println("Error loading songs")
fmt.Println(err)
return
}
err = loadBooks(books_root)
if err != nil {
fmt.Println("Error loading books")
fmt.Println(err)
return
}
fmt.Printf("%d Songs loaded.\n", len(loadedSongs))
//Sort lists by title
sort.Sort(ByTitle(loadedSongs))
sort.Sort(ByTitle(loadedBooks))
r := httprouter.New()
r.GET("/", indexHandler)
r.GET("/index.php", indexHandler)
r.GET("/index.html", indexHandler)
r.GET("/song/:song", songHandler)
r.GET("/song/:song/edit", editSongHandler)
r.GET("/pdf/song/:song", songPdfHandler)
r.GET("/pdf/book/:book/version/:version", bookPdfHandler)
r.GET("/book/:book/index", bookIndexHandler)
r.GET("/book/:book/edit", editBookHandler)
r.GET("/book/:book/song/:number", bookHandler)
r.ServeFiles("/css/*filepath", http.Dir("css"))
r.ServeFiles("/js/*filepath", http.Dir("js"))
r.POST("/song/:song/edit", editSongPostHandler)
r.POST("/book/:book/edit", editBookPostHandler)
r.DELETE("/book/:book/edit", editBookDeleteHandler)
log.Fatal(http.ListenAndServe(":8090", r))
}
type DisplayList struct {
Link string
Title string
}
// ByTitle implements sort.Interface for []DisplayList based on
// the Title field.
type ByTitle []DisplayList
func (a ByTitle) Len() int { return len(a) }
func (a ByTitle) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTitle) Less(i, j int) bool {
num_regex := regexp.MustCompile("^[0-9]")
i_pos := num_regex.FindAllStringIndex(a[i].Title, 1)
j_pos := num_regex.FindAllStringIndex(a[j].Title, 1)
i_num := (len(i_pos) > 0)
j_num := (len(j_pos) > 0)
//neither title begins with a number,
//or both begin with a number, normal sort
if i_num == j_num {
return a[i].Title < a[j].Title
}
//I is a number, put it at the end
if i_num {
return false
}
return true
}
func (song DisplayList) MatchTitle(title string) bool {
return song.Title == title
}
func (song Song) MatchNumber(num int) bool {
return song.SongNumber == num
}
type IndexPage struct {
Title string
Recent []DisplayList
Songs []DisplayList
Books []DisplayList
ShowIndigo bool
SelectedSong string
SelectedBook string
Error string
}
func (i IndexPage) HasSong() bool {
return len(i.SelectedSong) > 0
}
func (i IndexPage) HasBook() bool {
return len(i.SelectedBook) > 0
}
type SongPage struct {
Song Song
Songbook Songbook
NextSong int
PrevSong int
Selected int
IndexPage
}
type BookPage struct {
Songbook Songbook
Selected int
IndexPage
}
type EditSongPage struct {
Title string
Content string
IndexPage
}
var loadedSongs = make([]DisplayList, 0)
var loadedBooks = make([]DisplayList, 0)
var recent = make([]DisplayList, 0)
var last_err = ""
// indexHandler is an HTTP handler that serves the index page.
func indexHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
t, err := template.ParseFiles("templates/index.tmpl", "templates/_song_select.tmpl", "templates/_book_select.tmpl")
if err != nil {
panic(err)
}
data := getBasicIndexData()
data.ShowIndigo = true
if err := t.ExecuteTemplate(w, "index.tmpl", data); err != nil {
log.Println(err)
}
}
func loadSongFile(title string, transpose int) (*Song, error) {
filename := getSongFilename(title)
song, err := ParseSongFile(filename, transpose)
if err != nil {
return nil, err
}
return song, nil
}
func getBasicIndexData() IndexPage {
index_data := IndexPage{
Title: "Indigo Song Book",
Recent: recent,
Songs: loadedSongs,
Books: loadedBooks,
ShowIndigo: false,
SelectedSong: "",
SelectedBook: "",
Error: last_err}
last_err = ""
return index_data
}
func editBookDeleteHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
//find songbook file
name := strings.TrimSpace(p.ByName("book"))
err := os.Remove(books_root + "/" + name + ".songlist")
defer loadBooks(books_root)
if err != nil {
fmt.Println(err)
return
}
}
func editBookPostHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
raw_settings := r.PostFormValue("settings")
var settings map[string]string
_ = json.Unmarshal([]byte(raw_settings), &settings)
raw_songs := r.PostFormValue("songs")
var songs []string
_ = json.Unmarshal([]byte(raw_songs), &songs)
//open songbook file
name := strings.TrimSpace(settings["name"])
file, err := os.Create(books_root + "/" + name + ".songlist")
defer file.Close()
defer loadBooks(books_root)
if err != nil {
fmt.Println(err)
return
}
//write out the settings
for i, k := range settings {
switch i {
case "name":
continue
case "fixed-order":
file.WriteString("{fixed_order}\n")
break
case "index-pos":
file.WriteString("{index_position: ")
file.WriteString(k)
file.WriteString("}\n")
break
case "use-chorus":
file.WriteString("{index_use_chorus}\n")
break
case "use-sections":
file.WriteString("{index_use_sections}\n")
break
default:
fmt.Println("Unknown book setting: ", i, " -> ", k)
break
}
}
for _, s := range songs {
_, err = file.WriteString(strings.TrimSpace(s))
if err == nil {
_, err = file.WriteString("\n")
}
if err != nil {
fmt.Println(err)
return
}
}
}
func editBookHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
temp, err := template.ParseFiles(
"templates/index.tmpl",
"templates/book_edit.tmpl")
if err != nil {
panic(err)
}
sbook, err := ParseSongbookFile(books_root+"/"+p.ByName("book")+".songlist", songs_root)
var pBook Songbook
if err == nil {
pBook = *sbook
}
book_data := &BookPage{
Songbook: pBook,
IndexPage: getBasicIndexData(),
}
if err := temp.ExecuteTemplate(w, "book_edit.tmpl", book_data); err != nil {
log.Println(err)
}
}
func bookIndexHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
sbook, err := ParseSongbookFile(books_root+"/"+p.ByName("book")+".songlist", songs_root)
if err != nil {
fmt.Println(err)
}
index := getBasicIndexData()
index.SelectedBook = sbook.Title
book_data := &BookPage{
Songbook: *sbook,
IndexPage: index}
temp, err := template.ParseFiles(
"templates/index.tmpl",
"templates/_book_navigation.tmpl",
"templates/book_index.tmpl")
if err != nil {
panic(err)
}
if err := temp.ExecuteTemplate(w, "book_index.tmpl", book_data); err != nil {
log.Println(err)
}
}
func bookHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
num := p.ByName("number")
n, _ := strconv.Atoi(num)
var transpose = r.FormValue("transpose")
if len(transpose) == 0 {
transpose = "0"
}
t, err := strconv.Atoi(transpose)
sbook, err := ParseSongbookFile(books_root+"/"+p.ByName("book")+".songlist", songs_root)
if err != nil {
fmt.Println(err)
http.NotFound(w, r)
}
keys := GetSongOrder(sbook)
prev := n
next := n
for _, i := range keys {
if i < n {
prev = i
}
if i > n {
next = i
break
}
}
if next == n {
next = 0
}
if prev == n {
prev = 0
}
song, ok := sbook.Songs[n]
//Number does not exist in songbook
if !ok {
index := httprouter.CleanPath(r.URL.String() + "/../../index")
last_err = "Song '" + strconv.Itoa(n) + "' not found in songbook."
http.Redirect(w, r, index, 302)
return
}
index := getBasicIndexData()
index.SelectedSong = song.Title
index.SelectedBook = sbook.Title
song.Transpose(t)
updateRecent(song.Link(), song.Title)
page_data := &SongPage{
Song: song,
Songbook: *sbook,
PrevSong: prev,
NextSong: next,
Selected: song.SongNumber,
IndexPage: index}
temp, err := template.ParseFiles(
"templates/index.tmpl",
"templates/_song_select.tmpl",
"templates/_book_select.tmpl",
"templates/_display_song.tmpl",
"templates/_book_navigation.tmpl",
"templates/book_song.tmpl")
if err != nil {
panic(err)
}
if err := temp.ExecuteTemplate(w, "book_song.tmpl", page_data); err != nil {
log.Println(err)
}
}
func updateRecent(link string, title string) {
//if the song is already in the list, move it to the top
for i, dl := range recent {
if dl.Title == title {
//remove element
recent = append(recent[:i], recent[i+1:]...)
break
}
}
recent = append([]DisplayList{DisplayList{Link: link, Title: title}}, recent...)
if len(recent) > 5 {
recent = recent[0:5]
}
}
func editSongPostHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
raw_content := r.PostFormValue("content")
var content string
_ = json.Unmarshal([]byte(raw_content), &content)
filename := getSongFilename(p.ByName("song"))
err := ioutil.WriteFile(filename, []byte(content), 0644)
if err != nil {
log.Println(err)
}
}
func editSongHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
temp, err := template.ParseFiles(
"templates/index.tmpl",
"templates/song_edit.tmpl")
if err != nil {
panic(err)
}
filename := getSongFilename(p.ByName("song"))
b, err := ioutil.ReadFile(filename)
if err != nil {
log.Println(err)
return
}
page_data := &EditSongPage{
Title: p.ByName("song"),
Content: string(b),
IndexPage: getBasicIndexData(),
}
if err := temp.ExecuteTemplate(w, "song_edit.tmpl", page_data); err != nil {
log.Println(err)
}
}
func songHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var transpose = r.FormValue("transpose")
if len(transpose) == 0 {
transpose = "0"
}
t, err := strconv.Atoi(transpose)
data, err := loadSongFile(p.ByName("song"), t)
if err != nil {
log.Println(err)
home := httprouter.CleanPath(r.URL.String() + "/../..")
last_err = "Song '" + p.ByName("song") + "' not found."
http.Redirect(w, r, home, 302)
return
}
updateRecent(p.ByName("song"), data.Title)
index := getBasicIndexData()
index.SelectedSong = data.Title
page_data := &SongPage{
Song: *data,
IndexPage: index}
temp, err := template.ParseFiles(
"templates/index.tmpl",
"templates/_song_select.tmpl",
"templates/_display_song.tmpl",
"templates/song.tmpl")
if err != nil {
panic(err)
}
if err := temp.ExecuteTemplate(w, "song.tmpl", page_data); err != nil {
log.Println(err)
}
}
func songPdfHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
var transpose = r.FormValue("transpose")
if len(transpose) == 0 {
transpose = "0"
}
t, err := strconv.Atoi(transpose)
song, err := loadSongFile(p.ByName("song"), t)
if err != nil {
log.Println(err)
http.NotFound(w, r)
return
}
pdf, err := WriteSongPDF(song)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// stream straight to client(browser)
w.Header().Set("Content-type", "application/pdf")
if _, err := pdf.WriteTo(w); err != nil {
fmt.Fprintf(w, "%s", err)
}
w.Write([]byte("PDF Generated"))
}
func bookPdfHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
sbook, err := ParseSongbookFile(books_root+"/"+p.ByName("book")+".songlist", songs_root)
if err != nil {
log.Println(err)
http.NotFound(w, r)
return
}
var pdf *bytes.Buffer
ver := p.ByName("version")
if ver == "electronic" {
pdf, err = WriteBookPDFElectronic(sbook)
} else {
pdf, err = WriteBookPDF(sbook)
}
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if pdf == nil {
return
}
// stream straight to client(browser)
w.Header().Set("Content-type", "application/pdf")
if _, err := pdf.WriteTo(w); err != nil {
fmt.Fprintf(w, "%s", err)
}
w.Write([]byte("PDF Generated"))
}
func loadSongs(path string) error {
song_files, err := ioutil.ReadDir(songs_root)
if err != nil {
return err
}
for _, f := range song_files {
if !f.IsDir() && strings.HasSuffix(strings.ToLower(f.Name()), ".song") {
song, err := ParseSongFile(songs_root+"/"+f.Name(), 0)
if err != nil {
return err
}
link := song.Filename[0 : len(song.Filename)-len(".song")]
loadedSongs = append(loadedSongs, DisplayList{Link: link, Title: song.Title})
}
}
return err
}
func loadBooks(path string) error {
book_files, err := ioutil.ReadDir(books_root)
if err != nil {
return err
}
loadedBooks = make([]DisplayList, 0)
for _, f := range book_files {
if !f.IsDir() && strings.HasSuffix(strings.ToLower(f.Name()), ".songlist") {
book, err := ParseSongbookFile(books_root+"/"+f.Name(), songs_root)
if err != nil {
return err
}
link := book.Filename[0:len(book.Filename)-len(".songlist")] + "/index"
loadedBooks = append(loadedBooks, DisplayList{Link: link, Title: book.Title})
}
}
fmt.Printf("%d Books loaded.\n", len(loadedBooks))
return err
}
// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}