aboutsummaryrefslogtreecommitdiffstats
path: root/lulu.go
blob: af425f019d74ff0dd08cfb820f0cbb6bd748360a (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
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
// Package lulu is a client library for the Lulu book printing API.
package lulu

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"

	"golang.org/x/oauth2/clientcredentials"
)

const (
	SandboxUrl    = "https://api.sandbox.lulu.com/"
	ProductionUrl = "https://api.lulu.com/"

	tokenPath            = "/auth/realms/glasstree/protocol/openid-connect/token"
	validateInteriorPath = "/validate-interior"
	coverDimensionsPath  = "/cover-dimensions"
	validateCoverPath    = "/validate-cover"
)

// ApiUrl is the location of the API server. It is set to the sandbox
// environment by default; change it to the production environment when
// you are ready to deploy.
var ApiUrl = SandboxUrl

// Unit is a unit of length measurement.
type Unit string

const (
	Points      Unit = "pt"
	Millimeters Unit = "mm"
	Inches      Unit = "inch"
)

type ValidationStatus string

const (
	StatusNull        ValidationStatus = "NULL"        // file validation is not started yet
	StatusValidating  ValidationStatus = "VALIDATING"  // file validation is still running
	StatusValidated   ValidationStatus = "VALIDATED"   // file validation finished without any errors
	StatusNormalizing ValidationStatus = "NORMALIZING" // file normalization (next step of validation, available only if pod_package_id is was passed in the payload) is still running
	StatusNormalized  ValidationStatus = "NORMALIZED"  // file normalization finished without any errors
	StatusError       ValidationStatus = "ERROR"       // file is invalid, list of errors is included in the response
)

func (s ValidationStatus) IsFinal() bool {
	switch s {
	case StatusValidated, StatusNormalized, StatusError:
		return true
	}
	return false
}

// validateInteriorReq is the json body of a /validate-interior/ request.
type validateInteriorReq struct {
	SrcUrl string `json:"source_url"`
	PkgId  PkgId  `json:"pod_package_id"`
}

// validateInteriorReq is the json body of a /validate-interior/ request without the optional pod_package_id.
type validateInteriorBasicReq struct {
	SrcUrl string `json:"source_url"`
}

// InteriorValidationRecord contains the validation status of an interior file.
type InteriorValidationRecord struct {
	Id          uint
	SrcUrl      string `json:"source_url"`
	NPages      uint   `json:"page_count"`
	Errors      string
	Status      ValidationStatus
	ValidPkgIds []PkgId `json:"valid_pod_package_ids"`
}

// coverDimensionsReq is the json body of a /cover-dimensions/ request.
type coverDimensionsReq struct {
	PkgId  PkgId `json:"pod_package_id"`
	NPages uint  `json:"interior_page_count"`
	Unit   Unit  `json:"unit"`
}

type CoverDimensions struct {
	Width, Height float64
	Unit          Unit
}

func (cd *CoverDimensions) UnmarshalJSON(data []byte) error {
	s := string(data)
	var alias struct {
		Width, Height string
		Unit          Unit
	}
	if err := json.Unmarshal(data, &alias); err != nil {
		return fmt.Errorf("malformed %T: %q: %w", cd, s, err)
	}

	w, err := strconv.ParseFloat(alias.Width, 64)
	if err != nil {
		return fmt.Errorf("malformed %T.Width: %q: %w", cd, s, err)
	}
	h, err := strconv.ParseFloat(alias.Height, 64)
	if err != nil {
		return fmt.Errorf("malformed %T.Height: %q: %w", cd, s, err)
	}

	cd.Width = w
	cd.Height = h
	cd.Unit = alias.Unit
	return nil
}

type Client struct {
	c *http.Client
}

// NewClient returns a client that will use the given client-key and
// client-secret to connect to the API server.
func NewClient(ctx context.Context, key, secret string) (*Client, error) {
	tokenUrl, err := url.JoinPath(ApiUrl, tokenPath)
	if err != nil {
		return nil, err
	}

	cfg := &clientcredentials.Config{
		ClientID:     key,
		ClientSecret: secret,
		TokenURL:     tokenUrl,
	}
	return &Client{cfg.Client(ctx)}, nil
}

