Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
318 lines (266 loc) · 7.27 KB
/
Copy pathserver.go
File metadata and controls
318 lines (266 loc) · 7.27 KB
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
package main
import (
"context"
_ "embed"
"encoding/base64"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
type guideTemplateParams struct {
ShortcutsURL string
ExecPath string
IsAutoRun string
HostName string
LocalIP string
Port string
Password string
Notify string
ConnectedDevices string
}
// Store the device's last poll timestamp
var DeviceStates = make(map[string]TimeStamp)
var DeviceAlive = 120 * time.Second
func StartHTTPServer(ctx context.Context, port int) error {
// gin.SetMode(gin.ReleaseMode)
router := setupRouter()
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: router,
}
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
log.Printf("Server forced to shutdown: %v", err)
}
}()
log.Printf("Server starting on http://localhost:%d", port)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return fmt.Errorf("server failed to start: %v", err)
}
log.Printf("HTTP server shutting down.")
return nil
}
func clientName() gin.HandlerFunc {
return func(c *gin.Context) {
urlEncodedClientName := c.GetHeader("X-Client-Name")
clientName, err := url.PathUnescape(urlEncodedClientName)
if err != nil || clientName == "" {
clientName = "<Unknown Device>"
}
c.Set("clientName", clientName)
c.Next()
}
}
func auth() gin.HandlerFunc {
return func(c *gin.Context) {
if Password == "" {
c.Next()
return
}
reqAuth := c.GetHeader("X-Password")
if Password == reqAuth {
c.Next()
return
}
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "wrong password",
})
}
}
func setupRouter() *gin.Engine {
router := gin.Default()
tmpl := template.Must(template.New("guide").Parse(GuideTemplate))
router.SetHTMLTemplate(tmpl)
router.GET("/favicon.ico", func(c *gin.Context) {
c.Data(http.StatusOK, "image/x-icon", IconData)
})
router.GET("/shortcuts.png", func(c *gin.Context) {
c.Data(http.StatusOK, "image/png", ShortcutsData)
})
router.GET("/", guideHandler)
router.Use(clientName(), auth())
router.GET("/get", getHandler)
router.POST("/set", setHandler)
router.POST("/settings", settingsHandler)
router.GET("/poll", pollHandler)
return router
}
func guideHandler(c *gin.Context) {
isAutoRun, err := QueryAutoRun()
isAutoRunText := "否(No)"
if err != nil {
log.Println("[Warn] Unable to query AutoRun status:", err)
} else if isAutoRun {
isAutoRunText = "是(Yes)"
}
hostname, _ := os.Hostname()
notify := ""
if Notify != 0 {
notify = "checked"
}
c.HTML(http.StatusOK, "guide", guideTemplateParams{
ShortcutsURL: ShortcutsURL,
ExecPath: os.Args[0],
IsAutoRun: isAutoRunText,
HostName: hostname,
LocalIP: GetLocalIP(),
Port: fmt.Sprintf("%d", Port),
Password: Password,
Notify: notify,
ConnectedDevices: func() string {
var devices string
for device, timestamp := range DeviceStates {
devices += fmt.Sprintf("%s(%s), ", device, time.Unix(timestamp, 0).Format("2006/01/02 15:04:05"))
}
return devices
}(),
})
}
func settingsHandler(c *gin.Context) {
port := c.PostForm("port")
if port != "" {
if portInt, err := strconv.Atoi(port); err != nil || portInt <= 0 || portInt > 65536 {
log.Println("invalid port number")
c.JSON(http.StatusBadRequest, gin.H{"error": "Port number must be between 1 and 65535"})
return
}
} else {
port = fmt.Sprintf("%d", Port)
}
password := c.PostForm("password")
log.Println("[!]Notify:", c.PostForm("notify"))
notify := 0
if c.PostForm("notify") == "on" {
notify = 1
}
go Restart(port, password, notify)
}
func getHandler(c *gin.Context) {
if ClipboardLatest == TypeText {
log.Println("get clipboard text")
c.JSON(http.StatusOK, gin.H{
"type": TypeText,
"data": *ClipboardText,
"version": ClipboardLocalVersion,
})
defer SendNotification(fmt.Sprintf("To [%s]", c.GetString("clientName")), *ClipboardText)
return
}
if ClipboardLatest == TypeImage {
c.JSON(http.StatusOK, gin.H{
"type": TypeImage,
"data": base64.StdEncoding.EncodeToString(*ClipboardImage),
"version": ClipboardLocalVersion,
})
defer SendNotification(fmt.Sprintf("To [%s]", c.GetString("clientName")), "[Image]")
return
}
c.JSON(http.StatusBadRequest, gin.H{"error": "unknown content type"})
}
type ReqBody struct {
Data string `json:"data"`
}
func setHandler(c *gin.Context) {
contentType := c.GetHeader("X-Content-Type")
remoteVersion := c.GetHeader("X-Version")
if remoteVersion == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing version"})
return
}
version, err := strconv.ParseInt(remoteVersion, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid version"})
return
}
setClipboardVersion(version)
if contentType == TypeText {
setTextHandler(c)
} else if contentType == TypeImage {
setImageHandler(c)
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "unknown content type"})
return
}
}
func setTextHandler(c *gin.Context) {
var body ReqBody
if err := c.ShouldBindJSON(&body); err != nil {
log.Println("failed to bind text body")
c.Status(http.StatusBadRequest)
return
}
SetClipboardText(body.Data)
var notify string = "<empty>"
if body.Data != "" {
notify = body.Data
}
defer SendNotification(fmt.Sprintf("From [%s]", c.GetString("clientName")), notify)
log.Println("set clipboard text")
c.Status(http.StatusOK)
}
func setImageHandler(c *gin.Context) {
var body ReqBody
if err := c.ShouldBindJSON(&body); err != nil {
log.Println("failed to bind image body")
c.Status(http.StatusBadRequest)
return
}
imgBytes, err := base64.StdEncoding.DecodeString(body.Data)
if err != nil {
log.Println("failed to decode base64 image")
c.Status(http.StatusBadRequest)
return
}
SetClipboardImage(imgBytes)
defer SendNotification(fmt.Sprintf("From [%s]", c.GetString("clientName")), "[Image]")
log.Println("set clipboard image")
c.Status(http.StatusOK)
}
func pollHandler(c *gin.Context) {
reqVersion := c.GetHeader("X-Version")
client := c.GetString("clientName")
defer func() {
DeviceStates[client] = TimeStamp(time.Now().Unix())
}()
lastPoll, ok := DeviceStates[client]
isFirstPoll := false
if !ok || time.Since(time.Unix(lastPoll, 0)) > DeviceAlive { // new device
isFirstPoll = true
}
if reqVersion == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing version"})
return
}
remoteVersion, err := strconv.ParseInt(reqVersion, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid version"})
return
}
if remoteVersion == ClipboardLocalVersion {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
} else if remoteVersion < ClipboardLocalVersion {
// from PC to phone
log.Println("from PC to phone: ", remoteVersion, "<", ClipboardLocalVersion)
getHandler(c)
return
} else {
// from phone to PC
if isFirstPoll {
setClipboardVersion(remoteVersion)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
log.Println("from phone to PC: ", remoteVersion, ">", ClipboardLocalVersion)
c.JSON(http.StatusOK, gin.H{"status": "conflict"})
}
}