forked from macdylan/sm2uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnector.go
117 lines (100 loc) · 2.22 KB
/
connector.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
package main
import (
"errors"
"io"
"net"
"runtime"
"time"
)
const (
FILE_SIZE_MIN = 1
FILE_SIZE_MAX = 2 << 30 // 2GB
)
var (
errFileEmpty = errors.New("File is empty.")
errFileTooLarge = errors.New("File is too large.")
)
type Payload struct {
File io.Reader
Name string
Size int64
}
func (p *Payload) SetName(name string) {
p.Name = normalizedFilename(name)
}
func (p *Payload) ReadableSize() string {
return humanReadableSize(p.Size)
}
func (p *Payload) GetContent(nofix bool) (cont []byte, err error) {
defer runtime.GC()
if nofix || !p.ShouldBeFix() {
cont, err = io.ReadAll(p.File)
} else {
cont, err = postProcess(p.File)
p.Size = int64(len(cont))
}
return cont, err
}
func (p *Payload) ShouldBeFix() bool {
return shouldBeFix(p.Name)
}
func NewPayload(file io.Reader, name string, size int64) *Payload {
return &Payload{
File: file,
Name: normalizedFilename(name),
Size: size,
}
}
type connector struct {
handlers []Handler
}
type Handler interface {
Ping(*Printer) bool
Connect() error
Disconnect() error
Upload(*Payload) error
}
func (c *connector) RegisterHandler(h Handler) {
c.handlers = append(c.handlers, h)
}
// Upload to upload a file to a printer
func (c *connector) Upload(printer *Printer, payload *Payload) error {
// Iterate through all handlers
for _, h := range c.handlers {
// Check if handler can ping the printer
if h.Ping(printer) {
// Connect to the printer
if err := h.Connect(); err != nil {
return err
}
defer h.Disconnect()
if payload.Size > FILE_SIZE_MAX {
return errFileTooLarge
}
if payload.Size < FILE_SIZE_MIN {
return errFileEmpty
}
// Upload the file to the printer
if err := h.Upload(payload); err != nil {
return err
}
// Return nil if successful
return nil
}
}
// Return error if printer is not available
return errors.New("Printer " + printer.IP + " is not available.")
}
var Connector = &connector{}
// ping the printer to see if it is available
func ping(ip string, port string, timeout int) bool {
if timeout <= 0 {
timeout = 2
}
conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Second*time.Duration(timeout))
if err != nil {
return false
}
defer conn.Close()
return true
}