Esempio n. 1
0
        /// <summary>
        /// 检查是否更新NpsAppSecret、NpsServer、NpsClient
        /// </summary>
        /// <param name="npsAppSecret">NpsAppSecret</param>
        /// <returns>返回NpsAppSecret</returns>
        private async Task <NpsAppSecret> UpdateNpsClientOrNpsServerIfCheckNotNullAsync(NpsAppSecret npsAppSecret)
        {
            Check.NotNull(npsAppSecret, nameof(npsAppSecret));
            Check.NotNull(npsAppSecret.NpsClient, nameof(npsAppSecret.NpsClient));

            _logger.LogInformation($"检查是否更新NpsAppSecret、NpsServer、NpsClient,设备唯一识别编码:{npsAppSecret.DeviceUniqueId}");
            if (npsAppSecret.NpsClient.RemoteClientId == 0 || npsAppSecret.NpsServer == null || npsAppSecret.NpsServerId == 0)
            {
                var clientListOutput = await GetRemoteClientOutputAsync(npsAppSecret.AppSecret);

                if (clientListOutput == null || clientListOutput.Datas == null || clientListOutput.Datas.Count == 0)
                {
                    return(npsAppSecret);
                }

                //若本地数据库Nps客户端表中无远程Nps客户端Id,则将远程客户端信息回写
                if (npsAppSecret.NpsClient.RemoteClientId == 0)
                {
                    var remoteNpsClient = clientListOutput.Datas[0];

                    _npsClientRepository.Attach(npsAppSecret.NpsClient);
                    npsAppSecret.NpsClient.RemoteClientId     = remoteNpsClient.Id;
                    npsAppSecret.NpsClient.Status             = remoteNpsClient.Status;
                    npsAppSecret.NpsClient.IsConnect          = remoteNpsClient.IsConnect;
                    npsAppSecret.NpsClient.LastConnectAddress = remoteNpsClient.LastConnectAddress;
                    await _npsClientRepository.UpdateAsync(npsAppSecret.NpsClient);
                }

                //若该设备无对应的服务器信息,则将服务器写入本地数据库
                if (npsAppSecret.NpsServer == null)
                {
                    //先根据IP地址查询服务器是否存在
                    npsAppSecret.NpsServer = await _npsServerRepository.Where(x => x.ServerIPAddress == clientListOutput.ServerIPAddress).ToOneAsync();

                    if (npsAppSecret.NpsServer == null)
                    {
                        npsAppSecret.NpsServer = await _npsServerRepository.InsertAsync(new NpsServer
                        {
                            ServerIPAddress   = clientListOutput.ServerIPAddress,
                            ClientConnectPort = clientListOutput.ClientConnectPort.ToInt32OrDefault(0),
                            ProtocolType      = _protocolType
                        });
                    }
                }

                //若该设备无对应的服务器信息
                if (npsAppSecret.NpsServerId == 0)
                {
                    if (npsAppSecret?.NpsServer?.Id > 0)
                    {
                        //将服务器信息与设备应用密钥关联
                        _npsAppSecretRepository.Attach(npsAppSecret);
                        npsAppSecret.NpsServerId = npsAppSecret.NpsServer.Id;
                        await _npsAppSecretRepository.UpdateAsync(npsAppSecret);
                    }
                }
            }

            return(npsAppSecret);
        }
Esempio n. 2
0
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (SkipLogging(context))
            {
                return(base.OnActionExecutionAsync(context, next));
            }

            #region Serilog摘要日志

            _diagnosticContext.Set("ActionArguments", context.ActionArguments.ToJson());
            _diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues);
            _diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName);
            _diagnosticContext.Set("ActionId", context.ActionDescriptor.Id);
            _diagnosticContext.Set("ValidationState", context.ModelState.IsValid);

            #endregion

            #region 接口审计日志

            var input = new ActionTrackLog
            {
                HostDomain = $"{context.HttpContext.Request.Scheme}://{context.HttpContext.Request.Host.Value}",
                ApiMethod  = context.HttpContext.Request.Method,
                ApiPath    = context.HttpContext.Request.Path.Value,
                ApiParams  = context.ActionArguments.ToJson(),
                UserAgent  = _httpContextAccessor.HttpContext.Request.Headers["User-Agent"],
                IP         = GetIp(_httpContextAccessor?.HttpContext?.Request)
            };

            //接口执行耗时
            var watch = new Stopwatch();
            watch.Start();
            var actionExecutedContext = next();
            watch.Stop();
            input.ExecuteMilliseconds = watch.ElapsedMilliseconds;
            input.StatusCode          = context.HttpContext.Response.StatusCode;

            if (actionExecutedContext.Result.Exception != null)
            {
                input.ExecuteMessage = actionExecutedContext.Result.Exception.Message;
            }
            else
            {
                if (actionExecutedContext.Result.Result is ObjectResult result && result.Value is IExecuteResult res)
                {
                    input.ExecuteResult  = res.ToJson();
                    input.ExecuteMessage = res.Message;
                }
            }

            _actionTrackLogRepository.InsertAsync(input);

            #endregion

            return(Task.CompletedTask);
        }
Esempio n. 3
0
        /// <summary>
        /// 检测设备是否已创建过唯一识别密钥,如果不存在,则创建
        /// </summary>
        /// <param name="deviceUniqueId">设备唯一识别编码</param>
        /// <param name="npsAppSecret">NpsAppSecret</param>
        /// <returns>返回NpsAppSecret</returns>
        private async Task <NpsAppSecret> CreateNpsAppSecretIfCheckNullAsync(string deviceUniqueId, NpsAppSecret npsAppSecret)
        {
            _logger.LogInformation($"检测设备是否已创建过唯一识别密钥,设备唯一识别编码:{deviceUniqueId}");
            if (npsAppSecret == null)
            {
                npsAppSecret = await _npsAppSecretRepository.InsertAsync(new NpsAppSecret
                {
                    DeviceUniqueId = deviceUniqueId,
                    AppSecret      = _guidGenerator.Create().ToString("N")
                });
            }

            return(npsAppSecret);
        }
Esempio n. 4
0
        /// <summary>
        /// 检测设备是否已创建过客户端,如果不存在,则创建
        /// </summary>
        /// <param name="input">开通客户端输入参数</param>
        /// <param name="npsAppSecret">NpsAppSecret</param>
        /// <returns>返回NpsAppSecret</returns>
        private async Task <NpsAppSecret> CreateNpsClientIfCheckNullAsync(NpsClientOpenInput input, NpsAppSecret npsAppSecret)
        {
            Check.NotNull(npsAppSecret, nameof(npsAppSecret));

            _logger.LogInformation($"检测设备是否已创建过客户端,设备唯一识别编码:{npsAppSecret.DeviceUniqueId}");
            if (npsAppSecret.NpsClient == null)
            {
                //调用远程Api执行添加客户端
                var baseAuthInput = await BeforeRequestNpsApiAsync();

                var remoteApiResult = await _npsApi.AddClientAsync(new ClientAddInput
                {
                    AuthKey              = baseAuthInput.AuthKey,
                    Timestamp            = baseAuthInput.Timestamp,
                    AppSecret            = npsAppSecret.AppSecret,
                    IsConfigConnectAllow = input.IsConfigConnectAllow.ToInt32OrDefault(1),
                    IsCompress           = input.IsCompress.ToInt32OrDefault(0),
                    IsCrypt              = input.IsCrypt.ToInt32OrDefault(1),
                    Remark = input.Remark
                });

                if (remoteApiResult.Status == 1)
                {//远程添加成功后,将数据写入本地Nps客户端表中
                    npsAppSecret.NpsClient = await _npsClientRepository.InsertAsync(new NpsClient
                    {
                        Id = npsAppSecret.Id,
                        IsConfigConnectAllow = input.IsConfigConnectAllow,
                        IsCompress           = input.IsCompress,
                        IsCrypt = input.IsCrypt,
                        Remark  = input.Remark
                    });
                }
                else
                {
                    throw new NpsException(remoteApiResult.Message, StatusCode.Error);
                }
            }

            return(npsAppSecret);
        }
