-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremote_api.go
More file actions
1805 lines (1529 loc) · 53.8 KB
/
Copy pathremote_api.go
File metadata and controls
1805 lines (1529 loc) · 53.8 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 (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"sort"
"strings"
"sync"
"time"
)
// =============================================================================
// CLIENTE DA API REMOTA (VPS)
// =============================================================================
// Constantes de criptografia
const (
NonceSize = 12 // 96 bits = 12 bytes
ProtocolVersion = 1
)
// RemoteAPIClient cliente para comunicação com o servidor na VPS
type RemoteAPIClient struct {
serverURL string
key []byte
gcm cipher.AEAD
clientID string
httpClient *http.Client
mu sync.Mutex
}
// RequestPayload payload de requisição
type RequestPayload struct {
Action string `json:"action"`
Payload map[string]interface{} `json:"payload,omitempty"`
ClientID string `json:"client_id,omitempty"`
Timestamp int64 `json:"timestamp"`
}
// ResponsePayload payload de resposta
type ResponsePayload struct {
Status string `json:"status"`
Data map[string]interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Timestamp int64 `json:"timestamp"`
}
// EncryptedEnvelope envelope criptografado
// IMPORTANTE: O campo Data contém NONCE + CIPHERTEXT em Base64
type EncryptedEnvelope struct {
Data string `json:"data"`
Version int `json:"version"`
Signature string `json:"signature,omitempty"`
}
// RemoteAnimeInfo informações de anime da API remota
type RemoteAnimeInfo struct {
ID int64 `json:"id"`
MalID int64 `json:"mal_id,omitempty"`
Title string `json:"title"`
TitleEN string `json:"title_en,omitempty"`
CoverImage string `json:"cover_image,omitempty"`
Episodes int `json:"episodes"`
Status string `json:"status"`
Source string `json:"source"`
}
// RemoteEpisodeInfo informações de episódio da API remota
type RemoteEpisodeInfo struct {
ID int64 `json:"id"`
AnimeID int64 `json:"anime_id"`
Number int `json:"number"`
Title string `json:"title,omitempty"`
GoFileID string `json:"gofile_id,omitempty"`
TorBoxID string `json:"torbox_id,omitempty"`
MagnetLink string `json:"magnet_link,omitempty"`
Quality string `json:"quality,omitempty"`
HasPTBR bool `json:"has_ptbr"`
}
// RemoteTorrentResult resultado de busca de torrent
type RemoteTorrentResult struct {
Title string `json:"title"`
Name string `json:"name,omitempty"` // Nome real do torrent (se disponível)
RawTitle string `json:"raw_title,omitempty"` // raw_title da API TorBox
Magnet string `json:"magnet,omitempty"`
Hash string `json:"hash"`
Size string `json:"size"`
Seeds int `json:"seeds"`
Leeches int `json:"leeches"`
Source string `json:"source"`
PageURL string `json:"page_url,omitempty"`
IsBrazilian bool `json:"is_brazilian"`
// Campos para agrupamento
CleanTitle string `json:"clean_title,omitempty"` // Título limpo para buscar imagem
Variants []RemoteTorrentResult `json:"variants,omitempty"` // Variantes agrupadas (temporadas, etc)
}
// extractNameFromMagnet extrai o nome do torrent do magnet link (parâmetro dn=)
func extractNameFromMagnet(magnet string) string {
if magnet == "" {
return ""
}
// Primeiro, converte HTML entities para caracteres normais
magnet = strings.ReplaceAll(magnet, "&", "&")
// Procura por dn= no magnet link
dnStart := strings.Index(magnet, "dn=")
if dnStart == -1 {
return ""
}
// Pula "dn="
dnStart += 3
// Encontra o fim do parâmetro (próximo &)
dnEnd := strings.Index(magnet[dnStart:], "&")
var encoded string
if dnEnd == -1 {
encoded = magnet[dnStart:]
} else {
encoded = magnet[dnStart : dnStart+dnEnd]
}
// URL decode
decoded, err := url.QueryUnescape(encoded)
if err != nil {
// Fallback manual
decoded = encoded
decoded = strings.ReplaceAll(decoded, "%20", " ")
decoded = strings.ReplaceAll(decoded, "%5B", "[")
decoded = strings.ReplaceAll(decoded, "%5D", "]")
decoded = strings.ReplaceAll(decoded, "%28", "(")
decoded = strings.ReplaceAll(decoded, "%29", ")")
decoded = strings.ReplaceAll(decoded, "%2B", "+")
}
return decoded
}
// isBatchOrComplete verifica se um torrent é um batch/completo
func isBatchOrComplete(title string) bool {
titleLower := strings.ToLower(title)
batchKeywords := []string{
"batch", "complete", "completo", "full", "all episodes",
"temporada completa", "season complete", "1-", "01-", "001-",
"intégrale", "integral", "[complete]", "(complete)",
}
for _, kw := range batchKeywords {
if strings.Contains(titleLower, kw) {
return true
}
}
// Verifica padrões como "001-220", "1-12", etc
if matched, _ := regexp.MatchString(`\d{1,3}\s*[-~]\s*\d{1,3}`, title); matched {
return true
}
return false
}
// extractCleanAnimeName extrai nome muito limpo para buscar imagem (mais agressivo)
// FOCO: agrupar "Naruto Clássico 1ª Temporada", "Naruto Clássico 2ª Temporada" -> "Naruto Clássico"
func extractCleanAnimeName(title string) string {
name := title
// 1. Substitui pontos por espaços PRIMEIRO (importante para "Naruto.Clássico.6ª.Temporada")
name = strings.ReplaceAll(name, ".", " ")
// 2. Remove TUDO entre colchetes, parênteses e chaves
name = regexp.MustCompile(`\[[^\]]*\]`).ReplaceAllString(name, " ")
name = regexp.MustCompile(`\([^)]*\)`).ReplaceAllString(name, " ")
name = regexp.MustCompile(`\{[^}]*\}`).ReplaceAllString(name, " ")
// 3. Remove HTML entities
name = regexp.MustCompile(`&[a-z]+;`).ReplaceAllString(name, "")
// 4. Remove padrões de temporada/episódio BRASILEIROS (ANTES de remover qualidade)
// "6ª Temporada", "1º Temporada", "2ª.Temporada", etc
name = regexp.MustCompile(`(?i)\d+[ªºa°]?\s*(temporada|temp)\b`).ReplaceAllString(name, "")
// "Temporada 6", "Season 2"
name = regexp.MustCompile(`(?i)(temporada|season|temp)\s*\d+`).ReplaceAllString(name, "")
// Ranges de episódios: "001-500", "1-92", "156-176"
name = regexp.MustCompile(`\d{1,3}\s*[-~]\s*\d{1,3}`).ReplaceAllString(name, "")
// Set patterns: "Set 12", "Set 18"
name = regexp.MustCompile(`(?i)set\s*\d+`).ReplaceAllString(name, "")
// Part patterns: "Part I", "Part 1"
name = regexp.MustCompile(`(?i)part\s*[ivx\d]+`).ReplaceAllString(name, "")
// v2, v3 etc
name = regexp.MustCompile(`(?i)\bv\d+\b`).ReplaceAllString(name, "")
// Batch
name = regexp.MustCompile(`(?i)\bbatch\b`).ReplaceAllString(name, "")
// Complete/Completo
name = regexp.MustCompile(`(?i)\b(complete|completo|completa)\b`).ReplaceAllString(name, "")
// Final
name = regexp.MustCompile(`(?i)\bfinal\b`).ReplaceAllString(name, "")
// 5. Remove qualidade e info técnica
name = regexp.MustCompile(`(?i)(720p|1080p|480p|2160p|4k|hevc|x265|x264|10bit|flac|aac|ac3|h264|h 264|hi10p)`).ReplaceAllString(name, "")
name = regexp.MustCompile(`(?i)(bd|dvd|webrip|bluray|blu-ray|remux|hdtv|web-dl|bdrip|dvdrip)`).ReplaceAllString(name, "")
name = regexp.MustCompile(`(?i)(dual\s*audio|dual-audio|multi\s*subs?|multiple\s*subs?|eng\s*sub|legendado|dublado)`).ReplaceAllString(name, "")
name = regexp.MustCompile(`(?i)(mkv|mp4|avi)`).ReplaceAllString(name, "")
// 6. Remove nomes de sites e release groups
name = regexp.MustCompile(`(?i)(baixar|torrent|download|filmes|beta|viatorrents|dosfilmes)`).ReplaceAllString(name, "")
name = regexp.MustCompile(`(?i)(comoeubaixo|torrentdosfilmes|filmestorrents)\s*com?`).ReplaceAllString(name, "")
name = regexp.MustCompile(`(?i)\b(d4v1|jysze|judas|almighty|uss)\b`).ReplaceAllString(name, "")
// 7. Remove anos
name = regexp.MustCompile(`\b(19|20)\d{2}\b`).ReplaceAllString(name, "")
// 8. Limpa caracteres especiais restantes no final
name = regexp.MustCompile(`[-_:+]+$`).ReplaceAllString(name, "")
name = regexp.MustCompile(`^[-_:+]+`).ReplaceAllString(name, "")
// 9. Limpa espaços múltiplos
name = regexp.MustCompile(`\s+`).ReplaceAllString(name, " ")
name = strings.TrimSpace(name)
// 10. Se ficou muito curto, tenta extrair as primeiras palavras
if len(name) < 3 {
words := strings.Fields(title)
var cleanWords []string
for _, w := range words {
w = strings.Trim(w, "[](){}.,-_")
if len(w) > 1 && !regexp.MustCompile(`^\d+$`).MatchString(w) {
cleanWords = append(cleanWords, w)
if len(cleanWords) >= 3 {
break
}
}
}
name = strings.Join(cleanWords, " ")
}
return name
}
// filterAndSortTorrents filtra e organiza os torrents
// MODO SIMPLIFICADO: Remove duplicatas e ordena por seeds, sem agrupar demais
func filterAndSortTorrents(results []RemoteTorrentResult) []RemoteTorrentResult {
if len(results) == 0 {
return results
}
seenHashes := make(map[string]bool)
var filtered []RemoteTorrentResult
for i := range results {
// Remove duplicatas por hash
hashLower := strings.ToLower(results[i].Hash)
if hashLower != "" && seenHashes[hashLower] {
continue
}
if hashLower != "" {
seenHashes[hashLower] = true
}
// Adiciona o CleanTitle para busca de imagem
results[i].CleanTitle = extractCleanAnimeName(results[i].Title)
filtered = append(filtered, results[i])
}
// Ordena: batches/complete primeiro, depois por seeds
sort.Slice(filtered, func(i, j int) bool {
isBatchI := isBatchOrComplete(filtered[i].Title)
isBatchJ := isBatchOrComplete(filtered[j].Title)
if isBatchI != isBatchJ {
return isBatchI // Batches vêm primeiro
}
return filtered[i].Seeds > filtered[j].Seeds
})
fmt.Printf("[RemoteAPI] Filtro: %d torrents únicos de %d originais\n", len(filtered), len(results))
return filtered
}
func formatBytesClient(bytes int64) string {
const unit = 1024
if bytes < unit {
return fmt.Sprintf("%d B", bytes)
}
div, exp := int64(unit), 0
for n := bytes / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}
// RemoteStreamLink link de streaming
type RemoteStreamLink struct {
DirectURL string `json:"direct_url"`
Filename string `json:"filename"`
Size int64 `json:"size"`
ContentType string `json:"content_type"`
ExpiresAt int64 `json:"expires_at,omitempty"`
}
// RemoteTorrentFile representa um arquivo dentro de um torrent
type RemoteTorrentFile struct {
ID int `json:"id"`
TorrentID int `json:"torrent_id,omitempty"` // ID do torrent pai (para TorBox)
Name string `json:"name"`
ShortName string `json:"short_name"`
Size int64 `json:"size"`
SizeStr string `json:"size_str"`
Episode int `json:"episode"`
Season int `json:"season"`
IsVideo bool `json:"is_video"`
}
// RemoteTorrentInfo informações de um torrent com seus arquivos
type RemoteTorrentInfo struct {
Hash string `json:"hash"`
Name string `json:"name"`
Size int64 `json:"size"`
SizeStr string `json:"size_str"`
Status string `json:"status"`
Progress float64 `json:"progress"`
Files []RemoteTorrentFile `json:"files"`
}
// Constantes de ações
const (
ActionSearch = "search"
ActionSearchBR = "search_br"
ActionSearchNyaa = "search_nyaa"
ActionGetMagnet = "get_magnet"
ActionGetLink = "get_link"
ActionGetFiles = "get_files"
ActionGetMediaInfo = "get_mediainfo"
ActionGetSubtitle = "get_subtitle"
ActionGetAnimes = "get_animes"
ActionGetEpisodes = "get_episodes"
ActionGetRecent = "get_recent"
ActionDeleteTorrent = "delete_torrent"
ActionListTorrents = "list_torrents"
)
var (
remoteClient *RemoteAPIClient
remoteClientOnce sync.Once
)
// InitRemoteAPI inicializa o cliente da API remota
func InitRemoteAPI(serverURL string) error {
var initErr error
remoteClientOnce.Do(func() {
// Chave compartilhada (mesma do servidor)
secretKey := "GoAnime-Super-Secret-Key-2024-AES256-GCM"
keyHash := sha256.Sum256([]byte(secretKey))
block, err := aes.NewCipher(keyHash[:])
if err != nil {
initErr = fmt.Errorf("erro ao criar cipher: %w", err)
return
}
gcm, err := cipher.NewGCM(block)
if err != nil {
initErr = fmt.Errorf("erro ao criar GCM: %w", err)
return
}
// Cliente HTTP otimizado com timeouts específicos
transport := &http.Transport{
MaxIdleConns: 20,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
ResponseHeaderTimeout: 30 * time.Second,
}
remoteClient = &RemoteAPIClient{
serverURL: serverURL,
key: keyHash[:],
gcm: gcm,
clientID: fmt.Sprintf("goanime-gui-%d", time.Now().UnixNano()),
httpClient: &http.Client{
Timeout: 45 * time.Second, // Timeout aumentado para buscas lentas
Transport: transport,
},
}
fmt.Printf("[RemoteAPI] Cliente inicializado: %s\n", serverURL)
})
return initErr
}
// encryptBytes criptografa dados com AES-256-GCM
// Retorna: nonce (12 bytes) + ciphertext concatenados
func (c *RemoteAPIClient) encryptBytes(plaintext []byte) ([]byte, error) {
// Gera nonce aleatório
nonce := make([]byte, NonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("erro ao gerar nonce: %w", err)
}
// Criptografa e prefixa o nonce ao ciphertext
ciphertext := c.gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
// decryptBytes descriptografa dados com AES-256-GCM
// Espera: nonce (12 bytes) + ciphertext concatenados
func (c *RemoteAPIClient) decryptBytes(ciphertext []byte) ([]byte, error) {
if len(ciphertext) < NonceSize {
return nil, fmt.Errorf("ciphertext muito curto")
}
// Extrai o nonce do início
nonce := ciphertext[:NonceSize]
encrypted := ciphertext[NonceSize:]
// Descriptografa
plaintext, err := c.gcm.Open(nil, nonce, encrypted, nil)
if err != nil {
return nil, fmt.Errorf("erro ao descriptografar: %w", err)
}
return plaintext, nil
}
// Call faz uma chamada à API remota com retry automático
func (c *RemoteAPIClient) Call(action string, payload map[string]interface{}) (*ResponsePayload, error) {
c.mu.Lock()
defer c.mu.Unlock()
// Tenta até 3 vezes com backoff
var lastErr error
for attempt := 1; attempt <= 3; attempt++ {
if attempt > 1 {
backoff := time.Duration(attempt) * 2 * time.Second
fmt.Printf("[RemoteAPI] Retry %d/3 para %s após %v\n", attempt, action, backoff)
time.Sleep(backoff)
}
resp, err := c.doCall(action, payload)
if err == nil {
return resp, nil
}
lastErr = err
// Se for erro de autenticação ou não encontrado, não retenta
errStr := err.Error()
if strings.Contains(errStr, "401") || strings.Contains(errStr, "403") ||
strings.Contains(errStr, "404") || strings.Contains(errStr, "invalid") {
break
}
fmt.Printf("[RemoteAPI] Tentativa %d falhou: %v\n", attempt, err)
}
return nil, lastErr
}
// doCall executa uma chamada à API (sem retry)
func (c *RemoteAPIClient) doCall(action string, payload map[string]interface{}) (*ResponsePayload, error) {
// Criar request
req := RequestPayload{
Action: action,
Payload: payload,
ClientID: c.clientID,
Timestamp: time.Now().Unix(),
}
// Serializar
jsonData, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("erro ao serializar request: %w", err)
}
// Criptografar (nonce + ciphertext concatenados)
encrypted, err := c.encryptBytes(jsonData)
if err != nil {
return nil, fmt.Errorf("erro ao criptografar: %w", err)
}
// Criar envelope (Data contém nonce+ciphertext em Base64)
envelope := EncryptedEnvelope{
Data: base64.StdEncoding.EncodeToString(encrypted),
Version: ProtocolVersion,
}
envJson, err := json.Marshal(envelope)
if err != nil {
return nil, fmt.Errorf("erro ao serializar envelope: %w", err)
}
// Enviar
resp, err := c.httpClient.Post(
c.serverURL+"/api/tunnel",
"application/json",
bytes.NewReader(envJson),
)
if err != nil {
return nil, fmt.Errorf("erro na requisição: %w", err)
}
defer resp.Body.Close()
// Ler resposta
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("erro ao ler resposta: %w", err)
}
// Verificar se é erro HTTP
if resp.StatusCode != 200 {
// Tenta decodificar erro JSON
var errResp map[string]interface{}
if json.Unmarshal(body, &errResp) == nil {
if errMsg, ok := errResp["error"].(string); ok {
return nil, fmt.Errorf("erro do servidor: %s", errMsg)
}
}
return nil, fmt.Errorf("erro HTTP %d: %s", resp.StatusCode, string(body))
}
// Decodificar envelope de resposta
var respEnv EncryptedEnvelope
if err := json.Unmarshal(body, &respEnv); err != nil {
return nil, fmt.Errorf("erro ao decodificar envelope: %w", err)
}
// Decodifica Base64
encryptedResp, err := base64.StdEncoding.DecodeString(respEnv.Data)
if err != nil {
return nil, fmt.Errorf("erro ao decodificar base64: %w", err)
}
// Descriptografar
plaintext, err := c.decryptBytes(encryptedResp)
if err != nil {
return nil, fmt.Errorf("erro ao descriptografar resposta: %w", err)
}
// Decodificar resposta
var response ResponsePayload
if err := json.Unmarshal(plaintext, &response); err != nil {
return nil, fmt.Errorf("erro ao decodificar resposta: %w", err)
}
return &response, nil
}
// CallWithTimeout faz uma chamada com timeout customizado (para operações longas)
func (c *RemoteAPIClient) CallWithTimeout(action string, payload map[string]interface{}, timeout time.Duration) (*ResponsePayload, error) {
c.mu.Lock()
defer c.mu.Unlock()
start := time.Now()
fmt.Printf("[RemoteAPI] CallWithTimeout: %s (timeout: %v)\n", action, timeout)
// Criar request
req := RequestPayload{
Action: action,
Payload: payload,
ClientID: c.clientID,
Timestamp: time.Now().Unix(),
}
// Serializar
jsonData, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("erro ao serializar request: %w", err)
}
// Criptografar
encrypted, err := c.encryptBytes(jsonData)
if err != nil {
return nil, fmt.Errorf("erro ao criptografar: %w", err)
}
// Criar envelope
envelope := EncryptedEnvelope{
Data: base64.StdEncoding.EncodeToString(encrypted),
Version: ProtocolVersion,
}
envJson, err := json.Marshal(envelope)
if err != nil {
return nil, fmt.Errorf("erro ao serializar envelope: %w", err)
}
// Cliente HTTP com timeout customizado
client := &http.Client{
Timeout: timeout,
Transport: &http.Transport{
MaxIdleConns: 10,
IdleConnTimeout: 30 * time.Second,
DisableCompression: false,
},
}
// Enviar
resp, err := client.Post(
c.serverURL+"/api/tunnel",
"application/json",
bytes.NewReader(envJson),
)
if err != nil {
return nil, fmt.Errorf("erro na requisição (timeout %v): %w", timeout, err)
}
defer resp.Body.Close()
// Ler resposta
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("erro ao ler resposta: %w", err)
}
// Verificar erro HTTP
if resp.StatusCode != 200 {
var errResp map[string]interface{}
if json.Unmarshal(body, &errResp) == nil {
if errMsg, ok := errResp["error"].(string); ok {
return nil, fmt.Errorf("erro do servidor: %s", errMsg)
}
}
return nil, fmt.Errorf("erro HTTP %d: %s", resp.StatusCode, string(body))
}
// Decodificar envelope
var respEnv EncryptedEnvelope
if err := json.Unmarshal(body, &respEnv); err != nil {
return nil, fmt.Errorf("erro ao decodificar envelope: %w", err)
}
// Base64 decode
encryptedResp, err := base64.StdEncoding.DecodeString(respEnv.Data)
if err != nil {
return nil, fmt.Errorf("erro ao decodificar base64: %w", err)
}
// Descriptografar
plaintext, err := c.decryptBytes(encryptedResp)
if err != nil {
return nil, fmt.Errorf("erro ao descriptografar: %w", err)
}
// Decodificar resposta
var response ResponsePayload
if err := json.Unmarshal(plaintext, &response); err != nil {
return nil, fmt.Errorf("erro ao decodificar resposta: %w", err)
}
fmt.Printf("[RemoteAPI] CallWithTimeout concluído em %v\n", time.Since(start))
return &response, nil
}
// =============================================================================
// SISTEMA DE JOBS ASSÍNCRONOS (para operações longas)
// =============================================================================
// JobStatus status de um job assíncrono
type JobStatus struct {
JobID string `json:"job_id"`
Status string `json:"status"` // "pending", "processing", "completed", "failed"
Result map[string]interface{} `json:"result,omitempty"`
Error string `json:"error,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// GetJobStatus consulta o status de um job assíncrono
func (c *RemoteAPIClient) GetJobStatus(jobID string) (*JobStatus, error) {
resp, err := c.Call("job_status", map[string]interface{}{
"job_id": jobID,
})
if err != nil {
return nil, err
}
if resp.Status != "success" {
return nil, fmt.Errorf("erro ao consultar job: %s", resp.Error)
}
status := &JobStatus{}
if jsonData, err := json.Marshal(resp.Data); err == nil {
if err := json.Unmarshal(jsonData, status); err != nil {
return nil, fmt.Errorf("erro ao decodificar status: %w", err)
}
}
return status, nil
}
// CallWithPolling faz uma chamada que pode retornar um job_id e faz polling até completar
// Ideal para operações como get_files que podem demorar muito
func (c *RemoteAPIClient) CallWithPolling(action string, payload map[string]interface{}, initialTimeout time.Duration, maxWait time.Duration) (*ResponsePayload, error) {
start := time.Now()
fmt.Printf("[RemoteAPI] CallWithPolling: %s (initial: %v, maxWait: %v)\n", action, initialTimeout, maxWait)
// Primeira tentativa com timeout inicial
resp, err := c.CallWithTimeout(action, payload, initialTimeout)
if err != nil {
return nil, err
}
// Verifica se retornou um job_id (processamento assíncrono)
if resp.Status == "success" {
if jobID, ok := resp.Data["job_id"].(string); ok && jobID != "" {
fmt.Printf("[RemoteAPI] Job assíncrono iniciado: %s\n", jobID)
// Faz polling até completar ou timeout
pollInterval := 2 * time.Second
for {
elapsed := time.Since(start)
if elapsed >= maxWait {
return nil, fmt.Errorf("timeout aguardando job %s (após %v)", jobID, elapsed)
}
time.Sleep(pollInterval)
jobStatus, err := c.GetJobStatus(jobID)
if err != nil {
fmt.Printf("[RemoteAPI] Erro ao consultar job: %v\n", err)
continue
}
fmt.Printf("[RemoteAPI] Job %s: status=%s\n", jobID, jobStatus.Status)
switch jobStatus.Status {
case "completed":
// Converte result para ResponsePayload
return &ResponsePayload{
Status: "success",
Data: jobStatus.Result,
}, nil
case "failed":
return nil, fmt.Errorf("job falhou: %s", jobStatus.Error)
case "pending", "processing":
// Continua polling
continue
default:
fmt.Printf("[RemoteAPI] Status desconhecido: %s\n", jobStatus.Status)
}
}
}
}
// Retorno direto (não foi assíncrono)
return resp, nil
}
// =============================================================================
// MÉTODOS EXPOSTOS PARA O FRONTEND (via Wails)
// =============================================================================
// RemoteSearchAnimes busca animes na API remota
func (a *App) RemoteSearchAnimes(query string) []RemoteAnimeInfo {
if remoteClient == nil {
fmt.Println("[RemoteAPI] Cliente não inicializado")
return nil
}
resp, err := remoteClient.Call(ActionSearch, map[string]interface{}{
"query": query,
})
if err != nil {
fmt.Printf("[RemoteAPI] Erro na busca: %v\n", err)
return nil
}
if resp.Status != "success" {
fmt.Printf("[RemoteAPI] Busca falhou: %s\n", resp.Error)
return nil
}
// Converter data para []RemoteAnimeInfo
results := []RemoteAnimeInfo{}
if data, ok := resp.Data["results"]; ok {
if jsonData, err := json.Marshal(data); err == nil {
if err := json.Unmarshal(jsonData, &results); err != nil {
fmt.Printf("[RemoteAPI] Erro ao decodificar animes: %v\n", err)
}
}
}
fmt.Printf("[RemoteAPI] Encontrados %d animes\n", len(results))
return results
}
// RemoteSearchTorrents busca torrents na API remota
func (a *App) RemoteSearchTorrents(query string, brOnly bool) []RemoteTorrentResult {
if remoteClient == nil {
fmt.Println("[RemoteAPI] Cliente não inicializado")
return nil
}
action := ActionSearch
if brOnly {
action = ActionSearchBR
}
resp, err := remoteClient.Call(action, map[string]interface{}{
"query": query,
})
if err != nil {
fmt.Printf("[RemoteAPI] Erro na busca de torrents: %v\n", err)
return nil
}
if resp.Status != "success" {
fmt.Printf("[RemoteAPI] Busca de torrents falhou: %s\n", resp.Error)
return nil
}
results := []RemoteTorrentResult{}
// DEBUG: Mostrar estrutura completa dos dados recebidos
if fullJson, err := json.MarshalIndent(resp.Data, "", " "); err == nil {
fmt.Printf("[RemoteAPI] Dados recebidos:\n%s\n", string(fullJson))
}
// O gateway retorna em "results" não em "torrents"
if data, ok := resp.Data["results"]; ok {
if jsonData, err := json.Marshal(data); err == nil {
fmt.Printf("[RemoteAPI] JSON dos resultados: %s\n", string(jsonData)[:min(len(jsonData), 2000)])
if err := json.Unmarshal(jsonData, &results); err != nil {
fmt.Printf("[RemoteAPI] Erro ao decodificar results: %v\n", err)
}
}
} else if data, ok := resp.Data["torrents"]; ok {
// Fallback para "torrents"
if jsonData, err := json.Marshal(data); err == nil {
if err := json.Unmarshal(jsonData, &results); err != nil {
fmt.Printf("[RemoteAPI] Erro ao decodificar torrents: %v\n", err)
}
}
}
// DEBUG: Mostrar primeiro resultado para verificar mapeamento
if len(results) > 0 {
fmt.Printf("[RemoteAPI] Primeiro resultado mapeado: Title=%s, Hash=%s, Size=%s\n",
results[0].Title, results[0].Hash, results[0].Size)
}
// Corrigir títulos: extrair nome real do magnet link se o título for apenas categoria
for i := range results {
// Se não tem magnet mas tem hash, construir o magnet
if results[i].Magnet == "" && results[i].Hash != "" {
results[i].Magnet = fmt.Sprintf("magnet:?xt=urn:btih:%s", results[i].Hash)
fmt.Printf("[RemoteAPI] Magnet construído do hash: %s\n", results[i].Magnet)
}
// Se o título parece ser apenas uma categoria (ex: "Anime - English-translated")
// ou está vazio, extrair do magnet
if results[i].Title == "" ||
strings.Contains(results[i].Title, " - ") && len(results[i].Title) < 40 ||
strings.HasPrefix(results[i].Title, "Anime") {
nameFromMagnet := extractNameFromMagnet(results[i].Magnet)
if nameFromMagnet != "" {
results[i].Title = nameFromMagnet
fmt.Printf("[RemoteAPI] Título extraído do magnet: %s\n", nameFromMagnet)
}
}
// Se tem Name ou RawTitle, usar esses
if results[i].Name != "" {
results[i].Title = results[i].Name
}
if results[i].RawTitle != "" && results[i].RawTitle != results[i].Title {
results[i].Title = results[i].RawTitle
}
// Limpar o campo Size que pode ter HTML
if strings.Contains(results[i].Size, "<") {
results[i].Size = "" // Limpa HTML do Size
}
// DEBUG: Mostra cada torrent processado
magnetPreview := results[i].Magnet
if len(magnetPreview) > 60 {
magnetPreview = magnetPreview[:60]
}
fmt.Printf("[RemoteAPI] Torrent[%d]: Title=%s, Hash=%s, Magnet=%s...\n", i, results[i].Title, results[i].Hash, magnetPreview)
}
// Filtra e organiza: batches primeiro, agrupa episódios únicos
results = filterAndSortTorrents(results)
fmt.Printf("[RemoteAPI] Retornando %d torrents após filtro\n", len(results))
return results
}
// RemoteGetStreamLink obtém link de streaming via Player VPS
// Usa endpoint /api/torbox/stream/{torrentId}/{fileId}
func (a *App) RemoteGetStreamLink(hash string, fileID int) *RemoteStreamLink {
return a.RemoteGetStreamLinkWithTorrent(hash, fileID, 0)
}
// RemoteGetStreamLinkWithTorrent obtém link de streaming usando torrentId diretamente
func (a *App) RemoteGetStreamLinkWithTorrent(hash string, fileID int, torrentID int) *RemoteStreamLink {
fmt.Printf("[RemoteAPI] GetStreamLink via Player - hash: %s, fileID: %d, torrentID: %d\n", hash, fileID, torrentID)
client := &http.Client{Timeout: 30 * time.Second}
// Se já temos o torrentID, pula a busca
if torrentID == 0 {
// Precisa buscar o torrentID pelo hash
apiURL := fmt.Sprintf("%s/api/torbox/instant?q=%s", VPSPlayerURL, url.QueryEscape(hash))
fmt.Printf("[RemoteAPI] Buscando torrent: %s\n", apiURL)
resp, err := client.Get(apiURL)
if err != nil {
fmt.Printf("[RemoteAPI] Erro na requisição: %v\n", err)
return nil
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("[RemoteAPI] Erro ao ler resposta: %v\n", err)
return nil
}
var playerResp struct {
Success bool `json:"success"`
TorrentID int `json:"torrent_id"`
}
if err := json.Unmarshal(body, &playerResp); err != nil {
fmt.Printf("[RemoteAPI] Erro ao decodificar: %v\n", err)
return nil
}
if !playerResp.Success || playerResp.TorrentID == 0 {
fmt.Printf("[RemoteAPI] Torrent não encontrado\n")
return nil
}
torrentID = playerResp.TorrentID
}
// Chama o endpoint de stream
streamURL := fmt.Sprintf("%s/api/torbox/stream/%d/%d", VPSPlayerURL, torrentID, fileID)
fmt.Printf("[RemoteAPI] Obtendo stream: %s\n", streamURL)
resp, err := client.Get(streamURL)
if err != nil {
fmt.Printf("[RemoteAPI] Erro ao obter stream: %v\n", err)
return nil
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("[RemoteAPI] Erro ao ler stream: %v\n", err)
return nil
}
var streamResp struct {
StreamURL string `json:"stream_url"`
Error string `json:"error,omitempty"`
}
if err := json.Unmarshal(body, &streamResp); err != nil {
fmt.Printf("[RemoteAPI] Erro ao decodificar stream: %v\n", err)
return nil
}
if streamResp.StreamURL == "" {
fmt.Printf("[RemoteAPI] Stream URL vazia: %s\n", streamResp.Error)
return nil
}
link := &RemoteStreamLink{
DirectURL: streamResp.StreamURL,
}
fmt.Printf("[RemoteAPI] Link obtido: %s\n", link.DirectURL)
return link
}
// RemoteGetTorrentFiles obtém lista de arquivos de um torrent via VPS Player
// Usa POST /api/torbox/add para adicionar o torrent e obter lista de arquivos
func (a *App) RemoteGetTorrentFiles(magnet string, hash string) *RemoteTorrentInfo {
magnetPreview := magnet
if len(magnetPreview) > 50 {
magnetPreview = magnetPreview[:50]
}
fmt.Printf("[RemoteAPI] GetTorrentFiles via Player - magnet: %s..., hash: %s\n", magnetPreview, hash)