-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·5175 lines (4700 loc) · 132 KB
/
Copy pathmain.go
File metadata and controls
executable file
·5175 lines (4700 loc) · 132 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
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textarea"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// Model represents the application state
type model struct {
screen string
cursor int
pasteArea textarea.Model
analysis string
configBuffer string // Raw JSON to save
currentName string // Name for the config
resolvedJSONPath string
savePath string
configs []ConfigInfo
selectedItem int
selectedConfigs map[int]bool
configDetail string
configDetailNote string
xrayBinaryPath string
xrayVersion string
xrayBinaryError string
// Manual SOCKS fields
socksStep int
socksIP textinput.Model
socksPort textinput.Model
socksUsername textinput.Model
socksPassword textinput.Model
jsonPathInput textinput.Model
subscriptionURL textinput.Model
settingsHTTPPort int
settingsSOCKSPort int
settingsPingTimeout int
settingsCursor int
settingsInput textinput.Model
settingsEditing bool
savedSubs []SubscriptionInfo
selectedSubIndex int
showSubsList bool
spinner spinner.Model
isLoading bool
loadingText string
loadingDone func(model) model
pinging bool
latencyTotal int
latencyDone int
latencyCh chan tea.Msg
scrollOffset int
termWidth int
termHeight int
filter string
showFilter bool
searchInput textinput.Model
showSearch bool
detecting bool
detectTotal int
detectDone int
detectCh chan tea.Msg
selectedRegion string
regionOrder []string
}
type ConfigInfo struct {
Name string
Path string
Active bool
Protocol string
Server string
Port int
Ping string
RealPing string
Region string
}
type SubscriptionInfo struct {
Name string `json:"name"`
URL string `json:"url"`
Date string `json:"date"`
}
type connectionResult struct {
success bool
message string
}
type vmessConfig struct {
ADD string `json:"add"`
AID int `json:"aid,string"`
Host string `json:"host"`
ID string `json:"id"`
NET string `json:"net"`
Path string `json:"path"`
Port int `json:"port"`
PS string `json:"ps"`
SCY string `json:"scy"`
TLS string `json:"tls"`
Type string `json:"type"`
V string `json:"v"`
}
type trojanConfig struct {
Password string `json:"password"`
Server string `json:"server"`
Port int `json:"port"`
Type string `json:"type,omitempty"`
Security string `json:"security,omitempty"`
SNI string `json:"sni,omitempty"`
Path string `json:"path,omitempty"`
Host string `json:"host,omitempty"`
Remark string `json:"ps,omitempty"`
}
type shadowsocksConfig struct {
Server string `json:"server"`
Port int `json:"port"`
Method string `json:"method"`
Password string `json:"password"`
Plugin string `json:"plugin,omitempty"`
Remark string `json:"ps,omitempty"`
}
type hysteria2Config struct {
Server string `json:"server"`
Port int `json:"port"`
Password string `json:"password"`
SNI string `json:"sni,omitempty"`
AllowInsecure bool `json:"allowInsecure,omitempty"`
Obfs string `json:"obfs,omitempty"`
ObfsPassword string `json:"obfsPassword,omitempty"`
Remark string `json:"ps,omitempty"`
}
type geoIPResult struct {
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Region string `json:"regionName"`
City string `json:"city"`
Query string `json:"query"`
Status string `json:"status"`
}
func detectRegion(server string) string {
if server == "Unknown" || server == "" || net.ParseIP(server) == nil {
return "Unknown"
}
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(fmt.Sprintf("http://ip-api.com/json/%s?fields=status,country,countryCode,regionName,city,query", server))
if err != nil {
return "Unknown"
}
defer resp.Body.Close()
var result geoIPResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || result.Status != "success" {
return "Unknown"
}
if result.City != "" && result.City != result.Country {
return fmt.Sprintf("%s, %s", result.City, result.CountryCode)
}
return result.CountryCode
}
func (m model) detectAllRegions() model {
client := &http.Client{Timeout: 5 * time.Second}
for i := range m.configs {
if m.configs[i].Server == "Unknown" || m.configs[i].Server == "" {
m.configs[i].Region = "Unknown"
continue
}
if net.ParseIP(m.configs[i].Server) == nil {
m.configs[i].Region = "Domain"
continue
}
resp, err := client.Get(fmt.Sprintf("http://ip-api.com/json/%s?fields=status,country,countryCode,regionName,city,query", m.configs[i].Server))
if err != nil {
m.configs[i].Region = "Unknown"
continue
}
var result geoIPResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || result.Status != "success" {
m.configs[i].Region = "Unknown"
resp.Body.Close()
continue
}
resp.Body.Close()
region := ""
if result.City != "" && result.City != result.Country {
region = fmt.Sprintf("%s, %s", result.City, result.CountryCode)
} else {
region = result.CountryCode
}
m.configs[i].Region = region
time.Sleep(100 * time.Millisecond)
}
sort.SliceStable(m.configs, func(i, j int) bool {
if m.configs[i].Region != m.configs[j].Region {
return m.configs[i].Region < m.configs[j].Region
}
return parsePingMs(m.configs[i].Ping) < parsePingMs(m.configs[j].Ping)
})
return m
}
// Catppuccin Jade Color Palette
var (
// Base colors
catppuccinBackground = "#1d1d1d"
catppuccinForeground = "#fff4d2"
catppuccinSelection = "#8ec07c"
catppuccinCursor = "#fff4d2"
catppuccinInactive = "#393939"
catppuccinGreen = "#8ec07c"
catppuccinYellow = "#d8a657"
catppuccinBlue = "#83a598"
catppuccinPink = "#d3869b"
catppuccinRed = "#FF4A4A"
)
// Styles with Catppuccin Jade colors
var (
titleStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color(catppuccinGreen)).
MarginBottom(1)
statusStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color(catppuccinGreen))
menuItemStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinForeground))
selectedItemStyle = lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color(catppuccinForeground)).
Background(lipgloss.Color(catppuccinInactive)).
Padding(0, 1)
inputStyle = lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color(catppuccinInactive)).
Padding(1)
successStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinGreen)).
Bold(true)
errorStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinRed)).
Bold(true)
// Additional Catppuccin Jade styles
accentStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinPink))
infoStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinBlue))
warningStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinYellow)).
Bold(true)
dimStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color(catppuccinInactive))
)
// ASCII Art
const xrayArt = `██╗ ██╗██████╗ █████╗ ██╗ ██╗
╚██╗██╔╝██╔══██╗██╔══██╗╚██╗ ██╔╝
╚███╔╝ ██████╔╝███████║ ╚████╔╝
██╔██╗ ██╔══██╗██╔══██║ ╚██╔╝
██╔╝ ██╗██║ ██║██║ ██║ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝`
func initialModel() model {
// Initialize textarea for paste config (multi-line)
ta := textarea.New()
ta.Placeholder = "Paste your proxy URL or JSON config here...\n\nSupports:\n• vless:// URLs\n• vmess:// URLs\n• trojan:// URLs\n• ss:// URLs (Shadowsocks)\n• hysteria2:// URLs\n• JSON configurations\n• Multi-line content"
ta.Focus()
ta.SetWidth(70)
ta.SetHeight(12)
ta.ShowLineNumbers = false
// Style the textarea with Catppuccin colors
ta.FocusedStyle.Base = ta.FocusedStyle.Base.BorderForeground(lipgloss.Color(catppuccinGreen))
ta.BlurredStyle.Base = ta.BlurredStyle.Base.BorderForeground(lipgloss.Color(catppuccinInactive))
// Initialize SOCKS textinputs
socksIP := textinput.New()
socksIP.Placeholder = "192.168.1.100"
socksIP.CharLimit = 15
socksIP.Width = 20
socksPort := textinput.New()
socksPort.Placeholder = "1080"
socksPort.CharLimit = 5
socksPort.Width = 10
socksUsername := textinput.New()
socksUsername.Placeholder = "username (optional)"
socksUsername.CharLimit = 50
socksUsername.Width = 30
socksPassword := textinput.New()
socksPassword.Placeholder = "password (optional)"
socksPassword.EchoMode = textinput.EchoPassword
socksPassword.CharLimit = 50
socksPassword.Width = 30
jsonPathInput := textinput.New()
jsonPathInput.Placeholder = "/path/to/config.json"
jsonPathInput.CharLimit = 512
jsonPathInput.Width = 60
subscriptionURL := textinput.New()
subscriptionURL.Placeholder = "https://example.com/subscription"
subscriptionURL.CharLimit = 512
subscriptionURL.Width = 60
searchInput := textinput.New()
searchInput.Placeholder = "Search configs by name, server, or protocol..."
searchInput.CharLimit = 100
searchInput.Width = 60
settingsInput := textinput.New()
settingsInput.CharLimit = 10
settingsInput.Width = 15
spin := spinner.New()
spin.Spinner = spinner.Dot
spin.Style = accentStyle
return model{
screen: "main",
pasteArea: ta,
socksIP: socksIP,
socksPort: socksPort,
socksUsername: socksUsername,
socksPassword: socksPassword,
jsonPathInput: jsonPathInput,
subscriptionURL: subscriptionURL,
searchInput: searchInput,
settingsInput: settingsInput,
settingsHTTPPort: loadSettingsInt("http_port", 10808),
settingsSOCKSPort: loadSettingsInt("socks_port", 10809),
settingsPingTimeout: loadSettingsInt("ping_timeout", 8),
savedSubs: loadSubscriptions(),
selectedSubIndex: 0,
showSubsList: false,
spinner: spin,
savePath: filepath.Join(os.Getenv("HOME"), ".config", "xray", "config.json"),
configs: loadConfigs(),
selectedConfigs: map[int]bool{},
filter: "all",
}
}
func (m model) Init() tea.Cmd { // Remove pointer receiver
return tea.Batch(textarea.Blink, m.startLoading("Starting...", 350*time.Millisecond, func(next model) model {
next = populateXrayInfo(next)
next = next.applyResponsiveLayout()
return next
}, false))
}
type startLoadingMsg struct {
text string
duration time.Duration
apply func(model) model
quit bool
}
type loadingFinished struct {
apply func(model) model
quit bool
}
type latencyStarted struct {
total int
configs []ConfigInfo
indices []int // nil = ping all configs
timeout time.Duration
isTCP bool
}
type latencyResult struct {
server string
port int
ping string
isReal bool
}
type latencyFinished struct{}
type regionDetectionStarted struct {
total int
}
type regionDetected struct {
index int
region string
}
type regionDetectionFinished struct{}
type shellSessionEnded struct {
config string
}
func (m model) startLoading(text string, duration time.Duration, apply func(model) model, quit bool) tea.Cmd {
return func() tea.Msg {
return startLoadingMsg{text: text, duration: duration, apply: apply, quit: quit}
}
}
func (m model) readLatencyResult() tea.Cmd {
return func() tea.Msg {
msg, ok := <-m.latencyCh
if !ok {
return latencyFinished{}
}
return msg
}
}
func (m model) readRegionResult() tea.Cmd {
return func() tea.Msg {
msg, ok := <-m.detectCh
if !ok {
return regionDetectionFinished{}
}
return msg
}
}
func runRegionDetection(configs []ConfigInfo, ch chan<- tea.Msg) {
defer close(ch)
client := &http.Client{Timeout: 5 * time.Second}
for i := range configs {
region := "Unknown"
if configs[i].Server != "Unknown" && configs[i].Server != "" && net.ParseIP(configs[i].Server) != nil {
resp, err := client.Get(fmt.Sprintf("http://ip-api.com/json/%s?fields=status,country,countryCode,regionName,city,query", configs[i].Server))
if err == nil {
var result geoIPResult
if err := json.NewDecoder(resp.Body).Decode(&result); err == nil && result.Status == "success" {
if result.City != "" && result.City != result.Country {
region = fmt.Sprintf("%s, %s", result.City, result.CountryCode)
} else {
region = result.CountryCode
}
}
resp.Body.Close()
}
} else if configs[i].Server != "Unknown" && configs[i].Server != "" {
region = "Domain"
}
ch <- regionDetected{index: i, region: region}
time.Sleep(100 * time.Millisecond)
}
}
func runLatencyWorkers(configs []ConfigInfo, ch chan<- tea.Msg, indices []int, timeout time.Duration) {
defer close(ch)
binary, err := findXrayBinary()
if err != nil {
pingFrom := indices
if pingFrom == nil {
pingFrom = make([]int, len(configs))
for i := range configs {
pingFrom[i] = i
}
}
for _, idx := range pingFrom {
ch <- latencyResult{server: configs[idx].Server, port: configs[idx].Port, ping: "ERR", isReal: true}
}
return
}
const wCount = 10
jobs := make(chan struct {
idx int
server string
port int
})
var wg sync.WaitGroup
for i := 0; i < wCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
latency, err := runXrayLatency(binary, configs[job.idx].Path, timeout, job.server, job.port)
ping := "ERR"
if err == nil {
ping = latency
}
ch <- latencyResult{server: job.server, port: job.port, ping: ping, isReal: true}
}
}()
}
go func() {
pingFrom := indices
if pingFrom == nil {
pingFrom = make([]int, len(configs))
for i := range configs {
pingFrom[i] = i
}
}
for _, idx := range pingFrom {
jobs <- struct {
idx int
server string
port int
}{idx: idx, server: configs[idx].Server, port: configs[idx].Port}
}
close(jobs)
}()
wg.Wait()
}
func runTCPPingWorkers(configs []ConfigInfo, ch chan<- tea.Msg, indices []int, timeout time.Duration) {
defer close(ch)
pingFrom := indices
if pingFrom == nil {
pingFrom = make([]int, len(configs))
for i := range configs {
pingFrom[i] = i
}
}
const wCount = 20
jobs := make(chan struct {
idx int
server string
port int
})
var wg sync.WaitGroup
for i := 0; i < wCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
ping := "ERR"
latency, err := tcpPingLatency(job.server, job.port, timeout)
if err == nil {
ping = latency
}
ch <- latencyResult{server: job.server, port: job.port, ping: ping, isReal: false}
}
}()
}
for _, idx := range pingFrom {
jobs <- struct {
idx int
server string
port int
}{idx: idx, server: configs[idx].Server, port: configs[idx].Port}
}
close(jobs)
wg.Wait()
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Remove pointer receiver
switch msg := msg.(type) {
case connectionResult:
if msg.success {
m.analysis = successStyle.Render(msg.message)
} else {
m.analysis = errorStyle.Render(msg.message)
}
return m, nil
case startLoadingMsg:
m.isLoading = true
m.loadingText = msg.text
m.loadingDone = msg.apply
return m, tea.Batch(m.spinner.Tick, tea.Tick(msg.duration, func(time.Time) tea.Msg {
return loadingFinished{apply: msg.apply, quit: msg.quit}
}))
case loadingFinished:
m.isLoading = false
m.loadingText = ""
if msg.apply != nil {
m = msg.apply(m)
}
m.loadingDone = nil
if msg.quit {
return m, tea.Quit
}
return m, nil
case latencyStarted:
m.pinging = true
m.latencyTotal = msg.total
m.latencyDone = 0
m.analysis = fmt.Sprintf("Pinging %d configs... [0/%d]", msg.total, msg.total)
m.latencyCh = make(chan tea.Msg, msg.total)
if msg.isTCP {
go runTCPPingWorkers(msg.configs, m.latencyCh, msg.indices, msg.timeout)
} else {
go runLatencyWorkers(msg.configs, m.latencyCh, msg.indices, msg.timeout)
}
return m, m.readLatencyResult()
case latencyResult:
// Find config by server:port
found := false
for i := range m.configs {
if m.configs[i].Server == msg.server && m.configs[i].Port == msg.port {
if msg.isReal {
m.configs[i].RealPing = msg.ping
} else {
m.configs[i].Ping = msg.ping
}
found = true
break
}
}
if !found {
return m, nil
}
if m.latencyCh != nil {
m.latencyDone++
m.analysis = fmt.Sprintf("Pinging... [%d/%d]", m.latencyDone, m.latencyTotal)
return m, m.readLatencyResult()
}
pingType := "TCP"
if msg.isReal {
pingType = "Real"
}
m.analysis = fmt.Sprintf("✅ %s Ping: %s — %s:%d", pingType, msg.ping, msg.server, msg.port)
// Save single ping result
cache := loadPingCache()
key := fmt.Sprintf("%s:%d", msg.server, msg.port)
if msg.isReal {
key += ":real"
}
cache[key] = msg.ping
savePingCache(cache)
return m, nil
case latencyFinished:
m.pinging = false
cache := loadPingCache()
for _, cfg := range m.configs {
if cfg.Ping != "" {
cache[fmt.Sprintf("%s:%d", cfg.Server, cfg.Port)] = cfg.Ping
}
if cfg.RealPing != "" {
cache[fmt.Sprintf("%s:%d:real", cfg.Server, cfg.Port)] = cfg.RealPing
}
}
savePingCache(cache)
if m.latencyTotal > 0 {
m.analysis = fmt.Sprintf("✅ Ping completed (%d configs)", m.latencyTotal)
}
m.latencyTotal = 0
m.latencyDone = 0
return m, nil
case regionDetectionStarted:
m.detecting = true
m.detectTotal = msg.total
m.detectDone = 0
m.detectCh = make(chan tea.Msg, msg.total)
go runRegionDetection(m.configs, m.detectCh)
return m, tea.Batch(m.spinner.Tick, m.readRegionResult())
case regionDetected:
if msg.index >= 0 && msg.index < len(m.configs) {
m.configs[msg.index].Region = msg.region
}
if m.detectCh != nil {
m.detectDone++
return m, m.readRegionResult()
}
return m, nil
case regionDetectionFinished:
m.detecting = false
m.detectTotal = 0
m.detectDone = 0
m.detectCh = nil
// Save region cache
cache := loadRegionCache()
for _, cfg := range m.configs {
if cfg.Region != "" {
key := fmt.Sprintf("%s:%d", cfg.Server, cfg.Port)
cache[key] = cfg.Region
}
}
saveRegionCache(cache)
// Sort by region after all detected
sort.SliceStable(m.configs, func(i, j int) bool {
if m.configs[i].Region != m.configs[j].Region {
return m.configs[i].Region < m.configs[j].Region
}
return parsePingMs(m.configs[i].Ping) < parsePingMs(m.configs[j].Ping)
})
return m, nil
case shellSessionEnded:
m.analysis = successStyle.Render(fmt.Sprintf("✅ Shell proxy session ended. (%s)", msg.config))
return m, nil
case spinner.TickMsg:
if m.isLoading || m.detecting {
var cmd tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
}
return m, nil
case tea.WindowSizeMsg:
m.termWidth = msg.Width
m.termHeight = msg.Height
m = m.applyResponsiveLayout()
return m, nil
case tea.MouseMsg:
if m.isLoading || m.pinging {
return m, nil
}
if m.screen != "connectServer" && m.screen != "serverRegions" {
return m, nil
}
if msg.Action != tea.MouseActionPress {
return m, nil
}
switch msg.Button {
case tea.MouseButtonWheelUp:
if m.selectedItem > 0 {
m.selectedItem--
m.ensureVisible()
}
case tea.MouseButtonWheelDown:
if m.screen == "connectServer" {
flen := len(m.filteredConfigs())
if m.selectedItem < flen-1 {
m.selectedItem++
m.ensureVisible()
}
} else if m.screen == "serverRegions" {
flen := len(m.filteredRegionConfigs())
if m.selectedItem < flen-1 {
m.selectedItem++
m.ensureVisible()
}
}
case tea.MouseButtonLeft:
if m.screen == "serverRegions" {
clickX := msg.X
clickY := msg.Y
// Estimate region tab position: ~2 lines for border+padding + 3 for title + 2 for search+blank = ~7 from box start
// Box starts after header art (~6) + status bar (~3) + newlines (~3) = ~12
headerLines := 12
tabY := headerLines + 7
tabEndY := tabY + 1
if clickY >= tabY && clickY < tabEndY {
regions := m.filteredRegionOrder()
if len(regions) == 0 {
break
}
// Measure X offset for the box: centered, ~2 chars border + 2 padding
boxStartX := 2
// Skip " " prefix before region tabs
tabTextX := boxStartX + 2
relX := clickX - tabTextX
if relX < 0 {
relX = 0
}
// Each region entry: " │ [RegionName]" or " [RegionName]"
// Rough mapping: accumulate widths
cumX := 0
for i, r := range regions {
entryLen := len(r) + 4 // " [" + r + "] " or " " + r + " │ "
if i > 0 {
entryLen += 3 // " │ "
}
cumX += entryLen
if relX < cumX {
m.selectedRegion = r
m.selectedItem = 0
m.scrollOffset = 0
break
}
}
break
}
// Click on config item
visibleCfgs := m.filteredRegionConfigs()
total := len(visibleCfgs)
if total == 0 {
break
}
// Configs start after tabs + blank line + box padding
cfgStartY := tabEndY + 1
cfgEndY := cfgStartY + total
if clickY >= cfgStartY && clickY < cfgEndY {
idx := clickY - cfgStartY
if idx >= 0 && idx < total {
m.selectedItem = idx
m.ensureVisible()
}
}
break
}
// connectServer mouse handling
visible, offset, total := m.visibleConfigs()
if total == 0 {
break
}
bottomMargin := 7
listStartY := m.termHeight - len(visible) - bottomMargin
listEndY := listStartY + len(visible)
if msg.Y >= listStartY && msg.Y < listEndY {
idx := offset + (msg.Y - listStartY)
if idx >= 0 && idx < total {
m.selectedItem = idx
m.ensureVisible()
}
} else if msg.Y == listEndY+1 {
barWidth := m.termWidth - 30
if barWidth < 10 {
barWidth = 10
}
clickX := msg.X - 6
if clickX < 0 {
clickX = 0
}
if clickX > barWidth {
clickX = barWidth
}
pct := float64(clickX) / float64(barWidth)
target := int(pct * float64(total))
if target >= total {
target = total - 1
}
if target < 0 {
target = 0
}
m.selectedItem = target
m.ensureVisible()
}
}
return m, nil
case tea.KeyMsg:
if msg.String() == "ctrl+c" {
return m, tea.Quit
}
if m.isLoading {
return m, nil
}
switch m.screen {
case "main":
return m.updateMain(msg)
case "connectServer":
return m.updateConnectServer(msg)
case "addConfig":
return m.updateAddConfig(msg)
case "pasteConfig":
return m.updatePasteConfig(msg)
case "manualSocks":
return m.updateManualSocks(msg)
case "jsonFile":
return m.updateJSONFile(msg)
case "configDetails":
return m.updateConfigDetails(msg)
case "subscriptions":
return m.updateSubscriptions(msg)
case "settings":
return m.updateSettings(msg)
case "confirmDeleteSelected":
return m.updateConfirmDelete(msg, false)
case "confirmDeleteAll":
return m.updateConfirmDelete(msg, true)
case "ipChanger":
return m.updateIPChanger(msg)
case "xrayInfo":
return m.updateXrayInfo(msg)
case "serverRegions":
return m.updateServerRegions(msg)
}
}
return m, nil
}
func (m model) updateMain(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "q", "ctrl+c", "esc":
return m, m.startLoading("Closing...", 350*time.Millisecond, nil, true)
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < 7 {
m.cursor++
}
case "enter", " ":
switch m.cursor {
case 0:
m.screen = "connectServer"
m.cursor = 0
m.selectedConfigs = map[int]bool{}
m.configs = loadConfigs()
m.selectedItem = len(m.configs) - 1
if m.selectedItem < 0 {
m.selectedItem = 0
}
if len(m.configs) > 0 {
cfgs := make([]ConfigInfo, len(m.configs))
copy(cfgs, m.configs)
timeout := time.Duration(m.settingsPingTimeout) * time.Second
return m, func() tea.Msg {
return latencyStarted{total: len(cfgs), configs: cfgs, indices: nil, timeout: timeout, isTCP: true}
}
}
case 1:
m.screen = "addConfig"
m.cursor = 0
case 2:
m.screen = "subscriptions"
m.cursor = 0
m.subscriptionURL.Reset()
m.subscriptionURL.Focus()
m.analysis = ""
case 3:
m.screen = "settings"
m.cursor = 0
m.analysis = ""
case 4:
m.screen = "ipChanger"
m.cursor = 0
case 5:
m.screen = "xrayInfo"
m.cursor = 0
case 6:
m.screen = "serverRegions"
m.cursor = 0
m.selectedItem = 0
m.selectedRegion = ""
m.selectedConfigs = map[int]bool{}
m.configs = loadConfigs()
// Check if any configs still need detection
needsDetect := false
for _, cfg := range m.configs {
if cfg.Region == "" && cfg.Server != "Unknown" && cfg.Server != "" {
needsDetect = true
break
}
}
if needsDetect {
return m, func() tea.Msg {
return regionDetectionStarted{total: len(m.configs)}
}
}
return m, nil
case 7:
return m, tea.Quit
}
}
return m, nil
}
func (m model) updateAddConfig(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "esc":
m.screen = "main"
m.cursor = 1
case "up", "k":
if m.cursor > 0 {
m.cursor--
}
case "down", "j":
if m.cursor < 3 {
m.cursor++
}
case "enter", " ":
switch m.cursor {
case 0: