-
Notifications
You must be signed in to change notification settings - Fork 0
/
print.go
108 lines (95 loc) · 2.32 KB
/
print.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type Print struct {
ID string
Header string
Content string
Status string
CreatedAt time.Time
ModifiedAt time.Time
}
func getNextPrint(ctx context.Context, cfg Config) (pr Print, err error) {
b := bytes.Buffer{}
req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/printd/contests/%s/next_print", cfg.Toph.BaseURL, cfg.Toph.ContestID), nil)
if err != nil {
return Print{}, err
}
req.Header.Add("Authorization", "Printd "+cfg.Toph.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return Print{}, retryableError{tophError{"Could not reach Toph", err}}
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusNotFound:
return Print{}, noNextPrintError{
contestLocked: resp.Header.Get("Toph-Contest-Locked") == "1",
}
case http.StatusForbidden:
return Print{}, tophError{"Could not retrieve print", errInvalidToken}
}
b.Reset()
_, err = io.Copy(&b, resp.Body)
if err != nil {
return Print{}, retryableError{tophError{"Could not retrieve print", err}}
}
err = json.NewDecoder(&b).Decode(&pr)
if err != nil {
return Print{}, retryableError{tophError{"Could not parse response", err}}
}
return pr, nil
}
func runPrintJob(ctx context.Context, cfg Config, pr Print) (PDF, error) {
name := pr.ID + ".pdf"
pdf, err := PDFBuilder{
cfg: cfg,
}.Build(name, pr)
if err != nil {
return PDF{}, err
}
if !cfg.Debug.DontPrint {
err = printPDF(cfg, name)
if err != nil {
return PDF{}, err
}
}
if !cfg.Printd.KeepPDF {
err = os.Remove(name)
if err != nil {
return PDF{}, err
}
}
return pdf, nil
}
type Done struct {
PageCount int `json:"pageCount"`
}
func markPrintDone(ctx context.Context, cfg Config, pr Print, pdf PDF) error {
body := Done{
PageCount: pdf.PageCount,
}
b, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%s/api/printd/prints/%s/mark_done?contest=%s", cfg.Toph.BaseURL, pr.ID, cfg.Toph.ContestID), bytes.NewReader(b))
req.Header.Add("Authorization", "Printd "+cfg.Toph.Token)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return retryableError{tophError{"Could not reach Toph", err}}
}
defer resp.Body.Close()
return nil
}