This repository has been archived by the owner on Nov 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapp.go
368 lines (324 loc) · 10.2 KB
/
app.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package main
import (
"context"
"fmt"
"io"
"log"
"math"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"time"
"riftshare/transport"
"github.com/gen2brain/beeep"
"github.com/psanford/wormhole-william/wormhole"
"github.com/wailsapp/wails/v2/pkg/runtime"
"github.com/klauspost/compress/zip"
)
// App application struct
type App struct {
ctx context.Context
c *transport.Client
selectedFiles []string
wormholeCtx *context.Context
wormholeCancel *context.CancelFunc
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{c: transport.NewClient()}
}
// startup is called at application startup
func (b *App) startup(ctx context.Context) {
// Perform your setup here
b.ctx = ctx
settings, err := GetUserSettings()
if err != nil {
log.Println(err)
}
b.c.Notifications = settings.Notifications
b.c.OverwriteExisting = settings.Overwrite
b.c.DownloadPath = settings.DownloadsDirectory
}
// domReady is called after the front-end dom has been loaded
func (b *App) domReady(ctx context.Context) {
// Add your action here
b.UpdateCheckUI()
}
// shutdown is called at application termination
func (b *App) shutdown(ctx context.Context) {
// Perform your teardown here
settings := UserSettings{
Notifications: b.c.Notifications,
Overwrite: b.c.OverwriteExisting,
DownloadsDirectory: b.c.DownloadPath,
}
err := SaveUserSettings(settings)
if err != nil {
log.Println("Could not persist user settings")
}
}
// Greet returns a greeting for the given name
func (b *App) OpenDirectoryDialog() []string {
opts := runtime.OpenDialogOptions{Title: "Select Directory", DefaultDirectory: b.GetDownloadsFolder(), AllowDirectories: true}
selection, err := runtime.OpenDirectoryDialog(b.ctx, opts)
if err != nil {
runtime.LogInfo(b.ctx, "Error opening dialog")
b.ShowErrorDialog(err.Error())
}
runtime.LogInfo(b.ctx, "File Selected:"+selection)
b.selectedFiles = []string{selection}
return b.selectedFiles
}
func (b *App) OpenFilesDialog() []string {
opts := runtime.OpenDialogOptions{Title: "Select File", AllowFiles: true, DefaultDirectory: b.GetDownloadsFolder()}
selection, err := runtime.OpenMultipleFilesDialog(b.ctx, opts)
if err != nil {
runtime.LogInfo(b.ctx, "Error opening dialog")
}
runtime.LogInfo(b.ctx, "File Selected:")
log.Println(selection)
b.selectedFiles = selection
return b.selectedFiles
}
func (b *App) SendFile(filePath string) {
runtime.LogInfo(b.ctx, "Sending File: "+filePath)
runtime.EventsEmit(b.ctx, "send:status", "retrieving code")
go func() {
ctx := *b.wormholeCtx
code, status, err := b.c.NewFileSend(ctx, filePath, wormhole.WithProgress(b.UpdateSendProgress))
if err != nil {
runtime.LogError(b.ctx, "Send Failed")
runtime.EventsEmit(b.ctx, "send:status", "failed")
b.ShowErrorDialog(err.Error())
}
runtime.EventsEmit(b.ctx, "send:started", code)
runtime.EventsEmit(b.ctx, "send:status", "waiting for receiver")
select {
case s := <-status:
if s.Error != nil {
runtime.LogError(b.ctx, "Send Failed")
runtime.EventsEmit(b.ctx, "send:status", "failed")
b.ShowErrorDialog(s.Error.Error())
} else if s.OK {
runtime.LogInfo(b.ctx, "Send Success")
runtime.EventsEmit(b.ctx, "send:status", "completed")
if b.c.Notifications {
beeep.Notify("RiftShare", "Send Complete", "appicon.png")
}
}
if filepath.Ext(filePath) == ".zip" {
os.Remove(filePath)
}
case <-ctx.Done():
// If the request gets cancelled, log it
// to STDERR
log.Println("Request cancelled, removing zip file")
if filepath.Ext(filePath) == ".zip" {
os.Remove(filePath)
}
}
}()
}
func (b *App) SendDirectory(dirPath string) {
runtime.LogInfo(b.ctx, "Sending Directory: "+dirPath)
runtime.EventsEmit(b.ctx, "send:status", "sending")
go func() {
code, status, err := b.c.NewDirSend(*b.wormholeCtx, dirPath, wormhole.WithProgress(b.UpdateSendProgress))
if err != nil {
runtime.LogError(b.ctx, "Send Failed")
runtime.EventsEmit(b.ctx, "send:status", "failed")
b.ShowErrorDialog(err.Error())
}
runtime.EventsEmit(b.ctx, "send:started", code)
s := <-status
if s.Error != nil {
runtime.LogError(b.ctx, "Send Failed")
runtime.EventsEmit(b.ctx, "send:status", "failed")
b.ShowErrorDialog(s.Error.Error())
} else if s.OK {
runtime.LogInfo(b.ctx, "Send Success")
runtime.EventsEmit(b.ctx, "send:status", "completed")
}
}()
}
func (b *App) ReceiveFile(code string) {
runtime.LogInfo(b.ctx, "Receiving File...")
runtime.EventsEmit(b.ctx, "receive:status", "receiving")
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
b.wormholeCtx = &ctx
b.wormholeCancel = &cancel
pathname := make(chan string, 1)
progress := make(chan float64)
runtime.EventsEmit(b.ctx, "receive:started")
go func() {
path := <-pathname
runtime.LogInfo(b.ctx, path)
runtime.EventsEmit(b.ctx, "receive:path", path)
runtime.EventsEmit(b.ctx, "receive:status", "receiving")
}()
go func() {
for percent := range progress {
// log.Println(percent)
runtime.EventsEmit(b.ctx, "receive:updated", percent)
}
}()
go func() {
err := b.c.NewReceive(*b.wormholeCtx, code, pathname, progress)
if err != nil {
runtime.LogError(b.ctx, "Receive Failed")
runtime.EventsEmit(b.ctx, "receive:status", "failed")
b.ShowErrorDialog(err.Error())
}
runtime.EventsEmit(b.ctx, "receive:status", "completed")
if b.c.Notifications {
beeep.Notify("RiftShare", "Receive Complete", "appicon.png")
}
}()
}
func (b *App) UpdateSendProgress(sentBytes int64, totalBytes int64) {
percentage := math.Round(float64(sentBytes) / float64(totalBytes) * 100)
// runtime.LogInfo(b.ctx, "Progress"+strconv.Itoa(int(percentage)))
runtime.EventsEmit(b.ctx, "send:updated", percentage)
}
func (b *App) OpenFile(path string) {
var err error
switch goruntime.GOOS {
case "linux":
err = exec.Command("xdg-open", path).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", path).Start()
case "darwin":
err = exec.Command("open", path).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Println(err)
}
}
func (b *App) SelectedFilesSend() {
// Create a new context
ctx := context.Background()
// Create a new context, with its cancellation function
// from the original context
ctx, cancel := context.WithCancel(ctx)
b.wormholeCtx = &ctx
b.wormholeCancel = &cancel
if len(b.selectedFiles) == 1 {
fileInfo, err := os.Stat(b.selectedFiles[0])
if err != nil {
runtime.LogError(b.ctx, "Could not check send file info")
}
if fileInfo.IsDir() {
b.SendDirectory(b.selectedFiles[0])
} else {
b.SendFile(b.selectedFiles[0])
}
} else {
archivePath := b.zipFiles(b.selectedFiles)
b.SendFile(archivePath)
}
}
func (b *App) zipFiles(pathNames []string) string {
homeDir, err := os.UserHomeDir()
if err != nil {
runtime.LogError(b.ctx, "Could not find home directory")
}
runtime.LogInfo(b.ctx, "creating zip archive...")
runtime.EventsEmit(b.ctx, "send:status", "compressing Files")
timeString := time.Now().Format("2006-01-02-15-04-05")
archiveName := fmt.Sprintf("wormhole-%s.zip", timeString)
archivePath := filepath.Join(homeDir, archiveName)
archive, err := os.Create(archivePath)
if err != nil {
runtime.LogFatal(b.ctx, "Error creating archive")
}
defer archive.Close()
w := zip.NewWriter(archive)
defer w.Close()
for _, filePath := range pathNames {
file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
defer file.Close()
f, err := w.Create(filepath.Base(file.Name()))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(f, file)
if err != nil {
log.Fatal(err)
}
}
runtime.EventsEmit(b.ctx, "send:status", "zip Complete")
return archivePath
}
func (b *App) CancelWormholeRequest() {
runtime.LogInfo(b.ctx, "Cancelled wormhole request. ")
cancel := *b.wormholeCancel
cancel()
}
func (b *App) UpdateCheckUI() {
shouldUpdate, latestVersion := checkForUpdate()
if shouldUpdate {
updateMessage := fmt.Sprintf("New Version Available, would you like to update to v%s", latestVersion)
buttons := []string{"Yes", "No"}
dialogOpts := runtime.MessageDialogOptions{Title: "Update Available", Message: updateMessage, Type: runtime.QuestionDialog, Buttons: buttons, DefaultButton: "Yes", CancelButton: "No"}
action, err := runtime.MessageDialog(b.ctx, dialogOpts)
if err != nil {
runtime.LogError(b.ctx, "Error in update dialog. ")
}
runtime.LogInfo(b.ctx, action)
if action == "Yes" {
log.Println("Update clicked")
updated := doSelfUpdate()
if updated {
buttons = []string{"Ok"}
dialogOpts = runtime.MessageDialogOptions{Title: "Update Succeeded", Message: "Update Successfull. Please restart. ", Type: runtime.InfoDialog, Buttons: buttons, DefaultButton: "Ok"}
runtime.MessageDialog(b.ctx, dialogOpts)
} else {
buttons = []string{"Ok"}
dialogOpts = runtime.MessageDialogOptions{Title: "Update Error", Message: "Update failed, try again later. ", Type: runtime.InfoDialog, Buttons: buttons, DefaultButton: "Ok"}
runtime.MessageDialog(b.ctx, dialogOpts)
}
}
}
}
func (b *App) GetDownloadsFolder() string {
return b.c.DownloadPath
}
func (b *App) GetCurrentVersion() string {
return version
}
func (b *App) SetDownloadsFolder() string {
opts := runtime.OpenDialogOptions{Title: "Select Directory", DefaultDirectory: b.GetDownloadsFolder(), AllowDirectories: true}
selection, err := runtime.OpenDirectoryDialog(b.ctx, opts)
if err != nil {
runtime.LogInfo(b.ctx, "Error opening dialog")
b.ShowErrorDialog(err.Error())
}
b.c.DownloadPath = selection
return b.c.DownloadPath
}
func (b *App) SetOverwriteParam(val bool) bool {
b.c.OverwriteExisting = val
return b.c.OverwriteExisting
}
func (b *App) GetOverwriteParam() bool {
return b.c.OverwriteExisting
}
func (b *App) SetNotificationsParam(val bool) bool {
b.c.Notifications = val
return b.c.Notifications
}
func (b *App) GetNotificationsParam() bool {
return b.c.Notifications
}
func (b *App) ShowErrorDialog(message string) {
buttons := []string{"Ok"}
opts := runtime.MessageDialogOptions{Title: "Error Occured", Message: message, Buttons: buttons, Type: runtime.ErrorDialog, DefaultButton: "Ok"}
runtime.MessageDialog(b.ctx, opts)
}