Updated files proxy #172

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

View File

@ -7,6 +7,7 @@ import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@ -49,12 +50,10 @@ func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error
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,
@ -66,24 +65,20 @@ func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error
return nil, fmt.Errorf("file proxy transport: failed to marshal payload: %w", err)
}
// Формируем POST-запрос к API-прокси шлюзу
proxyReq, err := http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(proxyJsonBytes))
if err != nil {
return nil, fmt.Errorf("file proxy transport: failed to create request: %w", err)
}
// Проставляем обязательные заголовки
proxyReq.Header.Set("Content-Type", "application/json")
proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
resp, err := t.wrapped.RoundTrip(proxyReq)
if err != nil {
// Шлюз недоступен, переключаемся на бесплатные прокси
logrus.Warnf("approval: custom gateway failed (%v), switching to free fallback proxies for files.", err)
return t.switchToFallbackAndExecute(req, "")
}
// Если прокси вернул статус отличный от 200 OK
if resp.StatusCode != http.StatusOK {
defer resp.Body.Close()
errorBody, _ := io.ReadAll(resp.Body)
@ -93,19 +88,24 @@ 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 {
// КРИТИЧНОЕ ИСПРАВЛЕНИЕ: Если ошибка вызвана таймаутом в функции скачивания
// (context deadline exceeded или canceled), то прокси жив, просто файл качался слишком долго.
// Не бракуем прокси и не ищем новый!
if errors.Is(req.Context().Err(), context.DeadlineExceeded) || errors.Is(req.Context().Err(), context.Canceled) || strings.Contains(err.Error(), "canceled") {
return nil, err
}
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 {
@ -142,7 +142,6 @@ func (t *FileProxyTransport) switchToFallbackAndExecute(req *http.Request, faile
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",
@ -164,7 +163,8 @@ func findFastestFreeProxy() (string, error) {
}
}
}
if len(proxies) > 100 {
// Увеличили лимит пула до 200, чтобы повысить шансы быстро найти живой прокси
if len(proxies) > 200 {
break
}
}
@ -178,7 +178,7 @@ func findFastestFreeProxy() (string, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
limit := 100
limit := 200
if len(proxies) < limit {
limit = len(proxies)
}
@ -196,7 +196,6 @@ func findFastestFreeProxy() (string, error) {
return
}
// Строгая проверка, что прокси отдает именно ответ от Telegram
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.telegram.org/bot123456:invalid_token/getMe", nil)
client := &http.Client{
Transport: &http.Transport{
@ -243,14 +242,15 @@ func buildFileHTTPClient() (*http.Client, error) {
fileHTTPClientOnce.Do(func() {
baseTransport := &http.Transport{
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ResponseHeaderTimeout: 30 * time.Second, // Даем больше времени на ожидание заголовков от Telegram
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
}
fileHTTPClient = &http.Client{
Timeout: 30 * time.Second,
// Увеличили общий таймаут HTTP клиента с 30 до 120 секунд
Timeout: 120 * time.Second,
Transport: &FileProxyTransport{
wrapped: baseTransport,
},
@ -260,7 +260,6 @@ func buildFileHTTPClient() (*http.Client, error) {
return fileHTTPClient, nil
}
// fetchFileAsBase64 скачивает файл по URL через API-прокси и возвращает base64-строку.
func fetchFileAsBase64(url string) (string, error) {
client, err := buildFileHTTPClient()
if err != nil {
@ -272,7 +271,8 @@ func fetchFileAsBase64(url string) (string, error) {
var lastErr error
for attempt := 1; attempt <= maxRetries; attempt++ {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Увеличили время на скачивание одного файла через бесплатный прокси с 30 до 60 секунд
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
cancel()