Как использовать FirebaseAdmin с прокси? - PullRequest
0 голосов
/ 13 июля 2020

Следующий код отлично работает локально. Пользователи получают все push-уведомления (уведомления), когда я отправляю их через локальный P C. Но мне нужно использовать прокси на сервере, и этот код вызывает ошибку: «Не удалось установить sh соединение: сеть недоступна». Пожалуйста, помогите мне настроить прокси для этого кода.

using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;

namespace JMGlobal.Handlers
{
    public class PushHandler : IRequestHandler<Request_Push, Response_Push>
    {
        public async Task<Response_Push> Handle(Request_Push request, CancellationToken cancellationToken)
        {
            try
            {
                var defaultApp = FirebaseApp.DefaultInstance;

                if (defaultApp == null)
                {
                    var keyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jKey.json");
                    defaultApp = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = GoogleCredential.FromFile(keyPath),
                        // HttpClientFactory --- ????
                    });
                }
                var message = new Message()
                {
                    Token = request.FirebaseToken,
                    Apns = new ApnsConfig()
                    {
                        Aps = new FirebaseAdmin.Messaging.Aps()
                        {
                            Alert = new ApsAlert()
                            {
                                Title = "push",
                                Body = request.PushMessage
                            }
                        }
                    },
                     Notification = new Notification
                    {
                        Title = "System Notification",
                        Body = $"Message: {request.PushMessage}"
                    }
                };
                var messaging = FirebaseMessaging.DefaultInstance;
                var result = await messaging.SendAsync(message); // here fires the error: "Failed to establish a connection: Network is unreachable"

                return new Response_Push()
                { .... };
            }
            catch (Exception ex)
            {..... }

        }
    }

}

1 Ответ

0 голосов
/ 19 августа 2020

Рабочая версия ниже.

using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Http;
using System.Net.Http;
using System.Net;
using Microsoft.Extensions.Options;

namespace JMGlobal.Handlers
{
    public class ProxyHttpClientFactory2 : Google.Apis.Http.HttpClientFactory
    {
        private readonly string proxyAddress;
        private readonly bool proxyUseProxy;
        private readonly bool proxyBypassOnLocal;

        public ProxyHttpClientFactory2(string proxyAddress, bool proxyUseProxy, bool proxyBypassOnLocal)
        {
            this.proxyAddress = proxyAddress;
            this.proxyUseProxy = proxyUseProxy;
            this.proxyBypassOnLocal = proxyBypassOnLocal;
        }

        protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
        {
            var proxy = new WebProxy(Address: proxyAddress, BypassOnLocal: proxyBypassOnLocal, BypassList: null, Credentials: null);
            var webRequestHandler = new HttpClientHandler()
            {
                Proxy = proxy,
                UseProxy = proxyUseProxy,
                UseCookies = false
            };

            return webRequestHandler;
        }
    }




    public class PushHandler : IRequestHandler<Request_PushFromBackend, Response_PushFromBackend>
    {
        private readonly IDBCommander _commander;
        private readonly ILogger<PushHandler> _logger;

        public PushFromBackendHandler(ILogger<PushHandler> logger, IDBCommander commander)
        {
            _logger = logger;
            _commander = commander;
        }

        public async Task<Response_PushFromBackend> Handle(Request_PushFromBackend request, CancellationToken cancellationToken)
        {
            var sw = Stopwatch.StartNew();
            bool isProxyUsing = false;

            try
            {

                var resultFCMcreds = await _commander.Get_FCMcredentials(); // settings from DB
                var resultProxy = await _commander.Get_ProxySettings();     // settings from DB


                var defaultApp = FirebaseApp.DefaultInstance;

                if (defaultApp == null)
                {
                    var serviceAccountEmail = resultFCMcreds?.ServiceAccountEmail;
                    var PrivateKey = resultFCMcreds?.PrivateKey;

                    var credential = new ServiceAccountCredential(
                                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                                   {
                                       ProjectId = resultFCMcreds?.ProjectId,
                                       HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal),
                                   }.FromPrivateKey(PrivateKey));


                    defaultApp = FirebaseApp.Create(new AppOptions()
                    {
                        Credential = GoogleCredential.FromServiceAccountCredential(credential),
                        HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal)
                    });

                }


                FirebaseAdmin.Messaging.Aps aps_data = new Aps();

                if (request.PushMode == 1)
                {
                    aps_data.ContentAvailable = true;
                }

                var message = new Message()
                {
                    //Topic = "news",
                    Token = request.FirebaseToken,
                    Apns = new ApnsConfig()
                    {
                        Aps = aps_data
                    },
                    Data = new Dictionary<string, string>()
                    {
                        ["Changed"] = "true",
                    },
                    Notification = (request.PushMode == 1) ? null : new Notification
                    {
                        Title = $"System Notification {((request.PushMode == 1) ? " (SILENT)" : " (NORMAL)")}",
                        Body = $"Message: {request.PushMessage}"
                    }
                };
                var messaging = FirebaseMessaging.DefaultInstance;


                var result = await messaging.SendAsync(message);

                _logger.LogInformation($"result: {result}");

                return new Response_PushFromBackend()
                {
                    ....
                };
            }
            catch (Exception ex)
            {
                return new Response_PushFromBackend()
                {
                    Error = ex.Message
                };
            }

        }
    }

}
...