-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathuniclip.go
234 lines (218 loc) · 5.39 KB
/
uniclip.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
package main
import (
"bufio"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
var secondsBetweenChecksForClipChange = 1
var helpMsg = `Uniclip - Universal Clipboard
With Uniclip, you can copy from one device and paste on the other.
Usage: uniclip [ <address> | --help/-h ]
Examples:
uniclip # start a new clipboard
uniclip 192.168.86.24:53701 # join the clipboard at the address - 192.168.86.24:53701
uniclip --help # print this help message
Running just ` + "`uniclip`" + ` will start a new clipboard.
It will also provide an address with which you can connect to the clipboard with another device.`
var detectedOs = runtime.GOOS
var listOfClients = make([]*bufio.Writer, 0)
var localClipboard string
var lock sync.Mutex
func main() {
if len(os.Args) == 2 {
if os.Args[1] == "--help" || os.Args[1] == "-h" {
fmt.Println(helpMsg)
return
}
connectToServer(os.Args[1])
} else if len(os.Args) == 1 {
fmt.Println("Starting a new clipboard!")
makeServer()
} else {
fmt.Println("Too many arguments.\nTo start a new clipboard, use `uniclip`.\nTo connect to a clipboard, use `uniclip <IP>:<PORT>`")
}
}
func makeServer() {
l, err := net.Listen("tcp4", "0.0.0.0:")
if err != nil {
handleError(err)
return
}
defer l.Close()
port := strconv.FormatInt(int64(l.Addr().(*net.TCPAddr).Port), 10)
fmt.Println("Run", "`uniclip", getOutboundIP().String()+":"+port+"`", "to join this clipboard")
fmt.Println()
for {
c, err := l.Accept()
if err != nil {
handleError(err)
return
}
fmt.Println("Connected to the device")
go handleClient(c)
}
}
func handleClient(c net.Conn) {
w := bufio.NewWriter(c)
listOfClients = append(listOfClients, w)
defer c.Close()
go monitorSentClips(bufio.NewReader(c))
monitorLocalClip(w)
}
func connectToServer(address string) {
c, err := net.Dial("tcp4", address)
defer c.Close()
if err != nil {
handleError(err)
return
}
fmt.Println("Connected to the clipboard")
go monitorSentClips(bufio.NewReader(c))
monitorLocalClip(bufio.NewWriter(c))
}
func monitorLocalClip(w *bufio.Writer) {
for {
lock.Lock()
localClipboard = getLocalClip()
lock.Unlock()
err := sendClipboard(w, localClipboard)
if err != nil {
handleError(err)
return
}
for localClipboard == getLocalClip() {
time.Sleep(time.Second * time.Duration(secondsBetweenChecksForClipChange))
}
}
}
func monitorSentClips(r *bufio.Reader) {
var foreignClipboard string
for {
s, err := r.ReadString('\n')
if err != nil {
handleError(err)
return
}
if s == "STARTCLIPBOARD\n" {
for {
s, err = r.ReadString('\n')
if err != nil {
handleError(err)
return
}
if s == "ENDCLIPBOARD\n" {
foreignClipboard = strings.TrimSuffix(foreignClipboard, "\n")
break
}
foreignClipboard += s
}
lock.Lock() // don't let the goroutine that checks for changes do anything
setLocalClip(foreignClipboard)
localClipboard = foreignClipboard
lock.Unlock() // we've made sure the other goroutine won't have a false positive
// fmt.Println("Copied:" + "\n\"" + foreignClipboard + "\"\n") // debugging
for i, w := range listOfClients {
if w != nil {
err := sendClipboard(w, foreignClipboard)
if err != nil {
listOfClients[i] = nil
handleError(err)
}
}
}
foreignClipboard = ""
}
}
}
func sendClipboard(w *bufio.Writer, clipboard string) error {
var err error
clipString := "STARTCLIPBOARD\n" + clipboard + "\nENDCLIPBOARD\n"
_, err = w.WriteString(clipString)
if err != nil {
return err
}
err = w.Flush()
if err != nil {
return err
}
return nil
}
func getLocalClip() string {
var out []byte
var err error
var cmd *exec.Cmd
errMsg := "An error occurred wile getting the local clipboard"
if detectedOs == "darwin" {
cmd = exec.Command("pbpaste")
} else if detectedOs == "windows" {
cmd = exec.Command("powershell.exe", "-command", "Get-Clipboard")
}
if out, err = cmd.CombinedOutput(); err != nil {
handleError(err)
if exiterr, ok := err.(*exec.ExitError); ok {
fmt.Println(string(exiterr.Stderr))
}
return errMsg
}
if detectedOs == "windows" {
return strings.TrimSuffix(string(out), "\n") // ps's get-clipboard adds a newline to the end for some reason
}
return string(out)
}
func setLocalClip(s string) {
var copyCmd *exec.Cmd
if detectedOs == "darwin" {
copyCmd = exec.Command("pbcopy")
} else if detectedOs == "windows" {
copyCmd = exec.Command("powershell.exe", "-command", "Set-Clipboard")
}
in, err := copyCmd.StdinPipe()
if err != nil {
handleError(err)
return
}
if err := copyCmd.Start(); err != nil {
handleError(err)
return
}
if _, err := in.Write([]byte(s)); err != nil {
handleError(err)
return
}
if err := in.Close(); err != nil {
handleError(err)
return
}
if err := copyCmd.Wait(); err != nil {
handleError(err)
return
}
return
}
func getOutboundIP() net.IP {
// https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go/37382208#37382208
conn, err := net.Dial("udp", "8.8.8.8:80") // address can be anything. Doesn't even have to exist
if err != nil {
handleError(err)
return nil
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
func handleError(err error) {
if err == io.EOF {
fmt.Println("Disconnected from a device")
} else {
fmt.Println("An error occurred:", err)
}
return
}