-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
440 lines (364 loc) · 9.94 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
package main
import (
"bytes"
"errors"
"fmt"
"github.com/fabian-z/eporto/epservice"
"html/template"
"net/url"
"strings"
"github.com/gorilla/schema"
"io/ioutil"
"log"
"net/http"
"os/exec"
)
const (
endpoint = "https://internetmarke.deutschepost.de/OneClickForAppV3"
)
//TODO configuration object instead of global state
var (
Listener string
PrinterName string
PageFormat int
FormatSupportsAddress bool
PartnerId string
KeyPhase string
SignatureKey string
WalletUser string
WalletPassword string
)
type StampData struct {
StampAddress bool
SenderCompany string
SenderName string
SenderStreet string
SenderHouseNo string
SenderZIP string
SenderCity string
//SenderCountry hardcoded to "DEU"
ReceiverCompany string
ReceiverName string
ReceiverStreet string
ReceiverHouseNo string
ReceiverZIP string
ReceiverCity string
ReceiverCountry string
Product int
}
func main() {
config()
service, err := epservice.NewOneClickForAppPortTypeV3(endpoint, true, &epservice.AuthenticationData{
PartnerId: PartnerId,
KeyPhase: KeyPhase,
Key: SignatureKey,
})
if err != nil {
log.Fatal(err)
}
FormatSupportsAddress, err = checkPageFormat(service, PageFormat)
if err != nil {
log.Fatal(err)
}
h := new(Handler)
h.service = service
funcMap := map[string]interface{}{
"centToEuro": func(cent int) string {
return fmt.Sprintf("%.2f", Round(float64(cent)/100, .5, 2))
},
"newline": func(count int) template.HTMLAttr {
var s string
for x := 0; x <= count; x++ {
s = s + "\n"
}
return template.HTMLAttr(s)
},
}
t, err := template.New("index.html").Funcs(funcMap).ParseFiles("templates/index.html")
if err != nil {
log.Fatal(err)
}
h.template = t
ts, err := template.New("success.html").Funcs(funcMap).ParseFiles("templates/success.html")
if err != nil {
log.Fatal(err)
}
h.templateSuccess = ts
h.decoder = schema.NewDecoder()
log.Println("Starting to listen on", Listener)
log.Fatal(http.ListenAndServe(Listener, h))
return
}
func getStampPDFBytes(link string) ([]byte, error) {
pdfLink, err := url.Parse(link)
if err != nil {
return nil, err
}
if pdfLink.Scheme != "https" {
return nil, errors.New("Stamp link returned by API is not https, got: " + pdfLink.Scheme)
}
var response *http.Response
response, err = http.DefaultClient.Get(link)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error requesting stamp PDF from URL: %s. Status: %s ", link, response.Status)
}
defer response.Body.Close()
pdf, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if !bytes.Equal(pdf[:5], []byte("%PDF-")) {
return nil, errors.New("Downloaded stamp file is not PDF")
}
return pdf, nil
}
type Handler struct {
service *epservice.OneClickForAppPortTypeV3
template *template.Template
templateSuccess *template.Template
decoder *schema.Decoder
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
productState.RLock()
defer productState.RUnlock()
data := struct {
SupportAddress bool
Products []Product
Countries []Country
WalletUser string
}{
FormatSupportsAddress,
productState.products,
productState.countries,
WalletUser,
}
err := h.template.Execute(w, data)
if err != nil {
log.Println(err)
return
}
} else if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
http.Error(w, "Error parsing form", http.StatusBadRequest)
return
}
var stampData StampData
err = h.decoder.Decode(&stampData, r.PostForm)
if err != nil {
http.Error(w, "Error parsing form", http.StatusBadRequest)
return
}
balance, link, err := h.buyAndPrintStamp(&stampData)
if err != nil && len(link) == 0 {
http.Error(w, "Error buying stamps: "+err.Error(), http.StatusInternalServerError)
return
}
data := struct {
WalletUser string
Balance int
Link string
PrintSuccess bool
}{
WalletUser,
balance,
link,
err == nil,
}
if err := h.templateSuccess.Execute(w, data); err != nil {
log.Println(err)
}
} else {
http.Error(w, "Method unsupported", http.StatusMethodNotAllowed)
}
return
}
func (h *Handler) buyAndPrintStamp(stamp *StampData) (int, string, error) {
authResponse, err := h.service.AuthenticateUser(&epservice.AuthenticateUserRequest{
Username: WalletUser,
Password: WalletPassword,
})
if err != nil {
return 0, "", err
}
var pageFormat int32 = int32(PageFormat)
var productCode int32 = int32(stamp.Product)
productState.RLock()
product, ok := productState.productMap[stamp.Product]
productState.RUnlock()
if !ok {
return 0, "", errors.New("Invalid product id")
}
if stamp.StampAddress && stamp.ReceiverCountry != "DEU" && !product.International {
return 0, "", errors.New("Product must be international if receiver is not DEU")
}
var total int32 = int32(product.Cost) //Only support one purchase at a time right now
var createManifest bool = false
var voucherLayout *epservice.VoucherLayout
var addressBinding *epservice.AddressBinding
if FormatSupportsAddress && stamp.StampAddress {
voucherLayout = &epservice.VoucherLayoutAddressZone
senderCompany, receiverCompany, senderPerson, receiverPerson := processNames(stamp)
addressBinding = &epservice.AddressBinding{
Sender: &epservice.NamedAddress{
Name: &epservice.Name{
CompanyName: senderCompany,
PersonName: senderPerson,
},
Address: &epservice.Address{
Street: stamp.SenderStreet,
HouseNo: stamp.SenderHouseNo,
Zip: stamp.SenderZIP,
City: stamp.SenderCity,
Country: "DEU",
},
},
Receiver: &epservice.NamedAddress{
Name: &epservice.Name{
CompanyName: receiverCompany,
PersonName: receiverPerson,
},
Address: &epservice.Address{
Street: stamp.ReceiverStreet,
HouseNo: stamp.ReceiverHouseNo,
Zip: stamp.ReceiverZIP,
City: stamp.ReceiverCity,
Country: stamp.ReceiverCountry,
},
},
}
} else {
voucherLayout = &epservice.VoucherLayoutFrankingZone
}
cartResponse, err := h.service.CheckoutShoppingCartPDF(&epservice.CheckoutShoppingCartPDFRequest{
UserToken: authResponse.UserToken,
PageFormatId: (*epservice.PageFormatId)(&pageFormat),
Positions: []*epservice.ShoppingCartPDFPosition{{
ShoppingCartPosition: &epservice.ShoppingCartPosition{
ProductCode: (*epservice.ProductCode)(&productCode),
Address: addressBinding,
VoucherLayout: voucherLayout,
},
Position: &epservice.VoucherPosition{
Position: &epservice.Position{
LabelX: 1,
LabelY: 1,
},
Page: 1,
},
}},
Total: (*epservice.ShoppingCartPrice)(&total),
CreateManifest: (*epservice.Flag)(&createManifest),
CreateShippingList: &epservice.ShippingList0,
})
if err != nil {
return 0, "", err
}
balance := int(*cartResponse.WalletBallance)
link := string(*cartResponse.Link)
log.Println("Fetching PDF bytes")
pdf, err := getStampPDFBytes(link)
if err != nil {
return balance, "", err
}
//TODO factor out printing
log.Println("Starting print")
lprPath, err := exec.LookPath("lpr")
if err != nil {
return balance, link, err
}
printCmd := exec.Command(lprPath, "-P", PrinterName, "-C", "Internetmarke")
printCmd.Stdin = bytes.NewBuffer(pdf)
output, err := printCmd.CombinedOutput()
if err != nil {
log.Println("Printing error: ", string(output))
return balance, link, err
}
return int(*cartResponse.WalletBallance), link, nil
}
func processNames(stamp *StampData) (senderCompany, receiverCompany *epservice.CompanyName, senderPerson, receiverPerson *epservice.PersonName) {
// API demands both given and surname
splitSenderName := strings.SplitN(strings.TrimSpace(stamp.SenderName), " ", 2)
splitReceiverName := strings.SplitN(strings.TrimSpace(stamp.ReceiverName), " ", 2)
if stamp.SenderCompany != "" {
senderCompany = &epservice.CompanyName{
Company: stamp.SenderCompany,
}
}
if stamp.SenderName != "" {
var s *epservice.PersonName
if len(splitSenderName) < 2 {
s = &epservice.PersonName{
Firstname: " ",
Lastname: splitSenderName[0],
}
} else {
s = &epservice.PersonName{
Firstname: splitSenderName[0],
Lastname: splitSenderName[1],
}
}
if senderCompany != nil {
senderCompany.PersonName = s
} else {
senderPerson = s
}
}
if stamp.ReceiverCompany != "" {
receiverCompany = &epservice.CompanyName{
Company: stamp.ReceiverCompany,
}
}
if stamp.ReceiverName != "" {
var s *epservice.PersonName
if len(splitReceiverName) < 2 {
s = &epservice.PersonName{
Firstname: " ",
Lastname: splitReceiverName[0],
}
} else {
s = &epservice.PersonName{
Firstname: splitReceiverName[0],
Lastname: splitReceiverName[1],
}
}
if receiverCompany != nil {
receiverCompany.PersonName = s
} else {
receiverPerson = s
}
}
return
}
func checkPageFormat(service *epservice.OneClickForAppPortTypeV3, requestedFormat int) (supportsAddress bool, err error) {
var pageFormatResponse *epservice.RetrievePageFormatsResponse
pageFormatResponse, err = service.RetrievePageFormats(&epservice.RetrievePageFormatsRequest{})
if err != nil {
return
}
//TODO output page formats on user request
/*for _, v := range pageFormatResponse.PageFormat {
log.Printf("%d - %s", *v.Id, v.Name)
}
var out []byte
out, err = json.MarshalIndent(pageFormatResponse.PageFormat, "", "\t")
if err != nil {
log.Fatal(err)
}
os.Stdout.Write([]byte("\n\n"))
os.Stdout.Write(out)
os.Stdout.Write([]byte("\n\n"))
os.Exit(0)*/
for _, v := range pageFormatResponse.PageFormat {
id := int(*v.Id)
if id == requestedFormat {
log.Printf("Using page format: %d - %s. Address possible: %v\n", id, v.Name, v.IsAddressPossible)
return v.IsAddressPossible, nil
}
}
return false, errors.New("Requested page format not found")
}