-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
5186 lines (4399 loc) · 147 KB
/
Copy pathapp.go
File metadata and controls
5186 lines (4399 loc) · 147 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 (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"GoAnimeGUI/internal/manga"
"GoAnimeGUI/pkg/anilist"
"GoAnimeGUI/pkg/animesflix"
"GoAnimeGUI/pkg/aniskip"
"GoAnimeGUI/pkg/consumet"
"GoAnimeGUI/pkg/discord"
"GoAnimeGUI/pkg/enime"
"GoAnimeGUI/pkg/gofilecloud"
"GoAnimeGUI/pkg/jikan"
"GoAnimeGUI/pkg/smartrouter"
"GoAnimeGUI/pkg/store"
"GoAnimeGUI/pkg/videoextractor"
"github.com/alvarorichard/Goanime/pkg/goanime"
"github.com/alvarorichard/Goanime/pkg/goanime/types"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// CacheEntry representa uma entrada de cache com TTL e validação
type CacheEntry struct {
Data interface{}
ExpiresAt time.Time
URL string // URL original para validação
LastValidAt time.Time // Última vez que a URL foi validada
FailCount int // Número de falhas consecutivas
Source string // Fonte do stream (AnimeFire, AllAnime, etc)
}
// IsExpired verifica se a entrada expirou
func (c *CacheEntry) IsExpired() bool {
return time.Now().After(c.ExpiresAt)
}
// NeedsValidation verifica se a URL precisa ser revalidada
// Valida a cada 2 minutos ou se houve falhas
func (c *CacheEntry) NeedsValidation() bool {
// Se expirou, precisa de novo fetch, não apenas validação
if c.IsExpired() {
return false
}
// Se nunca foi validado
if c.LastValidAt.IsZero() {
return true
}
// Se teve falhas recentes, valida mais frequentemente
validationInterval := 2 * time.Minute
if c.FailCount > 0 {
validationInterval = 30 * time.Second
}
return time.Since(c.LastValidAt) > validationInterval
}
// StreamCacheEntry é uma entrada de cache especÃfica para streams com mais metadados
type StreamCacheEntry struct {
URL string
Source string
Quality string
Referer string
ExpiresAt time.Time
LastValidAt time.Time
FailCount int
IsValidated bool
}
// SourceFailure rastreia falhas de fontes especÃficas
type SourceFailure struct {
Source string
FailedAt time.Time
FailCount int
LastError string
RetryAfter time.Time
}
// toTitleCase converte string para Title Case (substitui strings.Title deprecated)
func toTitleCase(s string) string {
words := strings.Fields(s)
for i, word := range words {
if len(word) > 0 {
words[i] = strings.ToUpper(string(word[0])) + strings.ToLower(word[1:])
}
}
return strings.Join(words, " ")
}
// PrefetchRequest representa um pedido de pré-carregamento de episódio
type PrefetchRequest struct {
AnimeURL string
EpisodeURL string
EpisodeNum int
}
// StreamResult representa o resultado de uma busca de stream
type StreamResult struct {
URL string
Source string
Error error
}
type App struct {
ctx context.Context
client *goanime.Client
animesflixClient *animesflix.Client
gofileClient *gofilecloud.Client
User *store.UserData
// Smart Router para fontes de vÃdeo
streamRouter *smartrouter.SmartRouter
// Cache unificado com TTL
cache map[string]*CacheEntry
cacheMutex sync.RWMutex
// Cache especÃficos de alta performance (sem TTL para itens crÃticos)
episodesCache map[string][]store.Episode
urlCache map[string]string
topAnimesCache []store.SavedAnime
trendingCache []*AniListAnime
// Cache inteligente de streams com validação
streamCache map[string]*StreamCacheEntry
streamCacheMutex sync.RWMutex
// Rastreamento de falhas por fonte
sourceFailures map[string]*SourceFailure
sourceFailuresMutex sync.RWMutex
// Prefetch de episódios (carrega próximos episódios em background)
prefetchQueue chan PrefetchRequest
prefetchActive map[string]bool
prefetchMutex sync.RWMutex
// Cache para imagens HD do AniList
hdImageCache map[string]*anilist.AnimeMedia
// Proxy de vÃdeo para contornar CORS
proxyServer *http.Server
proxyPort int
currentVideoURL string
proxyMutex sync.RWMutex
// Cache de imagens de mangá para carregamento rápido
imageCache map[string][]byte
imageCacheMutex sync.RWMutex
imageClient *http.Client
// Estado de inicialização
initialized bool
initMutex sync.RWMutex
// HTTP client para validação de URLs
validationClient *http.Client
// Cliente de Manga com cache e worker pool
mangaClient *manga.MangaClient
mangaCache *manga.MangaCache
mangaWorkerPool *manga.WorkerPool
mangaAggregator *manga.MangaAggregator // Agregador de múltiplas fontes
// Seeding Worker para contribuição comunitária
seedingWorker *SeedingWorker
}
// Cache TTLs
const (
CacheTTLSearch = 10 * time.Minute // Buscas
CacheTTLTrending = 30 * time.Minute // Trending
CacheTTLTop = 1 * time.Hour // Top animes
CacheTTLEpisodes = 1 * time.Hour // Episódios (aumentado para não perder dados)
CacheTTLStream = 10 * time.Minute // URLs de stream (aumentado)
)
func NewApp() *App {
app := &App{
cache: make(map[string]*CacheEntry),
episodesCache: make(map[string][]store.Episode),
urlCache: make(map[string]string),
hdImageCache: make(map[string]*anilist.AnimeMedia),
streamCache: make(map[string]*StreamCacheEntry),
sourceFailures: make(map[string]*SourceFailure),
imageCache: make(map[string][]byte),
imageClient: &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 50,
MaxIdleConnsPerHost: 20,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
},
},
validationClient: &http.Client{
Timeout: 3 * time.Second, // Reduzido para resposta mais rápida
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// Permite redirecionamentos normalmente
if len(via) >= 10 {
return fmt.Errorf("too many redirects")
}
return nil
},
},
prefetchQueue: make(chan PrefetchRequest, 10),
prefetchActive: make(map[string]bool),
}
// Inicializa o Smart Router com circuit breaker
app.streamRouter = smartrouter.New(smartrouter.Config{
CircuitThreshold: 3, // 3 falhas abre o circuit
CircuitResetTime: 30 * time.Second, // Tenta resetar após 30s
DefaultTimeout: 5 * time.Second,
})
// Adiciona fontes de streaming em ordem de prioridade
// Prioridade 1: Enime API (mais rápida, timeout curto)
app.streamRouter.AddSource(smartrouter.StreamSource{
Name: "Enime",
Priority: 1,
Timeout: 3 * time.Second, // Timeout curto para não travar
Fetcher: func(ctx context.Context, title string, ep int) (string, error) {
return enime.FindAndGetStreamWithContext(ctx, title, ep)
},
})
// Prioridade 2: Consumet API (fallback confiável)
app.streamRouter.AddSource(smartrouter.StreamSource{
Name: "Consumet",
Priority: 2,
Timeout: 5 * time.Second,
Fetcher: func(ctx context.Context, title string, ep int) (string, error) {
url, _, err := consumet.FindAnimeAndGetStream(title, ep)
return url, err
},
})
// Inicializa o cliente de Manga com cache e worker pool
app.mangaClient = manga.NewMangaClient()
app.mangaCache = manga.NewMangaCache()
app.mangaWorkerPool = manga.NewWorkerPool(app.mangaClient, app.mangaCache, 4) // 4 workers paralelos
app.mangaAggregator = manga.NewMangaAggregator() // Agregador com todas as fontes
return app
}
// getCache recupera um item do cache se não expirou
func (a *App) getCache(key string) (interface{}, bool) {
a.cacheMutex.RLock()
defer a.cacheMutex.RUnlock()
if entry, ok := a.cache[key]; ok && !entry.IsExpired() {
return entry.Data, true
}
return nil, false
}
// setCache armazena um item no cache com TTL
func (a *App) setCache(key string, data interface{}, ttl time.Duration) {
a.cacheMutex.Lock()
defer a.cacheMutex.Unlock()
a.cache[key] = &CacheEntry{
Data: data,
ExpiresAt: time.Now().Add(ttl),
}
}
// cleanExpiredCache limpa entradas expiradas (chamar periodicamente)
func (a *App) cleanExpiredCache() {
a.cacheMutex.Lock()
defer a.cacheMutex.Unlock()
count := 0
for key, entry := range a.cache {
if entry.IsExpired() {
delete(a.cache, key)
count++
}
}
if count > 0 {
fmt.Printf("[Cache] Limpou %d entradas expiradas\n", count)
}
}
// ClearEpisodesCache limpa o cache de episódios para forçar recarga
func (a *App) ClearEpisodesCache() {
a.cacheMutex.Lock()
defer a.cacheMutex.Unlock()
a.episodesCache = make(map[string][]store.Episode)
fmt.Println("[Cache] Cache de episódios limpo")
}
// ClearAllCache limpa todo o cache (útil para resolver problemas)
func (a *App) ClearAllCache() {
a.cacheMutex.Lock()
defer a.cacheMutex.Unlock()
a.cache = make(map[string]*CacheEntry)
a.episodesCache = make(map[string][]store.Episode)
a.urlCache = make(map[string]string)
// Limpa também o cache de streams e falhas
a.streamCacheMutex.Lock()
a.streamCache = make(map[string]*StreamCacheEntry)
a.streamCacheMutex.Unlock()
a.sourceFailuresMutex.Lock()
a.sourceFailures = make(map[string]*SourceFailure)
a.sourceFailuresMutex.Unlock()
fmt.Println("[Cache] Todo o cache foi limpo")
}
// === SISTEMA DE CACHE INTELIGENTE COM VALIDAÇÃO ===
// ValidateStreamURL verifica se uma URL de stream ainda é acessÃvel
// Usa HEAD request para ser rápido e não consumir banda
func (a *App) ValidateStreamURL(url string) (bool, error) {
if url == "" {
return false, fmt.Errorf("URL vazia")
}
fmt.Printf("[ValidateURL] Verificando: %s\n", url)
// Cria request HEAD (não baixa o conteúdo, só verifica headers)
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return false, err
}
// Configura headers baseado no tipo de URL
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
if strings.Contains(url, "lightspeedst.net") || strings.Contains(url, "animefire") {
req.Header.Set("Referer", "https://animefire.plus/")
req.Header.Set("Origin", "https://animefire.plus")
} else if strings.Contains(url, "sharepoint") || strings.Contains(url, "microsoft") {
req.Header.Set("Referer", "https://myanime.sharepoint.com/")
} else if strings.Contains(url, "allanime") || strings.Contains(url, "gogoanime") {
req.Header.Set("Referer", "https://allanime.to/")
}
resp, err := a.validationClient.Do(req)
if err != nil {
fmt.Printf("[ValidateURL] Erro na requisição: %v\n", err)
return false, err
}
defer resp.Body.Close()
// Status 2xx ou 3xx é válido
isValid := resp.StatusCode >= 200 && resp.StatusCode < 400
fmt.Printf("[ValidateURL] Status: %d, Válido: %v\n", resp.StatusCode, isValid)
return isValid, nil
}
// GetValidatedStreamCache obtém stream do cache, validando se ainda funciona
func (a *App) GetValidatedStreamCache(key string) (string, bool) {
a.streamCacheMutex.RLock()
entry, exists := a.streamCache[key]
a.streamCacheMutex.RUnlock()
if !exists {
return "", false
}
// Verifica se expirou
if time.Now().After(entry.ExpiresAt) {
fmt.Printf("[SmartCache] Cache expirado para: %s\n", key)
return "", false
}
// Verifica se precisa revalidar
if !entry.IsValidated || time.Since(entry.LastValidAt) > 2*time.Minute {
fmt.Printf("[SmartCache] Validando URL do cache: %s\n", entry.URL)
// Valida em goroutine para não bloquear, mas retorna o cache atual
go func(e *StreamCacheEntry, k string) {
valid, err := a.ValidateStreamURL(e.URL)
a.streamCacheMutex.Lock()
defer a.streamCacheMutex.Unlock()
if cached, ok := a.streamCache[k]; ok {
if valid {
cached.IsValidated = true
cached.LastValidAt = time.Now()
cached.FailCount = 0
fmt.Printf("[SmartCache] URL validada com sucesso: %s\n", cached.URL)
} else {
cached.FailCount++
fmt.Printf("[SmartCache] URL inválida (falha %d): %s - %v\n", cached.FailCount, cached.URL, err)
// Se falhou 3 vezes, remove do cache
if cached.FailCount >= 3 {
delete(a.streamCache, k)
a.recordSourceFailure(cached.Source, "URL inválida após múltiplas tentativas")
fmt.Printf("[SmartCache] Cache removido após 3 falhas: %s\n", k)
}
}
}
}(entry, key)
}
return entry.URL, true
}
// SetStreamCache armazena URL de stream no cache inteligente
func (a *App) SetStreamCache(key string, url string, source string, ttl time.Duration) {
a.streamCacheMutex.Lock()
defer a.streamCacheMutex.Unlock()
a.streamCache[key] = &StreamCacheEntry{
URL: url,
Source: source,
ExpiresAt: time.Now().Add(ttl),
LastValidAt: time.Now(),
IsValidated: true, // Assume válido no momento do cache
FailCount: 0,
}
fmt.Printf("[SmartCache] Stream cacheado: %s -> %s (source: %s)\n", key, url, source)
}
// InvalidateStreamCache invalida uma entrada especÃfica do cache de streams
func (a *App) InvalidateStreamCache(key string) {
a.streamCacheMutex.Lock()
defer a.streamCacheMutex.Unlock()
if entry, ok := a.streamCache[key]; ok {
a.recordSourceFailure(entry.Source, "Cache invalidado manualmente")
delete(a.streamCache, key)
fmt.Printf("[SmartCache] Cache invalidado: %s\n", key)
}
}
// recordSourceFailure registra falha de uma fonte
func (a *App) recordSourceFailure(source string, reason string) {
a.sourceFailuresMutex.Lock()
defer a.sourceFailuresMutex.Unlock()
if failure, exists := a.sourceFailures[source]; exists {
failure.FailCount++
failure.FailedAt = time.Now()
failure.LastError = reason
// Backoff exponencial: 30s, 1min, 2min, 5min, 10min
backoffMinutes := []time.Duration{30 * time.Second, 1 * time.Minute, 2 * time.Minute, 5 * time.Minute, 10 * time.Minute}
backoffIndex := failure.FailCount - 1
if backoffIndex >= len(backoffMinutes) {
backoffIndex = len(backoffMinutes) - 1
}
failure.RetryAfter = time.Now().Add(backoffMinutes[backoffIndex])
fmt.Printf("[SourceTracker] Falha %d para %s: %s (retry após %v)\n",
failure.FailCount, source, reason, backoffMinutes[backoffIndex])
} else {
a.sourceFailures[source] = &SourceFailure{
Source: source,
FailedAt: time.Now(),
FailCount: 1,
LastError: reason,
RetryAfter: time.Now().Add(30 * time.Second),
}
fmt.Printf("[SourceTracker] Primeira falha para %s: %s\n", source, reason)
}
}
// recordSourceSuccess registra sucesso de uma fonte
func (a *App) recordSourceSuccess(source string) {
a.sourceFailuresMutex.Lock()
defer a.sourceFailuresMutex.Unlock()
// Reseta falhas após sucesso
if failure, exists := a.sourceFailures[source]; exists {
fmt.Printf("[SourceTracker] Fonte %s recuperada após %d falhas\n", source, failure.FailCount)
delete(a.sourceFailures, source)
}
}
// IsSourceAvailable verifica se uma fonte está disponÃvel (não em cooldown)
func (a *App) IsSourceAvailable(source string) bool {
a.sourceFailuresMutex.RLock()
defer a.sourceFailuresMutex.RUnlock()
if failure, exists := a.sourceFailures[source]; exists {
if time.Now().Before(failure.RetryAfter) {
fmt.Printf("[SourceTracker] Fonte %s em cooldown até %v\n", source, failure.RetryAfter)
return false
}
}
return true
}
// GetAlternativeSource retorna a melhor fonte alternativa disponÃvel
func (a *App) GetAlternativeSource(excludeSources ...string) string {
sources := []string{"AllAnime", "AnimeFire", "Enime", "Consumet"}
excludeMap := make(map[string]bool)
for _, s := range excludeSources {
excludeMap[s] = true
}
a.sourceFailuresMutex.RLock()
defer a.sourceFailuresMutex.RUnlock()
for _, source := range sources {
if excludeMap[source] {
continue
}
// Verifica se a fonte está disponÃvel
if failure, exists := a.sourceFailures[source]; exists {
if time.Now().Before(failure.RetryAfter) {
continue // Ainda em cooldown
}
}
fmt.Printf("[SourceTracker] Fonte alternativa selecionada: %s\n", source)
return source
}
// Se todas estão em cooldown, retorna a com menor tempo de espera
var bestSource string
var earliestRetry time.Time
for _, source := range sources {
if excludeMap[source] {
continue
}
if failure, exists := a.sourceFailures[source]; exists {
if bestSource == "" || failure.RetryAfter.Before(earliestRetry) {
bestSource = source
earliestRetry = failure.RetryAfter
}
} else {
return source // Fonte sem falhas registradas
}
}
return bestSource
}
// SourceStatus representa o status de uma fonte de vÃdeo para o frontend
type SourceStatus struct {
Name string `json:"name"`
IsAvailable bool `json:"isAvailable"`
FailCount int `json:"failCount"`
LastError string `json:"lastError,omitempty"`
RetryAfter string `json:"retryAfter,omitempty"`
CachedURLs int `json:"cachedUrls"`
}
// CacheStats representa estatÃsticas do cache para o frontend
type CacheStats struct {
Sources []SourceStatus `json:"sources"`
TotalStreams int `json:"totalStreams"`
TotalCache int `json:"totalCache"`
}
// GetCacheStats retorna estatÃsticas do cache e status das fontes
func (a *App) GetCacheStats() CacheStats {
stats := CacheStats{
Sources: make([]SourceStatus, 0),
}
// Conta caches
a.cacheMutex.RLock()
stats.TotalCache = len(a.cache)
a.cacheMutex.RUnlock()
a.streamCacheMutex.RLock()
stats.TotalStreams = len(a.streamCache)
// Conta URLs por fonte
sourceCounts := make(map[string]int)
for _, entry := range a.streamCache {
sourceCounts[entry.Source]++
}
a.streamCacheMutex.RUnlock()
// Status de cada fonte
sources := []string{"AllAnime", "AnimeFire", "Enime", "Consumet"}
a.sourceFailuresMutex.RLock()
defer a.sourceFailuresMutex.RUnlock()
for _, name := range sources {
status := SourceStatus{
Name: name,
IsAvailable: true,
CachedURLs: sourceCounts[name],
}
if failure, exists := a.sourceFailures[name]; exists {
status.FailCount = failure.FailCount
status.LastError = failure.LastError
if time.Now().Before(failure.RetryAfter) {
status.IsAvailable = false
status.RetryAfter = failure.RetryAfter.Format("15:04:05")
}
}
stats.Sources = append(stats.Sources, status)
}
return stats
}
// ResetSourceFailures reseta todas as falhas de fontes (útil para debug)
func (a *App) ResetSourceFailures() {
a.sourceFailuresMutex.Lock()
defer a.sourceFailuresMutex.Unlock()
a.sourceFailures = make(map[string]*SourceFailure)
fmt.Println("[SourceTracker] Todas as falhas foram resetadas")
}
// startVideoProxy inicia um servidor HTTP local para fazer proxy do vÃdeo
func (a *App) startVideoProxy() error {
if a.proxyServer != nil {
return nil // Já está rodando
}
// Encontra uma porta livre
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return fmt.Errorf("erro ao encontrar porta livre: %w", err)
}
a.proxyPort = listener.Addr().(*net.TCPAddr).Port
listener.Close()
mux := http.NewServeMux()
mux.HandleFunc("/video", a.handleVideoProxy)
mux.HandleFunc("/proxy/", a.handleGenericProxy) // Para segmentos HLS
mux.HandleFunc("/manga-image", a.handleMangaImageProxy) // Para imagens de mangá com cache
a.proxyServer = &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", a.proxyPort),
Handler: mux,
}
go func() {
fmt.Printf("[VideoProxy] Iniciando servidor na porta %d\n", a.proxyPort)
if err := a.proxyServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("[VideoProxy] Erro: %v\n", err)
}
}()
// Espera o servidor iniciar
time.Sleep(100 * time.Millisecond)
return nil
}
// handleGenericProxy faz proxy de qualquer URL (para segmentos HLS)
func (a *App) handleGenericProxy(w http.ResponseWriter, r *http.Request) {
// URL está no path: /proxy/https://...
targetURL := strings.TrimPrefix(r.URL.Path, "/proxy/")
if r.URL.RawQuery != "" {
targetURL += "?" + r.URL.RawQuery
}
if targetURL == "" {
http.Error(w, "URL não especificada", http.StatusBadRequest)
return
}
fmt.Printf("[GenericProxy] Proxy de: %s\n", targetURL)
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest("GET", targetURL, nil)
if err != nil {
http.Error(w, "Erro ao criar request", http.StatusInternalServerError)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
// Copia Range header se presente
if rangeHeader := r.Header.Get("Range"); rangeHeader != "" {
req.Header.Set("Range", rangeHeader)
}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("[GenericProxy] Erro: %v\n", err)
http.Error(w, "Erro ao acessar recurso", http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Headers CORS
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
// Copia headers da resposta
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
// handleMangaImageProxy faz proxy de imagens de mangá com cache em memória
func (a *App) handleMangaImageProxy(w http.ResponseWriter, r *http.Request) {
imageURL := r.URL.Query().Get("url")
referer := r.URL.Query().Get("referer")
if imageURL == "" {
http.Error(w, "URL não especificada", http.StatusBadRequest)
return
}
// Verifica cache
a.imageCacheMutex.RLock()
cachedData, exists := a.imageCache[imageURL]
a.imageCacheMutex.RUnlock()
if exists && len(cachedData) > 0 {
// Serve do cache
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Cache-Control", "public, max-age=3600")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(cachedData)
return
}
// Baixa a imagem
req, err := http.NewRequest("GET", imageURL, nil)
if err != nil {
http.Error(w, "Erro ao criar request", http.StatusInternalServerError)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
req.Header.Set("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8")
req.Header.Set("Accept-Language", "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7")
if referer != "" {
req.Header.Set("Referer", referer)
} else {
// Extrai referer da URL
parsed, _ := url.Parse(imageURL)
if parsed != nil {
req.Header.Set("Referer", fmt.Sprintf("%s://%s/", parsed.Scheme, parsed.Host))
}
}
resp, err := a.imageClient.Do(req)
if err != nil {
fmt.Printf("[MangaImageProxy] Erro ao baixar: %v\n", err)
http.Error(w, "Erro ao baixar imagem", http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
http.Error(w, "Imagem não encontrada", resp.StatusCode)
return
}
// Lê a imagem
data, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "Erro ao ler imagem", http.StatusInternalServerError)
return
}
// Salva no cache (limite de 100MB total)
a.imageCacheMutex.Lock()
// Limpa cache se muito grande (simples, pode melhorar depois)
if len(a.imageCache) > 500 {
// Remove metade das entradas mais antigas
count := 0
for k := range a.imageCache {
if count > 250 {
break
}
delete(a.imageCache, k)
count++
}
}
a.imageCache[imageURL] = data
a.imageCacheMutex.Unlock()
// Detecta content-type
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
contentType = http.DetectContentType(data)
}
// Responde
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "public, max-age=3600")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data)))
w.Write(data)
}
// handleVideoProxy faz proxy do vÃdeo remoto para o cliente local
func (a *App) handleVideoProxy(w http.ResponseWriter, r *http.Request) {
a.proxyMutex.RLock()
videoURL := a.currentVideoURL
a.proxyMutex.RUnlock()
if videoURL == "" {
http.Error(w, "Nenhum vÃdeo configurado", http.StatusBadRequest)
return
}
fmt.Printf("[VideoProxy] Fazendo proxy de: %s\n", videoURL)
// Cria request para o servidor remoto
client := &http.Client{
Timeout: 0, // Sem timeout para streaming
}
req, err := http.NewRequest("GET", videoURL, nil)
if err != nil {
http.Error(w, "Erro ao criar request", http.StatusInternalServerError)
return
}
// Copia headers da requisição original (para suportar Range requests)
for key, values := range r.Header {
for _, value := range values {
if key == "Range" || key == "Accept" || key == "Accept-Encoding" {
req.Header.Add(key, value)
}
}
}
// Headers comuns para parecer um navegador real
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
// Define Referer baseado na URL de origem
if strings.Contains(videoURL, "lightspeedst.net") {
// LightSpeed CDN - precisa do referer correto do AnimeFire
req.Header.Set("Referer", "https://animefire.plus/")
req.Header.Set("Origin", "https://animefire.plus")
} else if strings.Contains(videoURL, "animefire") {
req.Header.Set("Referer", "https://animefire.plus/")
req.Header.Set("Origin", "https://animefire.plus")
} else if strings.Contains(videoURL, "sharepoint") || strings.Contains(videoURL, "microsoft") {
// SharePoint precisa de headers especÃficos
req.Header.Set("Referer", "https://myanime.sharepoint.com/")
req.Header.Set("Origin", "https://myanime.sharepoint.com")
req.Header.Set("Accept", "*/*")
} else if strings.Contains(videoURL, "allanime") || strings.Contains(videoURL, "gogoanime") {
req.Header.Set("Referer", "https://allanime.to/")
req.Header.Set("Origin", "https://allanime.to")
} else {
req.Header.Set("Referer", "https://google.com/")
}
// Headers adicionais para compatibilidade
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("Sec-Fetch-Dest", "video")
req.Header.Set("Sec-Fetch-Mode", "no-cors")
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Accept", "*/*")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("[VideoProxy] Erro na requisição: %v\n", err)
http.Error(w, "Erro ao acessar vÃdeo", http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Verifica se a resposta foi bem sucedida
if resp.StatusCode >= 400 {
fmt.Printf("[VideoProxy] Servidor remoto retornou erro: %d %s\n", resp.StatusCode, resp.Status)
// Se for um erro de autenticação, tenta sem proxy
if resp.StatusCode == 401 || resp.StatusCode == 403 {
fmt.Printf("[VideoProxy] Erro de autenticação - URL pode requerer acesso direto\n")
}
}
// Headers CORS e de resposta
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Range, Accept, Content-Type")
w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Range, Accept-Ranges")
// Se for m3u8, reescreve as URLs para usar nosso proxy
isM3U8 := strings.Contains(videoURL, ".m3u8") || strings.Contains(resp.Header.Get("Content-Type"), "mpegurl")
if isM3U8 {
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "Erro ao ler m3u8", http.StatusInternalServerError)
return
}
// Reescreve URLs no m3u8 para usar nosso proxy
content := string(body)
lines := strings.Split(content, "\n")
var newLines []string
baseURL := videoURL[:strings.LastIndex(videoURL, "/")+1]
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
// Mantém comentários e linhas vazias
newLines = append(newLines, line)
} else {
// É uma URL de segmento
var fullURL string
if strings.HasPrefix(line, "http://") || strings.HasPrefix(line, "https://") {
fullURL = line
} else {
fullURL = baseURL + line
}
// Reescreve para usar nosso proxy
proxyURL := fmt.Sprintf("http://127.0.0.1:%d/proxy/%s", a.proxyPort, fullURL)
newLines = append(newLines, proxyURL)
}
}
newContent := strings.Join(newLines, "\n")
w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(newContent)))
w.WriteHeader(http.StatusOK)
w.Write([]byte(newContent))
return
}
// Copia headers da resposta remota
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
// Garante Content-Type correto para MP4
if strings.HasSuffix(videoURL, ".mp4") {
w.Header().Set("Content-Type", "video/mp4")
}
w.WriteHeader(resp.StatusCode)
// Faz streaming do corpo
_, err = io.Copy(w, resp.Body)
if err != nil {
fmt.Printf("[VideoProxy] Erro no streaming: %v\n", err)
}
}
// GetProxyURLForVideo retorna a URL do proxy local para um vÃdeo
func (a *App) GetProxyURLForVideo(videoURL string) (string, error) {
// Inicia o proxy se ainda não estiver rodando
if err := a.startVideoProxy(); err != nil {
return "", err
}
// Configura a URL atual
a.proxyMutex.Lock()
a.currentVideoURL = videoURL
a.proxyMutex.Unlock()
proxyURL := fmt.Sprintf("http://127.0.0.1:%d/video", a.proxyPort)
fmt.Printf("[GetProxyURLForVideo] Proxy URL: %s -> %s\n", proxyURL, videoURL)
return proxyURL, nil
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.client = goanime.NewClient()
a.User = store.LoadUser()
// Inicializa Discord OAuth
initDiscordOAuth()
// Pré-carrega dados em background para inicialização rápida
go a.preloadData()