fix proxy configuration for files #28
|
|
@ -1,6 +1,7 @@
|
|||
package tgkit
|
||||
|
||||
import (
|
||||
"bitrix_balancer_api/core/variables"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
|
|
@ -15,13 +16,6 @@ import (
|
|||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Константы для нового API-прокси
|
||||
const (
|
||||
ProxyForwardURL = "https://proxyservice.ddns.net/forward"
|
||||
ProxySecretHeader = "X-Proxy-Secret"
|
||||
ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5"
|
||||
)
|
||||
|
||||
// APIProxyRequest описывает структуру тела запроса к твоему прокси-сервису
|
||||
type APIProxyRequest struct {
|
||||
URL string `json:"url"`
|
||||
|
|
@ -87,17 +81,14 @@ func (t *CustomAPIProxyTransport) RoundTrip(req *http.Request) (*http.Response,
|
|||
return nil, fmt.Errorf("proxy transport: failed to marshal proxy payload: %w", err)
|
||||
}
|
||||
|
||||
// 3. Создаем новый запрос к прокси-серверу
|
||||
proxyReq, err := http.NewRequestWithContext(req.Context(), "POST", ProxyForwardURL, bytes.NewReader(proxyJsonBytes))
|
||||
proxyReq, err := http.NewRequestWithContext(req.Context(), "POST", variables.ProxyForwardURL, bytes.NewReader(proxyJsonBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("proxy transport: failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// 4. Устанавливаем заголовки
|
||||
proxyReq.Header.Set("Content-Type", "application/json")
|
||||
proxyReq.Header.Set(ProxySecretHeader, ProxySecretKey)
|
||||
proxyReq.Header.Set(variables.ProxySecretHeader, variables.ProxySecretKey)
|
||||
|
||||
// 5. Выполняем запрос
|
||||
resp, err := t.wrapped.RoundTrip(proxyReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
|||
|
|
@ -8,3 +8,10 @@ const (
|
|||
ContextTimeoutBase = 15 * time.Second
|
||||
ContextTimeoutLong = 30 * time.Second
|
||||
)
|
||||
|
||||
// Константы для нового API-прокси (должны совпадать с tgkit)
|
||||
const (
|
||||
ProxyForwardURL = "https://proxyservice.ddns.net/forward"
|
||||
ProxySecretHeader = "X-Proxy-Secret"
|
||||
ProxySecretKey = "9cb0a2655bde593de45b2f3fd17f39e5"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler {
|
|||
}
|
||||
|
||||
// TODO: вызывается только после обновлений
|
||||
go handler.broadcastBotUpdated()
|
||||
//go handler.broadcastBotUpdated()
|
||||
//go handler.sendSupportNotification()
|
||||
|
||||
return handler
|
||||
|
|
|
|||
|
|
@ -2,15 +2,19 @@ package approval
|
|||
|
||||
import (
|
||||
configcore "bitrix_balancer_api/core/config"
|
||||
"bitrix_balancer_api/core/variables"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
@ -18,21 +22,76 @@ var (
|
|||
fileHTTPClientOnce sync.Once
|
||||
)
|
||||
|
||||
// APIProxyRequest описывает структуру тела запроса к прокси-сервису
|
||||
type APIProxyRequest struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Body interface{} `json:"body"`
|
||||
}
|
||||
|
||||
// FileProxyTransport перехватывает GET-запросы на скачивание файлов и заворачивает их в API-прокси
|
||||
type FileProxyTransport struct {
|
||||
wrapped http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *FileProxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// Для скачивания файлов используется GET, поэтому body всегда пустой объект {}
|
||||
proxyReqPayload := APIProxyRequest{
|
||||
URL: req.URL.String(),
|
||||
Method: req.Method,
|
||||
Body: map[string]interface{}{},
|
||||
}
|
||||
|
||||
proxyJsonBytes, err := json.Marshal(proxyReqPayload)
|
||||
if err != nil {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Если прокси вернул статус отличный от 200 OK, вычитываем ошибку
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
defer resp.Body.Close()
|
||||
errorBody, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("file proxy returned status %d (%s): %s", resp.StatusCode, resp.Status, string(errorBody))
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func buildFileHTTPClient(tgConfig configcore.TelegramConfig) (*http.Client, error) {
|
||||
if tgConfig.ProxyURL == "" || tgConfig.ParsedProxy == nil {
|
||||
// Оставляем проверку, чтобы контролировать включение прокси через конфиг
|
||||
if tgConfig.ProxyURL == "" {
|
||||
return nil, errors.New("proxy url is empty or not configured")
|
||||
}
|
||||
|
||||
fileHTTPClientOnce.Do(func() {
|
||||
baseTransport := &http.Transport{
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
|
||||
fileHTTPClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
ResponseHeaderTimeout: 10 * time.Second,
|
||||
MaxIdleConns: 100,
|
||||
MaxIdleConnsPerHost: 10,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
Proxy: http.ProxyURL(tgConfig.ParsedProxy),
|
||||
// Оборачиваем базовый транспорт в наш FileProxyTransport
|
||||
Transport: &FileProxyTransport{
|
||||
wrapped: baseTransport,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
|
@ -40,7 +99,7 @@ func buildFileHTTPClient(tgConfig configcore.TelegramConfig) (*http.Client, erro
|
|||
return fileHTTPClient, nil
|
||||
}
|
||||
|
||||
// fetchFileAsBase64 скачивает файл по URL и возвращает base64-строку.
|
||||
// fetchFileAsBase64 скачивает файл по URL через API-прокси и возвращает base64-строку.
|
||||
func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string, error) {
|
||||
client, err := buildFileHTTPClient(tgConfig)
|
||||
if err != nil {
|
||||
|
|
@ -76,9 +135,12 @@ func fetchFileAsBase64(url string, tgConfig configcore.TelegramConfig) (string,
|
|||
}
|
||||
cancel()
|
||||
|
||||
lastErr = err
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
logrus.Warnf("fetchFileAsBase64: attempt %d/%d failed: %v", attempt, maxRetries, err)
|
||||
} else if resp != nil {
|
||||
lastErr = fmt.Errorf("bad status code: %s", resp.Status)
|
||||
logrus.Warnf("fetchFileAsBase64: attempt %d/%d bad status: %s", attempt, maxRetries, resp.Status)
|
||||
}
|
||||
|
||||
if attempt < maxRetries {
|
||||
|
|
|
|||
Loading…
Reference in New Issue