Esempio n. 5
0
        /// <summary>
        /// 检查是否已创建服务器客户端隧道,如果不存在,则创建
        /// </summary>
        /// <param name="input">设备开通服务输入参数</param>
        /// <param name="npsAppSecret">NpsAppSecret</param>
        /// <returns>返回NpsAppSecret</returns>
        private async Task <NpsAppSecret> CreateNpsChannelIfCheckNullAsync(NpsClientOpenInput input, NpsAppSecret npsAppSecret)
        {
            Check.NotNull(npsAppSecret, nameof(npsAppSecret));
            Check.NotNull(npsAppSecret.NpsClient, nameof(npsAppSecret.NpsClient));

            _logger.LogInformation($"检查是否已创建服务器客户端隧道,设备唯一识别编码:{npsAppSecret.DeviceUniqueId};开通端口列表:{input.OpenPorts.ToJson()}");
            if (npsAppSecret.NpsClient.NpsChannels == null)
            {
                npsAppSecret.NpsClient.NpsChannels = new List <NpsChannel>();
            }

            //查询已开通隧道列表
            var openedNpsChannels = npsAppSecret.NpsClient?.NpsChannels.Where(x => input.OpenPorts.Contains(x.DeviceAddress));
            //查询已开通隧道端口号列表
            var openedNpsChannelPorts = openedNpsChannels?.Select(x => x.DeviceAddress);
            //取需要开通端口号集合与已开通端口号集合差集,得到正在需要开通的端口列表
            var needOpenPorts = input.OpenPorts.Except(openedNpsChannelPorts).ToList();

            if (needOpenPorts.Count > 0)
            {
                var needOpenNpsChannels = new List <NpsChannel>();

                //取自定义服务器端口
                var nowMaxServerPort = await _npsChannelRepository.Select.MaxAsync(x => x.ServerPort);

                var startServerPort = nowMaxServerPort == 0 ? _minServerPort : nowMaxServerPort;

                var baseAuthInput = await BeforeRequestNpsApiAsync();

                for (int index = 0; index < needOpenPorts.Count; index++)
                {
                    //向远程服务器添加隧道
                    var remark          = $"{input.Remark}_隧道_{startServerPort += 1}";
                    var remoteApiResult = await _npsApi.AddChannelAsync(new ChannelAddInput
                    {
                        AuthKey       = baseAuthInput.AuthKey,
                        Timestamp     = baseAuthInput.Timestamp,
                        Remark        = remark,
                        ServerPort    = startServerPort,
                        TargetAddress = needOpenPorts[index],
                        ClientId      = npsAppSecret.NpsClient.RemoteClientId
                    });

                    if (remoteApiResult.Status == 1)
                    {//隧道添加成功后,写入本地数据库表
                        needOpenNpsChannels.Add(new NpsChannel
                        {
                            NpsClientId   = npsAppSecret.NpsClient.Id,
                            ServerPort    = startServerPort,
                            DeviceAddress = needOpenPorts[index],
                            Remark        = remark
                        });
                    }
                    else
                    {
                        _logger.LogError($"开通客户端{npsAppSecret.DeviceUniqueId},端口{needOpenPorts[index]},{remoteApiResult.Message}");
                        continue;
                    }
                }

                if (needOpenNpsChannels.Count > 0)
                {
                    //将本次已开通隧道列表写入本地数据库
                    needOpenNpsChannels = await _npsChannelRepository.InsertAsync(needOpenNpsChannels);

                    //将本次已开通隧道列表附加至查询结果
                    npsAppSecret.NpsClient.NpsChannels.AddRange(needOpenNpsChannels);
                }
            }

            return(npsAppSecret);
        }