Updated files proxy #171

Merged
romanskijdev merged 1 commits from fix-permissions into main 2026-10-01 15:10:55 +03:00
1 changed files with 172 additions and 4 deletions

View File

@ -4,11 +4,15 @@ import (
"bitrix_balancer_api/core/variables"
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
@ -30,10 +34,27 @@ type APIProxyRequest struct {
// FileProxyTransport перехватывает GET-запросы на скачивание файлов и заворачивает их в API-прокси
type FileProxyTransport struct {
wrapped http.RoundTripper
// Поля для fallback-механизма на бесплатные прокси
mu sync.RWMutex
fallbackMode bool
fallbackProxyURL string
fallbackTransport http.RoundTripper
}
func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Для скачивания файлов используется GET, поэтому body всегда пустой объект {}
t.mu.RLock()
fallbackMode := t.fallbackMode
fallbackTrans := t.fallbackTransport
currentFallbackURL := t.fallbackProxyURL
t.mu.RUnlock()
// Если мы уже перешли на бесплатный прокси — идем по резервному пути напрямую
if fallbackMode && fallbackTrans != nil {
return t.executeFallback(req, fallbackTrans, currentFallbackURL)
}
// --- Стандартный путь через приватный шлюз ---
proxyReqPayload := APIProxyRequest{
URL: req.URL.String(),
Method: req.Method,
@ -57,10 +78,12 @@ func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error
resp, err := t.wrapped.RoundTrip(proxyReq)
if err != nil {
return nil, err
// Шлюз недоступен, переключаемся на бесплатные прокси
logrus.Warnf("approval: custom gateway failed (%v), switching to free fallback proxies for files.", err)
return t.switchToFallbackAndExecute(req, "")
}
// Если прокси вернул статус отличный от 200 OK, вычитываем ошибку
// Если прокси вернул статус отличный от 200 OK
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
errorBody, _ := io.ReadAll(resp.Body)
@ -70,6 +93,152 @@ func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error
return resp, nil
}
// executeFallback перенаправляет оригинальный GET запрос напрямую в Telegram через бесплатный прокси
func (t *FileProxyTransport) executeFallback(req *http.Request, trans http.RoundTripper, currentProxyURL string) (*http.Response, error) {
newReq := req.Clone(req.Context())
resp, err := trans.RoundTrip(newReq)
if err != nil {
logrus.Warnf("approval: fallback proxy %s disconnected (%v), searching for a new one...", currentProxyURL, err)
return t.switchToFallbackAndExecute(req, currentProxyURL)
}
return resp, nil
}
// switchToFallbackAndExecute блокирует транспорт, ищет прокси и выполняет запрос
func (t *FileProxyTransport) switchToFallbackAndExecute(req *http.Request, failedProxyURL string) (*http.Response, error) {
t.mu.Lock()
if t.fallbackMode && t.fallbackProxyURL != failedProxyURL {
savedTrans := t.fallbackTransport
currentURL := t.fallbackProxyURL
t.mu.Unlock()
return t.executeFallback(req, savedTrans, currentURL)
}
logrus.Infof("approval: searching for the fastest free proxy for file downloads...")
newProxyURL, err := findFastestFreeProxy()
if err != nil {
t.mu.Unlock()
return nil, fmt.Errorf("failed to find a working free proxy: %w", err)
}
parsedURL, _ := url.Parse(newProxyURL)
newTrans := &http.Transport{
Proxy: http.ProxyURL(parsedURL),
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
t.fallbackMode = true
t.fallbackProxyURL = newProxyURL
t.fallbackTransport = newTrans
savedTrans := newTrans
t.mu.Unlock()
logrus.Infof("approval: successfully switched to free proxy: %s", newProxyURL)
return t.executeFallback(req, savedTrans, newProxyURL)
}
// findFastestFreeProxy ищет рабочий прокси со строгой проверкой Telegram API
func findFastestFreeProxy() (string, error) {
sources := []string{
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
"https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=5000&country=all&ssl=all&anonymity=all",
}
var proxies []string
for _, src := range sources {
resp, err := http.Get(src)
if err == nil {
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
lines := strings.Split(string(body), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" {
proxies = append(proxies, line)
}
}
}
if len(proxies) > 100 {
break
}
}
if len(proxies) == 0 {
return "", fmt.Errorf("could not fetch proxies from public sources")
}
resultCh := make(chan string, 1)
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
limit := 100
if len(proxies) < limit {
limit = len(proxies)
}
for i := 0; i < limit; i++ {
p := proxies[i]
if !strings.HasPrefix(p, "http") && !strings.HasPrefix(p, "socks") {
p = "http://" + p
}
wg.Add(1)
go func(proxyUrl string) {
defer wg.Done()
u, err := url.Parse(proxyUrl)
if err != nil {
return
}
// Строгая проверка, что прокси отдает именно ответ от Telegram
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org/bot123456:invalid_token/getMe", nil)
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(u),
DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 4 * time.Second,
}
resp, err := client.Do(req)
if err == nil {
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if bytes.Contains(body, []byte(`"ok":`)) {
select {
case resultCh <- proxyUrl:
cancel()
default:
}
}
}
}(p)
}
go func() {
wg.Wait()
close(resultCh)
}()
select {
case best, ok := <-resultCh:
if !ok {
return "", fmt.Errorf("all %d tested proxies failed", limit)
}
return best, nil
case <-time.After(8 * time.Second):
return "", fmt.Errorf("timeout waiting for a valid proxy")
}
}
func buildFileHTTPClient() (*http.Client, error) {
fileHTTPClientOnce.Do(func() {
baseTransport := &http.Transport{
@ -82,7 +251,6 @@ func buildFileHTTPClient() (*http.Client, error) {
fileHTTPClient = &http.Client{
Timeout: 30 * time.Second,
// Оборачиваем базовый транспорт в наш FileProxyTransport
Transport: &FileProxyTransport{
wrapped: baseTransport,
},