This repository has been archived by the owner on Feb 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathserver_amd64.go
851 lines (751 loc) · 27.5 KB
/
server_amd64.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
package cmd
import (
"bytes"
"fmt"
"image"
"image/png"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/asticode/go-astilectron"
bootstrap "github.com/asticode/go-astilectron-bootstrap"
"github.com/asticode/go-astilog"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/nikhilsaraf/go-tools/multithreading"
"github.com/pkg/browser"
"github.com/rs/cors"
"github.com/spf13/cobra"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/go/support/errors"
"github.com/stellar/kelp/gui"
"github.com/stellar/kelp/gui/backend"
"github.com/stellar/kelp/support/kelpos"
"github.com/stellar/kelp/support/logger"
"github.com/stellar/kelp/support/networking"
"github.com/stellar/kelp/support/prefs"
"github.com/stellar/kelp/support/sdk"
"github.com/stellar/kelp/support/utils"
)
const kelpAssetsPath = "/assets"
const uiLogsDir = "/ui_logs"
const vendorDirectory = "/vendor"
const trayIconName = "kelp-icon@1-8x.png"
const kelpCcxtPath = "/ccxt"
const ccxtDownloadBaseURL = "https://github.com/stellar/kelp/releases/download/ccxt-rest_v0.0.4"
const ccxtBinaryName = "ccxt-rest"
const ccxtWaitSeconds = 60
const versionPlaceholder = "VERSION_PLACEHOLDER"
const stringPlaceholder = "PLACEHOLDER_URL"
const redirectPlaceholder = "REDIRECT_URL"
const pingPlaceholder = "PING_URL"
const sleepNumSecondsBeforeReadyString = 1
const readyPlaceholder = "READY_STRING"
const readyStringIndicator = "Serving frontend and API server on HTTP port"
const downloadCcxtUpdateIntervalLogMillis = 1000
type serverInputs struct {
port *uint16
dev *bool
devAPIPort *uint16
horizonTestnetURI *string
horizonPubnetURI *string
noHeaders *bool
verbose *bool
noElectron *bool
}
func init() {
hasUICapability = true
options := serverInputs{}
options.port = serverCmd.Flags().Uint16P("port", "p", 8000, "port on which to serve")
options.dev = serverCmd.Flags().Bool("dev", false, "run in dev mode for hot-reloading of JS code")
options.devAPIPort = serverCmd.Flags().Uint16("dev-api-port", 8001, "port on which to run API server when in dev mode")
options.horizonTestnetURI = serverCmd.Flags().String("horizon-testnet-uri", "https://horizon-testnet.stellar.org", "URI to use for the horizon instance connected to the Stellar Test Network (must contain the word 'test')")
options.horizonPubnetURI = serverCmd.Flags().String("horizon-pubnet-uri", "https://horizon.stellar.org", "URI to use for the horizon instance connected to the Stellar Public Network (must not contain the word 'test')")
options.noHeaders = serverCmd.Flags().Bool("no-headers", false, "do not set X-App-Name and X-App-Version headers on requests to horizon")
options.verbose = serverCmd.Flags().BoolP("verbose", "v", false, "enable verbose log lines typically used for debugging")
options.noElectron = serverCmd.Flags().Bool("no-electron", false, "open in browser instead of using electron")
serverCmd.Run = func(ccmd *cobra.Command, args []string) {
isLocalMode := env == envDev
isLocalDevMode := isLocalMode && *options.dev
kos := kelpos.GetKelpOS()
var e error
if isLocalMode {
wd, e := os.Getwd()
if e != nil {
panic(errors.Wrap(e, "could not get working directory"))
}
if filepath.Base(wd) != "kelp" {
e := fmt.Errorf("need to invoke from the root 'kelp' directory")
utils.PrintErrorHintf(e.Error())
panic(e)
}
}
var logFilepath *kelpos.OSPath
if !isLocalDevMode {
l := logger.MakeBasicLogger()
t := time.Now().Format("20060102T150405MST")
logFilename := fmt.Sprintf("kelp-ui_%s.log", t)
uiLogsDirPath := kos.GetDotKelpWorkingDir().Join(uiLogsDir)
log.Printf("calling mkdir on uiLogsDirPath: %s ...", uiLogsDirPath.AsString())
e = kos.Mkdir(uiLogsDirPath)
if e != nil {
panic(errors.Wrap(e, "could not mkdir on uiLogsDirPath: "+uiLogsDirPath.AsString()))
}
// don't use explicit unix filepath here since it uses os.Open directly and won't work on windows
logFilepath = uiLogsDirPath.Join(logFilename)
setLogFile(l, logFilepath.Native())
if *options.verbose {
astilog.SetDefaultLogger()
}
}
// create a latch to trigger the browser opening once the backend server is loaded
openBrowserWg := &sync.WaitGroup{}
openBrowserWg.Add(1)
if !isLocalDevMode {
// don't use explicit unix filepath here since it uses os.Create directly and won't work on windows
assetsDirPath := kos.GetDotKelpWorkingDir().Join(kelpAssetsPath)
log.Printf("assetsDirPath: %s", assetsDirPath.AsString())
trayIconPath := assetsDirPath.Join(trayIconName)
log.Printf("trayIconPath: %s", trayIconPath.AsString())
e = writeTrayIcon(kos, trayIconPath, assetsDirPath)
if e != nil {
log.Fatal(errors.Wrap(e, "could not write tray icon"))
}
htmlContent := tailFileHTML
if runtime.GOOS == "windows" {
htmlContent = windowsInitialFile
}
appURL := fmt.Sprintf("http://localhost:%d", *options.port)
pingURL := fmt.Sprintf("http://localhost:%d/ping", *options.port)
// write out tail.html after setting the file to be tailed
tailFileCompiled1 := strings.Replace(htmlContent, stringPlaceholder, logFilepath.Native(), -1)
tailFileCompiled2 := strings.Replace(tailFileCompiled1, redirectPlaceholder, appURL, -1)
tailFileCompiled3 := strings.Replace(tailFileCompiled2, readyPlaceholder, readyStringIndicator, -1)
version := strings.TrimSpace(fmt.Sprintf("%s (%s)", guiVersion, version))
tailFileCompiled4 := strings.Replace(tailFileCompiled3, versionPlaceholder, version, -1)
tailFileCompiled5 := strings.Replace(tailFileCompiled4, pingPlaceholder, pingURL, -1)
tailFileCompiled := tailFileCompiled5
var electronURL string
if runtime.GOOS == "windows" {
// start a new web server to serve the tail file since windows does not allow accessing a file directly in electron
// likely because of the way the file path is specified
tailFilePort := startTailFileServer(tailFileCompiled)
electronURL = fmt.Sprintf("http://localhost:%d", tailFilePort)
} else {
tailFilepath := kos.GetDotKelpWorkingDir().Join("tail.html")
fileContents := []byte(tailFileCompiled)
e := ioutil.WriteFile(tailFilepath.Native(), fileContents, 0644)
if e != nil {
panic(fmt.Sprintf("could not write tailfile to path '%s': %s", tailFilepath, e))
}
electronURL = tailFilepath.Native()
}
// kick off the desktop window for UI feedback to the user
// local mode (non --dev) and release binary should open browser (since --dev already opens browser via yarn and returns)
go func() {
if *options.noElectron {
openBrowser(appURL, openBrowserWg)
} else {
openElectron(trayIconPath, electronURL)
}
}()
}
log.Printf("Starting Kelp GUI Server, gui=%s, cli=%s [%s]\n", guiVersion, version, gitHash)
checkInitRootFlags()
if !strings.Contains(*options.horizonTestnetURI, "test") {
panic("'horizon-testnet-uri' argument must contain the word 'test'")
}
if strings.Contains(*options.horizonPubnetURI, "test") {
panic("'horizon-pubnet-uri' argument must not contain the word 'test'")
}
horizonTestnetURI := strings.TrimSuffix(*options.horizonTestnetURI, "/")
horizonPubnetURI := strings.TrimSuffix(*options.horizonPubnetURI, "/")
log.Printf("using horizonTestnetURI: %s\n", horizonTestnetURI)
log.Printf("using horizonPubnetURI: %s\n", horizonPubnetURI)
if *rootCcxtRestURL == "" {
*rootCcxtRestURL = "http://localhost:3000"
e := sdk.SetBaseURL(*rootCcxtRestURL)
if e != nil {
panic(fmt.Errorf("unable to set CCXT-rest URL to '%s': %s", *rootCcxtRestURL, e))
}
}
log.Printf("using ccxtRestUrl: %s\n", *rootCcxtRestURL)
apiTestNet := &horizonclient.Client{
HorizonURL: horizonTestnetURI,
HTTP: http.DefaultClient,
}
apiPubNet := &horizonclient.Client{
HorizonURL: horizonPubnetURI,
HTTP: http.DefaultClient,
}
if !*options.noHeaders {
apiTestNet.AppName = "kelp-ui"
apiTestNet.AppVersion = version
apiPubNet.AppName = "kelp-ui"
apiPubNet.AppVersion = version
p := prefs.Make(prefsFilename)
if p.FirstTime() {
log.Printf("Kelp sets the `X-App-Name` and `X-App-Version` headers on requests made to Horizon. These headers help us track overall Kelp usage, so that we can learn about general usage patterns and adapt Kelp to be more useful in the future. These can be turned off using the `--no-headers` flag. See `kelp trade --help` for more information.\n")
e := p.SetNotFirstTime()
if e != nil {
log.Println("")
log.Printf("unable to create preferences file: %s", e)
// we can still proceed with this error
}
}
}
if isLocalDevMode {
log.Printf("not checking ccxt in local dev mode")
} else {
// we need to check twice because sometimes the ccxt process lingers between runs so we can get a false positive on the first check
e := checkIsCcxtUpTwice(*rootCcxtRestURL)
ccxtRunning := e == nil
log.Printf("checked if CCXT is already running, ccxtRunning = %v", ccxtRunning)
if !ccxtRunning {
// start ccxt before we make API server (which loads exchange list)
ccxtGoos := runtime.GOOS
if ccxtGoos == "windows" {
ccxtGoos = "linux"
}
ccxtDirPath := kos.GetDotKelpWorkingDir().Join(kelpCcxtPath)
ccxtFilenameNoExt := fmt.Sprintf("ccxt-rest_%s-x64", ccxtGoos)
filenameWithExt := fmt.Sprintf("%s.zip", ccxtFilenameNoExt)
ccxtDestDir := ccxtDirPath.Join(ccxtFilenameNoExt)
ccxtBinPath := ccxtDestDir.Join(ccxtBinaryName)
log.Printf("mkdir ccxtDirPath: %s ...", ccxtDirPath.AsString())
e := kos.Mkdir(ccxtDirPath)
if e != nil {
panic(fmt.Errorf("could not mkdir for ccxtDirPath: %s", e))
}
if runtime.GOOS == "windows" {
ccxtSourceDir := kos.GetBinDir().Join("ccxt").Join(ccxtFilenameNoExt)
e = copyCcxtFolder(kos, ccxtSourceDir, ccxtDestDir)
if e != nil {
panic(e)
}
} else {
ccxtBundledZipPath := kos.GetBinDir().Join("ccxt").Join(filenameWithExt)
ccxtZipDestPath := ccxtDirPath.Join(filenameWithExt)
e = copyOrDownloadCcxtBinary(kos, ccxtBundledZipPath, ccxtZipDestPath, filenameWithExt)
if e != nil {
panic(e)
}
unzipCcxtFile(kos, ccxtDirPath, ccxtBinPath, filenameWithExt)
}
e = runCcxtBinary(kos, ccxtBinPath)
if e != nil {
panic(e)
}
}
}
dataPath := kos.GetDotKelpWorkingDir().Join("bot_data")
botConfigsPath := dataPath.Join("configs")
botLogsPath := dataPath.Join("logs")
s, e := backend.MakeAPIServer(
kos,
botConfigsPath,
botLogsPath,
*options.horizonTestnetURI,
apiTestNet,
*options.horizonPubnetURI,
apiPubNet,
*rootCcxtRestURL,
*options.noHeaders,
quit,
)
if e != nil {
panic(e)
}
guiWebPath := kos.GetBinDir().Join("../gui/web")
if isLocalDevMode {
// the frontend app checks the REACT_APP_API_PORT variable to be set when serving
os.Setenv("REACT_APP_API_PORT", fmt.Sprintf("%d", *options.devAPIPort))
go runAPIServerDevBlocking(s, *options.port, *options.devAPIPort)
runWithYarn(kos, options, guiWebPath)
log.Printf("should not have reached here after running yarn")
return
}
options.devAPIPort = nil
// the frontend app checks the REACT_APP_API_PORT variable to be set when serving
os.Setenv("REACT_APP_API_PORT", fmt.Sprintf("%d", *options.port))
if isLocalMode {
generateStaticFiles(kos, guiWebPath)
}
r := chi.NewRouter()
setMiddleware(r)
backend.SetRoutes(r, s)
// gui.FS is automatically compiled based on whether this is a local or deployment build
gui.FileServer(r, "/", gui.FS)
portString := fmt.Sprintf(":%d", *options.port)
log.Printf("starting server on port %d\n", *options.port)
threadTracker := multithreading.MakeThreadTracker()
e = threadTracker.TriggerGoroutine(func(inputs []interface{}) {
if isLocalMode {
e1 := http.ListenAndServe(portString, r)
if e1 != nil {
log.Fatal(e1)
}
} else {
_ = http.ListenAndServe(portString, r)
}
}, nil)
if e != nil {
log.Fatal(e)
}
log.Printf("sleeping for %d seconds before showing the ready string indicator...\n", sleepNumSecondsBeforeReadyString)
time.Sleep(sleepNumSecondsBeforeReadyString * time.Second)
log.Printf("%s: %d\n", readyStringIndicator, *options.port)
openBrowserWg.Done()
threadTracker.Wait()
log.Printf("should not have reached here after starting the backend server")
}
}
func checkIsCcxtUpTwice(ccxtURL string) error {
e := isCcxtUp(ccxtURL)
if e != nil {
return fmt.Errorf("ccxt-rest was not running on first check: %s", e)
}
// tiny pause before second check
time.Sleep(100 * time.Millisecond)
e = isCcxtUp(ccxtURL)
if e != nil {
return fmt.Errorf("ccxt-rest was not running on second check: %s", e)
}
// return nil for no error when it is running
return nil
}
func setMiddleware(r *chi.Mux) {
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
}
func copyCcxtFolder(
kos *kelpos.KelpOS,
ccxtSourceDir *kelpos.OSPath,
ccxtDestDir *kelpos.OSPath,
) error {
log.Printf("copying ccxt directory from %s to location %s ...", ccxtSourceDir.AsString(), ccxtDestDir.AsString())
cpCmd := fmt.Sprintf("cp -a %s %s", ccxtSourceDir.Unix(), ccxtDestDir.Unix())
_, e := kos.Blocking("cp-ccxt", cpCmd)
if e != nil {
return fmt.Errorf("unable to copy ccxt directory from %s to %s: %s", ccxtSourceDir.AsString(), ccxtDestDir.AsString(), e)
}
log.Printf("... done copying ccxt from %s to location %s", ccxtSourceDir.AsString(), ccxtDestDir.AsString())
return nil
}
func copyOrDownloadCcxtBinary(
kos *kelpos.KelpOS,
ccxtBundledZipPath *kelpos.OSPath,
ccxtZipDestPath *kelpos.OSPath,
filenameWithExt string,
) error {
if _, e := os.Stat(ccxtZipDestPath.Native()); !os.IsNotExist(e) {
return nil
}
if _, e := os.Stat(ccxtBundledZipPath.Native()); !os.IsNotExist(e) {
log.Printf("copying ccxt from %s to location %s ...", ccxtBundledZipPath.Unix(), ccxtZipDestPath.Unix())
cpCmd := fmt.Sprintf("cp %s %s", ccxtBundledZipPath.Unix(), ccxtZipDestPath.Unix())
_, e = kos.Blocking("cp-ccxt", cpCmd)
if e != nil {
return fmt.Errorf("unable to copy ccxt zip file from %s to %s: %s", ccxtBundledZipPath.Unix(), ccxtZipDestPath.Unix(), e)
}
log.Printf("... done copying ccxt from %s to location %s", ccxtBundledZipPath.Unix(), ccxtZipDestPath.Unix())
return nil
}
log.Printf("did not find ccxt zip file at source %s, proceeding to download", ccxtBundledZipPath.Unix())
// else download
downloadURL := fmt.Sprintf("%s/%s", ccxtDownloadBaseURL, filenameWithExt)
log.Printf("download ccxt from %s to location: %s ...", downloadURL, ccxtZipDestPath.AsString())
e := networking.DownloadFileWithGrab(
downloadURL,
ccxtZipDestPath.Native(),
downloadCcxtUpdateIntervalLogMillis,
func(statusCode int, statusString string) {
log.Printf(" response_status = %s, code = %d\n", statusString, statusCode)
},
func(completedBytes float64, sizeBytes float64, speedBytesPerSec float64) {
log.Printf(" downloaded %.2f / %.2f MB (%.2f%%) at an average speed of %.2f MB/sec\n",
completedBytes,
sizeBytes,
100*(float64(completedBytes)/float64(sizeBytes)),
speedBytesPerSec,
)
},
func(filename string) {
log.Printf(" done\n")
log.Printf("... downloaded file from URL '%s' to destination '%s'\n", downloadURL, filename)
},
)
if e != nil {
return fmt.Errorf("could not download ccxt from '%s' to location '%s': %s", downloadURL, ccxtZipDestPath.AsString(), e)
}
return nil
}
func unzipCcxtFile(
kos *kelpos.KelpOS,
ccxtDir *kelpos.OSPath,
ccxtBinPath *kelpos.OSPath,
filenameWithExt string,
) {
if _, e := os.Stat(ccxtDir.Native()); !os.IsNotExist(e) {
if _, e := os.Stat(ccxtBinPath.Native()); !os.IsNotExist(e) {
return
}
}
log.Printf("unzipping file %s ... ", filenameWithExt)
zipCmd := fmt.Sprintf("cd %s && unzip %s", ccxtDir.Unix(), filenameWithExt)
_, e := kos.Blocking("zip", zipCmd)
if e != nil {
log.Fatal(errors.Wrap(e, fmt.Sprintf("unable to unzip file %s in directory %s", filenameWithExt, ccxtDir.AsString())))
}
log.Printf("done\n")
}
func runCcxtBinary(kos *kelpos.KelpOS, ccxtBinPath *kelpos.OSPath) error {
if _, e := os.Stat(ccxtBinPath.Native()); os.IsNotExist(e) {
return fmt.Errorf("path to ccxt binary (%s) does not exist", ccxtBinPath.AsString())
}
log.Printf("running binary %s", ccxtBinPath.AsString())
// TODO CCXT should be run at the port specified by rootCcxtRestURL, currently it will default to port 3000 even if the config file specifies otherwise
_, e := kos.Background("ccxt-rest", ccxtBinPath.Unix())
if e != nil {
log.Fatal(errors.Wrap(e, fmt.Sprintf("unable to run ccxt file at location %s", ccxtBinPath.AsString())))
}
log.Printf("waiting up to %d seconds for ccxt-rest to start up ...", ccxtWaitSeconds)
for i := 0; i < ccxtWaitSeconds; i++ {
e := isCcxtUp(*rootCcxtRestURL)
ccxtRunning := e == nil
if ccxtRunning {
log.Printf("done, waited for ~%d seconds before CCXT was running\n", i)
return nil
}
// wait
log.Printf("ccxt is not up, sleeping for 1 second (waited so far = %d seconds)\n", i)
time.Sleep(1 * time.Second)
}
return fmt.Errorf("waited for %d seconds but CCXT was still not running at URL %s", ccxtWaitSeconds, *rootCcxtRestURL)
}
func runAPIServerDevBlocking(s *backend.APIServer, frontendPort uint16, devAPIPort uint16) {
r := chi.NewRouter()
// Add CORS middleware around every request since both ports are different when running server in dev mode
r.Use(cors.New(cors.Options{
AllowedOrigins: []string{fmt.Sprintf("http://localhost:%d", frontendPort)},
}).Handler)
setMiddleware(r)
backend.SetRoutes(r, s)
portString := fmt.Sprintf(":%d", devAPIPort)
log.Printf("Serving API server on HTTP port: %d\n", devAPIPort)
e := http.ListenAndServe(portString, r)
log.Fatal(e)
}
func runWithYarn(kos *kelpos.KelpOS, options serverInputs, guiWebPath *kelpos.OSPath) {
// yarn requires the PORT variable to be set when serving
os.Setenv("PORT", fmt.Sprintf("%d", *options.port))
log.Printf("Serving frontend via yarn on HTTP port: %d\n", *options.port)
e := kos.StreamOutput(exec.Command("yarn", "--cwd", guiWebPath.Unix(), "start"))
if e != nil {
panic(e)
}
}
func generateStaticFiles(kos *kelpos.KelpOS, guiWebPath *kelpos.OSPath) {
log.Printf("generating contents of %s/build ...\n", guiWebPath.Unix())
e := kos.StreamOutput(exec.Command("yarn", "--cwd", guiWebPath.Unix(), "build"))
if e != nil {
panic(e)
}
log.Printf("... finished generating contents of %s/build\n", guiWebPath.Unix())
log.Println()
}
func writeTrayIcon(kos *kelpos.KelpOS, trayIconPath *kelpos.OSPath, assetsDirPath *kelpos.OSPath) error {
if _, e := os.Stat(trayIconPath.Native()); !os.IsNotExist(e) {
// file exists, don't write again
return nil
}
// requires icon to be in /resources folder
trayIconBytes, e := resourcesKelpIcon18xPngBytes()
if e != nil {
return errors.Wrap(e, "could not fetch tray icon image bytes")
}
img, _, e := image.Decode(bytes.NewReader(trayIconBytes))
if e != nil {
return errors.Wrap(e, "could not decode bytes as image data")
}
// create dir if not exists
if _, e := os.Stat(assetsDirPath.Native()); os.IsNotExist(e) {
log.Printf("mkdir assetsDirPath: %s ...", assetsDirPath.AsString())
e = kos.Mkdir(assetsDirPath)
if e != nil {
return errors.Wrap(e, "could not mkdir for assetsDirPath: "+assetsDirPath.AsString())
}
log.Printf("... made assetsDirPath (%s)", assetsDirPath.AsString())
}
trayIconFile, e := os.Create(trayIconPath.Native())
if e != nil {
return errors.Wrap(e, "could not create tray icon file")
}
defer trayIconFile.Close()
e = png.Encode(trayIconFile, img)
if e != nil {
return errors.Wrap(e, "could not write png encoded icon")
}
return nil
}
func openBrowser(url string, openBrowserWg *sync.WaitGroup) {
log.Printf("opening URL in native browser: %s", url)
openBrowserWg.Wait()
e := browser.OpenURL(url)
if e != nil {
log.Fatal(e)
}
}
func openElectron(trayIconPath *kelpos.OSPath, url string) {
log.Printf("opening URL in electron: %s", url)
quitMenuItemOption := &astilectron.MenuItemOptions{
Label: astilectron.PtrStr("Quit"),
Visible: astilectron.PtrBool(true),
Enabled: astilectron.PtrBool(true),
OnClick: astilectron.Listener(func(e astilectron.Event) (deleteListener bool) {
quit()
return false
}),
}
mainMenuItemOptions := []*astilectron.MenuItemOptions{
&astilectron.MenuItemOptions{
Label: astilectron.PtrStr("File"),
SubMenu: []*astilectron.MenuItemOptions{
&astilectron.MenuItemOptions{
Label: astilectron.PtrStr("Reload"),
Role: astilectron.MenuItemRoleReload,
},
quitMenuItemOption,
},
},
&astilectron.MenuItemOptions{
Label: astilectron.PtrStr("Edit"),
Role: astilectron.MenuItemRoleEditMenu,
},
}
e := bootstrap.Run(bootstrap.Options{
AstilectronOptions: astilectron.Options{
AppName: "Kelp",
AppIconDefaultPath: "resources/kelp-icon@2x.png",
AcceptTCPTimeout: time.Minute * 2,
},
Debug: true,
Windows: []*bootstrap.Window{&bootstrap.Window{
Homepage: url,
Options: &astilectron.WindowOptions{
Center: astilectron.PtrBool(true),
Width: astilectron.PtrInt(1280),
Height: astilectron.PtrInt(960),
Closable: astilectron.PtrBool(false),
},
}},
TrayOptions: &astilectron.TrayOptions{
Image: astilectron.PtrStr(trayIconPath.Native()),
},
TrayMenuOptions: []*astilectron.MenuItemOptions{
quitMenuItemOption,
},
MenuOptions: []*astilectron.MenuItemOptions{
&astilectron.MenuItemOptions{SubMenu: mainMenuItemOptions},
},
})
if e != nil {
log.Fatal(e)
}
quit()
}
func quit() {
log.Printf("quitting...")
os.Exit(0)
}
// startTailFileServer takes in anhtml file or a string and serves that on the root of a new url at localhost:port where port is the int returned
func startTailFileServer(tailFileHTML string) int {
r := chi.NewRouter()
r.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(tailFileHTML))
}))
listener, e := net.Listen("tcp", ":0")
if e != nil {
log.Fatal(e)
}
port := listener.Addr().(*net.TCPAddr).Port
log.Printf("starting server for tail file on port %d\n", port)
go func() {
panic(http.Serve(listener, r))
}()
return port
}
const windowsInitialFile = `<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Kelp GUI VERSION_PLACEHOLDER</title>
<script type="text/javascript">
if (typeof XMLHttpRequest == "undefined") {
// this is only for really ancient browsers
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.xmlHttp.6.0"); }
catch (e1) { }
try { return new ActiveXObject("Msxml2.xmlHttp.3.0"); }
catch (e2) { }
try { return new ActiveXObject("Msxml2.xmlHttp"); }
catch (e3) { }
throw new Error("This browser does not support xmlHttpRequest.");
};
}
var pingUrl = "PING_URL";
var redirectUrl = "REDIRECT_URL";
function checkServerOnline() {
var ajax = new XMLHttpRequest();
ajax.open("GET", pingUrl, true);
ajax.onreadystatechange = function () {
if ((ajax.readyState == 4) && (ajax.status == 200)) {
window.location.href = redirectUrl;
}
}
ajax.send(null);
}
</script>
</head>
<body onLoad='setInterval("checkServerOnline()", 1000);' bgcolor="#0D0208" text="#00FF41">
<div>
Loading the backend for Kelp.<br />
This will take a few minutes.<br />
<br />
You will be redirected automatically once loaded.<br />
<br />
Please be patient.<br />
</div>
</body>
</html>
`
const tailFileHTML = `<!-- taken from http://www.davejennifer.com/computerjunk/javascript/tail-dash-f.html with minor modifications -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Kelp GUI VERSION_PLACEHOLDER</title>
<style>
.button {
background-color: #003B00; /* Dark Green */
color: #00FF41;
border: 2px solid #00FF41;
padding: 15px 32px;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
}
</style>
<script type="text/javascript">
var lastByte = 0;
if (typeof XMLHttpRequest == "undefined") {
// this is only for really ancient browsers
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.xmlHttp.6.0"); }
catch (e1) { }
try { return new ActiveXObject("Msxml2.xmlHttp.3.0"); }
catch (e2) { }
try { return new ActiveXObject("Msxml2.xmlHttp"); }
catch (e3) { }
throw new Error("This browser does not support xmlHttpRequest.");
};
}
// Substitute the URL for your server log file here...
//
var url = "PLACEHOLDER_URL";
var visible = false;
function tailf() {
var ajax = new XMLHttpRequest();
ajax.open("POST", url, true);
if (lastByte == 0) {
// First request - get everything
} else {
//
// All subsequent requests - add the Range header
//
ajax.setRequestHeader("Range", "bytes=" + parseInt(lastByte) + "-");
}
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
// only the first request
lastByte = parseInt(ajax.getResponseHeader("Content-length"));
document.getElementById("thePlace").innerHTML = ajax.responseText;
if (visible) {
document.getElementById("theEnd").scrollIntoView();
}
} else if (ajax.status == 206) {
lastByte += parseInt(ajax.getResponseHeader("Content-length"));
document.getElementById("thePlace").innerHTML += ajax.responseText;
if (visible) {
document.getElementById("theEnd").scrollIntoView();
}
} else if (ajax.status == 416) {
// no new data, so do nothing
} else {
// Some error occurred - just display the status code and response
alert("Ajax status: " + ajax.status + "\n" + ajax.getAllResponseHeaders());
}
if (ajax.status == 200 || ajax.status == 206) {
if (ajax.responseText.includes("READY_STRING")) {
var redirectURL = "REDIRECT_URL";
var pingURL = "PING_URL";
document.getElementById("theEnd").innerHTML = "<br/><br/><b>redirecting to " + redirectURL + " ...</b><br/><br/>";
document.getElementById("theEnd").scrollIntoView();
// sleep for 2 seconds so the user sees that we are being redirected
setTimeout(() => {
var ajaxPing = new XMLHttpRequest();
ajaxPing.open("GET", pingURL, true);
ajaxPing.onreadystatechange = function () {
if ((ajaxPing.readyState == 4) && (ajaxPing.status == 200)) {
window.location.href = redirectURL;
}
}
ajaxPing.send(null);
}, 2000)
}
}
}// ready state 4
}//orsc function def
ajax.send(null);
}// function tailf
</script>
<script type="text/javascript">
function onInit() {
document.getElementById("overHood").style.visibility = "visible";
document.getElementById("underHood").style.visibility = "hidden";
}
function liftHood() {
document.getElementById("overHood").style.visibility = "hidden";
document.getElementById("underHood").style.visibility = "visible";
visible = true;
document.getElementById("theEnd").scrollIntoView();
}
</script>
</head>
<body onLoad='onInit(); tailf(); setInterval("tailf()", 250);' bgcolor="#0D0208" text="#00FF41">
<div>
<div id="overHood">
<center>
<button class="button" onclick='liftHood();'>Show Me What's Under The Hood</button>
</center>
</div>
<div id="underHood">
<pre id="thePlace"/>
</div>
<div id="theEnd"/>
</div>
</body>
</html>
`