~reesmichael1/chantpointer

ref: fix_ci chantpointer/handlers.go -rw-r--r-- 3.1 KiB View raw
a8ef912f — Michael Rees Only build on master 1 year, 6 months ago
                                                                                
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
package main

import (
	"bytes"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"path"
	"path/filepath"
)

// ErrorHandler handles any errors that occur in the other endpoints
// and nicely displays them to the user
type ErrorHandler func(http.ResponseWriter, *http.Request) error

var templates = template.Must(template.ParseFiles("index.html", "error.html"))

// Page holds the link to the generated PDF, if it exists
type Page struct {
	URL string
}

// ErrorPage holds an error message to show to the user
type ErrorPage struct {
	Message string
}

func (fn ErrorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := fn(w, r); err != nil {
		log.Printf("error: %v\n", err)
		templates.ExecuteTemplate(w, "error.html", ErrorPage{err.Error()})
	}
}

// ChantHandler serves the finished PDFs of chants
func ChantHandler(w http.ResponseWriter, r *http.Request) {
	chantID := path.Base(r.URL.Path)
	url := fmt.Sprintf("/tmp/chant%s/psalm.pdf", chantID)
	http.ServeFile(w, r, url)
}

// GenerateHandler handles incoming requests to the generate endpoint
func GenerateHandler(w http.ResponseWriter, r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}

	var buf bytes.Buffer
	file, _, err := r.FormFile("score")
	if err != nil {
		return err
	}

	dir, err := ioutil.TempDir("", "chant")
	if err != nil {
		return err
	}

	stylePath := filepath.Join(dir, "psalm.sty")
	style, err := ioutil.ReadFile("psalm.sty")
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(stylePath, style, 0644)
	if err != nil {
		return err
	}

	io.Copy(&buf, file)
	chantPath := filepath.Join(dir, "chant.png")
	err = ioutil.WriteFile(chantPath, buf.Bytes(), 0644)
	if err != nil {
		return err
	}

	buf.Reset()

	c := Chant{
		Verses:    ParseInput(r.FormValue("chant")),
		Title:     r.FormValue("title"),
		Subtitle:  r.FormValue("subtitle"),
		ScorePath: chantPath,
		PointSize: 12,
	}

	texPath := filepath.Join(dir, "psalm.tex")
	texFile, err := os.OpenFile(texPath, os.O_CREATE|os.O_RDWR, 0644)
	defer texFile.Close()
	err = WriteTexForChant(texFile, &c)

	cmd := exec.Command("pdflatex", texPath)
	cmd.Stdout = &buf
	cmd.Stderr = &buf
	startDir, err := os.Getwd()
	if err != nil {
		return err
	}

	os.Chdir(dir)
	err = cmd.Run()
	if err != nil {
		log.Printf("pdflatex error: %v", string(buf.Bytes()))
		return fmt.Errorf("pdflatex error: %v", err)
	}

	os.Chdir(startDir)

	relativeURL := "/"
	u, err := url.Parse(relativeURL)
	if err != nil {
		return err
	}

	queryString := u.Query()
	queryString.Set("id", dir[len("/tmp/chant"):])
	u.RawQuery = queryString.Encode()

	baseURL := "/"
	base, err := url.Parse(baseURL)
	if err != nil {
		log.Fatal(err)
	}

	http.Redirect(w, r, fmt.Sprint(base.ResolveReference(u)), http.StatusFound)
	return nil
}

// IndexHandler handles incoming requests to the generate endpoint
func IndexHandler(w http.ResponseWriter, r *http.Request) error {
	chant := r.URL.Query().Get("id")
	if chant != "" {
		chant = fmt.Sprintf("/chant/%s", chant)
		return templates.ExecuteTemplate(w, "index.html", Page{chant})
	}
	return templates.ExecuteTemplate(w, "index.html", Page{})
}