-
Notifications
You must be signed in to change notification settings - Fork 16
/
sender.go
101 lines (84 loc) 路 2.27 KB
/
sender.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
package sender
import (
"os"
"io"
"fmt"
"net"
"time"
"syscall"
"net/http"
"os/signal"
"github.com/gorilla/websocket"
"github.com/abdfnx/tran/models"
"github.com/abdfnx/tran/core/crypt"
)
// Sender represents the sender client, handles tranx communication and file transfer.
type Sender struct {
payload io.Reader
payloadSize int64
senderServer *Server
closeServer chan os.Signal
receiverIP net.IP
tranxAddress string
tranxPort int
ui chan<- UIUpdate
crypt *crypt.Crypt
state TransferState
}
// NewSender returns a bare bones Sender.
func NewSender(programOptions models.TranOptions) *Sender {
closeServerCh := make(chan os.Signal, 1)
signal.Notify(closeServerCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
return &Sender{
closeServer: closeServerCh,
tranxAddress: programOptions.TranxAddress,
tranxPort: programOptions.TranxPort,
state: Initial,
}
}
// WithPayload specifies the payload that will be transfered.
func WithPayload(s *Sender, payload io.Reader, payloadSize int64) *Sender {
s.payload = payload
s.payloadSize = payloadSize
return s
}
// WithServer specifies the option to run the sender by hosting a server which the receiver establishes a connection to.
func WithServer(s *Sender, options ServerOptions) *Sender {
s.receiverIP = options.receiverIP
router := &http.ServeMux{}
s.senderServer = &Server{
router: router,
server: &http.Server{
Addr: fmt.Sprintf(":%d", options.port),
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
Handler: router,
},
upgrader: websocket.Upgrader{},
}
// setup routes
router.HandleFunc("/tran", s.handleTransfer())
return s
}
// WithUI specifies the option to run the sender with an UI channel that reports the state of the transfer.
func WithUI(s *Sender, ui chan<- UIUpdate) *Sender {
s.ui = ui
return s
}
func (s *Sender) TranxAddress() string {
return s.tranxAddress
}
func (s *Sender) TranxPort() int {
return s.tranxPort
}
// updateUI is a helper function that checks if we have a UI channel and reports the state.
func (s *Sender) updateUI(progress ...float32) {
if s.ui == nil {
return
}
var p float32
if len(progress) > 0 {
p = progress[0]
}
s.ui <- UIUpdate{State: s.state, Progress: p}
}