80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"yumc.pw/cloud/clipboard-sync/lib/clipboard"
|
|
)
|
|
|
|
func main() {
|
|
t := flag.String("t", "c", "Type c(client) or s(server)")
|
|
a := flag.String("a", "http://127.0.0.1:8080", "Server Address")
|
|
b := flag.String("b", ":8080", "Server Listen Port")
|
|
flag.Parse()
|
|
if *t == "c" {
|
|
if clipboard.Unsupported {
|
|
panic("Unsupported On This Machine")
|
|
}
|
|
readClipboard(*a)
|
|
} else {
|
|
startServer(*b)
|
|
}
|
|
}
|
|
|
|
const (
|
|
TextHeader = "Go-Clipboard-Text"
|
|
TimeHeader = "Go-Clipboard-Time"
|
|
)
|
|
|
|
func startServer(b string) {
|
|
text := ""
|
|
time := time.Now().Unix()
|
|
var err error
|
|
g := gin.Default()
|
|
g.GET("/", func(c *gin.Context) {
|
|
c.Header(TextHeader, text)
|
|
c.Header(TimeHeader, strconv.FormatInt(time, 10))
|
|
})
|
|
g.POST("/", func(c *gin.Context) {
|
|
text = c.Query("text")
|
|
time, err = strconv.ParseInt(c.Query("time"), 10, 64)
|
|
})
|
|
g.Run(b)
|
|
}
|
|
|
|
func readClipboard(a string) {
|
|
old, _ := clipboard.ReadAll()
|
|
updateTime := time.Now().Unix()
|
|
client := &http.Client{}
|
|
address := a + "?text=%s&time=%s"
|
|
for {
|
|
time.Sleep(100 * time.Millisecond)
|
|
text, _ := clipboard.ReadAll()
|
|
if old != text {
|
|
old = text
|
|
updateTime = time.Now().Unix()
|
|
request, _ := http.NewRequest("POST",
|
|
fmt.Sprintf(address, text, strconv.FormatInt(updateTime, 10)), nil)
|
|
client.Do(request)
|
|
} else {
|
|
response, _ := http.Get(a)
|
|
texts, ok := response.Header[TextHeader]
|
|
if ok {
|
|
sText := texts[0]
|
|
sTime, _ := strconv.ParseInt(response.Header[TimeHeader][0], 10, 64)
|
|
if sTime > updateTime {
|
|
old = sText
|
|
updateTime = time.Now().Unix()
|
|
clipboard.WriteAll(sText)
|
|
fmt.Printf("Update Clipboard: %s\n", sText)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|