// ValidateInterior starts a server-side validation job for the interior
// file located at srcUrl using manufacturing settings given by mfg. It
// returns the ID of the job. Use GetInteriorValidation() to poll the
// status of the job.
//
// https://api.lulu.com/docs/#tag/Files-validation/operation/Validate-Interior_create
func (c *Client) ValidateInterior(srcUrl string, mfg PkgId) (uint, error) {
	return c.validateInterior(validateInteriorReq{srcUrl, mfg})
}

// ValidateInteriorBasic is like ValidateInterior but without the
// optional pod_package_id.
//
// https://api.lulu.com/docs/#tag/Files-validation/operation/Validate-Interior_create
func (c *Client) ValidateInteriorBasic(srcUrl string) (uint, error) {
	return c.validateInterior(validateInteriorBasicReq{srcUrl})
}

func (c *Client) validateInterior(payload any) (uint, error) {
	body, err := json.Marshal(payload)
	if err != nil {
		return 0, fmt.Errorf("lulu: error encoding request body %v for %s: %w", payload, validateInteriorPath, err)
	}

	url, err := url.JoinPath(ApiUrl, validateInteriorPath)
	if err != nil {
		return 0, fmt.Errorf("lulu: %w", err)
	}
	resp, err := c.c.Post(url, "application/json", bytes.NewBuffer(body))
	if err != nil {
		return 0, fmt.Errorf("lulu: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated {
		return 0, errResp{resp}
	}

	var rec InteriorValidationRecord
	err = decodeResponse(resp, &rec)
	return rec.Id, err
}

// GetInteriorValidation retrieves information about an interior file
// validation job that was started by ValidateInterior().
//
// https://api.lulu.com/docs/#tag/Files-validation/operation/Validate-Interior_read
func (c *Client) GetInteriorValidation(id uint) (InteriorValidationRecord, error) {
	url, err := url.JoinPath(ApiUrl, validateInteriorPath, fmt.Sprint(id))
	if err != nil {
		return InteriorValidationRecord{}, fmt.Errorf("lulu: %w", err)
	}
	resp, err := c.c.Get(url)
	if err != nil {
		return InteriorValidationRecord{}, fmt.Errorf("lulu: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return InteriorValidationRecord{}, errResp{resp}
	}

	var rec InteriorValidationRecord
	err = decodeResponse(resp, &rec)
	return rec, err
}

// CoverDimensions calculates the required dimensions of the cover for a
// book with the given manufacturing settings and number of pages. The
// returned dimensions are given in the specified units of measurement.
//
// https://api.lulu.com/docs/#tag/Files-validation/operation/Cover-Dimensions_create
func (c *Client) CoverDimensions(mfg PkgId, npages uint, unit Unit) (CoverDimensions, error) {
	payload := coverDimensionsReq{mfg, npages, unit}
	body, err := json.Marshal(payload)
	if err != nil {
		return CoverDimensions{}, fmt.Errorf("lulu: error encoding request body %v for %s: %w", payload, coverDimensionsPath, err)
	}

	url, err := url.JoinPath(ApiUrl, coverDimensionsPath)
	if err != nil {
		return CoverDimensions{}, fmt.Errorf("lulu: %w", err)
	}
	resp, err := c.c.Post(url, "application/json", bytes.NewBuffer(body))
	if err != nil {
		return CoverDimensions{}, fmt.Errorf("lulu: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusCreated {
		return CoverDimensions{}, errResp{resp}
	}

	var dims CoverDimensions
	err = decodeResponse(resp, &dims)
	return dims, err
}

func decodeResponse(resp *http.Response, v any) error {
	buf := new(bytes.Buffer)
	if _, err := io.Copy(buf, resp.Body); err != nil {
		return errReadResp{resp, err}
	}
	dec := json.NewDecoder(buf)
	if err := dec.Decode(v); err != nil {
		return errDecResp{resp, buf.Bytes(), err}
	}
	return nil
}