123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using JsonRpcLite.Services;
- using WingInterfaceLibrary.DB.Request;
- using WingInterfaceLibrary.DTO.Device;
- using WingInterfaceLibrary.DTO.Organization;
- using WingInterfaceLibrary.Enum;
- using WingInterfaceLibrary.Interface;
- using WingInterfaceLibrary.Request;
- using WingInterfaceLibrary.Request.Authentication;
- using WingInterfaceLibrary.Request.Device;
- using WingInterfaceLibrary.Result.Device;
- using WingServerCommon.Log;
- using WingServerCommon.Mapper;
- using WingServerCommon.Service;
- using WingServerCommon.Config;
- using WingServerCommon.Config.Parameters;
- using System.Text.RegularExpressions;
- using WingDeviceService.Common;
- using WingInterfaceLibrary.Internal.Request;
- using System.Net;
- using WingServerCommon.Utilities;
- namespace WingDeviceService.Service
- {
- /// <summary>
- /// 鉴权服务
- /// </summary>
- public partial class DeviceService : JsonRpcService, IConnectService
- {
- private readonly bool _isMergedChannel = ConfigurationManager.GetParammeter<BoolParameter>("Device", "IsMergedChannel").Value;
- private readonly int _highMergedVideoOutputWidth = ConfigurationManager.GetParammeter<IntParameter>("Device", "HighMergedVideoOutputWidth").Value;
- private readonly int _highMergedVideoOutputHeight = ConfigurationManager.GetParammeter<IntParameter>("Device", "HighMergedVideoOutputHeight").Value;
- private readonly int _lowMergedVideoOutputWidth = ConfigurationManager.GetParammeter<IntParameter>("Device", "LowMergedVideoOutputWidth").Value;
- private readonly int _lowMergedVideoOutputHeight = ConfigurationManager.GetParammeter<IntParameter>("Device", "LowMergedVideoOutputHeight").Value;
- private readonly string _highCpuLevels = ConfigurationManager.GetParammeter<StringParameter>("Device", "HighCpuLevels").Value;
- private readonly string _sourceUrl = "cloud.xinglinghui.com";
- private readonly object _createShortCodeLocker = new object();
- /// <summary>设备连接云服务</summary>
- /// <param name="request">请求对象</param>
- /// <returns>授权响应</returns>
- /// <remarks>POST</remarks>
- public async Task<ConnectResult> ConnectAsync(ConnectRequest request)
- {
- try
- {
- #region Params Check
- if (!request.IsOldPlatform)
- {
- if (string.IsNullOrWhiteSpace(request.DeviceUniqueCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceUniqueCodeEmpty, "DeviceUniqueCode empty error");
- }
- if (string.IsNullOrWhiteSpace(request.DeviceModel))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceModelEmpty, "DeviceModel empty error");
- }
- if (string.IsNullOrWhiteSpace(request.DeviceType))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceTypeEmpty, "DeviceType empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
- {
- ThrowCustomerException(CustomerRpcCode.SoftwareVersionEmpty, "SoftwareVersion empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SystemVersion))
- {
- ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemVersion empty error");
- }
- if (string.IsNullOrWhiteSpace(request.CPUModel))
- {
- ThrowCustomerException(CustomerRpcCode.CPUModelEmpty, "CPUModel empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SystemLanguage))
- {
- ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemLanguage empty error");
- }
- var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
- if (!deviceTypeList.Select(x => x.DictionaryCode).Contains(request.DeviceType))
- {
- // ThrowCustomerException(CustomerRpcCode.DeviceTypeError, "DeviceType error");
- Logger.WriteLineWarn(CustomerRpcCode.DeviceTypeError.ToString() + "_" + request.DeviceType);
- }
- var deviceModelList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceModel });
- if (!deviceModelList.Select(x => x.Value).Contains(request.DeviceModel))
- {
- //ThrowCustomerException(CustomerRpcCode.DeviceModelError, "DeviceModel error");
- Logger.WriteLineWarn(CustomerRpcCode.DeviceModelError.ToString() + "_" + request.DeviceModel);
- }
- }
- #endregion
- DeviceInfoDTO deviceDto;
- if (request.IsOldPlatform)
- {
- deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDto == null || string.IsNullOrWhiteSpace(deviceDto.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceNotExist");
- }
- deviceDto.SerialNumber = request.DeviceUniqueCode;
- if (!string.IsNullOrWhiteSpace(request.Name))
- {
- deviceDto.Name = request.Name;
- }
- deviceDto.DeviceType = request.DeviceType;
- deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
- // deviceDto.SystemVersion = request.SystemVersion;
- // deviceDto.CPUModel = request.CPUModel;
- // deviceDto.SystemLanguage = request.SystemLanguage;
- await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
- }
- else
- {
- deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
- if (deviceDto == null && !string.IsNullOrWhiteSpace(request.Name))
- {
- deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.Name);
- if (!string.IsNullOrWhiteSpace(request.Password))
- {
- var password = OldSecurity.Hash(OldSecurity.Salt(request.Password));
- if (deviceDto == null)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNameNotExisted, "DeviceNameNotExisted");
- }
- else if (deviceDto.Password != password)
- {
- ThrowCustomerException(CustomerRpcCode.DevicePasswordErr, "DevicePasswordErr");
- }
- }
- }
- if (deviceDto == null)
- {
- deviceDto = new DeviceInfoDTO()
- {
- SerialNumber = request.DeviceUniqueCode,
- Name = request.Name,
- Password = request.Password,
- Description = request.Description,
- OrganizationCode = request.OrganizationCode,
- DeviceModel = request.DeviceModel,
- DeviceType = request.DeviceType,
- DeviceSoftwareVersion = request.SoftwareVersion,
- SystemVersion = request.SystemVersion,
- CPUModel = request.CPUModel,
- SystemLanguage = request.SystemLanguage,
- IsEncryptedShow = false,
- MergedChannel = _isMergedChannel
- };
- SetDeviceMergedOutput(request.DeviceModel, request.CPUModel, deviceDto);
- var shortCode = deviceDto.ShortCode;
- for (var i = 0; i < 5; i++)
- {
- shortCode = GenerateShortCode();
- if (!string.IsNullOrWhiteSpace(shortCode))
- {
- var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
- if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
- {
- break;
- }
- }
- shortCode = string.Empty;
- }
- deviceDto.ShortCode = shortCode;
- if (string.IsNullOrWhiteSpace(deviceDto.OrganizationCode))
- {
- deviceDto.OrganizationCode = "VINNO_FIS";
- }
- deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
- {
- Data = deviceDto
- });
- }
- else
- {
- deviceDto.SerialNumber = request.DeviceUniqueCode;
- if (!string.IsNullOrWhiteSpace(request.Name))
- {
- deviceDto.Name = request.Name;
- }
- deviceDto.DeviceModel = request.DeviceModel;
- deviceDto.DeviceType = request.DeviceType;
- deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
- deviceDto.SystemVersion = request.SystemVersion;
- deviceDto.CPUModel = request.CPUModel;
- SetDeviceMergedOutput(request.DeviceModel, request.CPUModel, deviceDto);
- // deviceDto.Description = request.Description;
- // deviceDto.Name = request.Name;
- // deviceDto.OrganizationCode = request.OrganizationCode;
- deviceDto.SystemLanguage = request.SystemLanguage;
- await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
- }
- }
- //更新设备型号
- if (!string.IsNullOrEmpty(request.DeviceModel) && !string.IsNullOrEmpty(request.DeviceType))
- {
- var typeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(request.DeviceType);
- if (typeModel != null && typeModel.DictionaryType == DictionaryTypeEnum.DeviceType)
- {
- var dicRequest = new FindDictionaryItemsDBRequest()
- {
- DictionaryType = (int)DictionaryTypeEnum.DeviceModel,
- ParentCode = typeModel.DictionaryCode,
- Value = request.DeviceModel
- };
- var dataList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(dicRequest);
- if (dataList?.Count > 0)
- {
- //存在,不处理
- }
- else
- {
- //新增
- var createDictionaryItemDBRequest = new CreateDictionaryItemDBRequest()
- {
- Data = new WingInterfaceLibrary.DTO.Dictionary.DictionaryDTO() {
- LanguageConfigs = new List<WingInterfaceLibrary.DTO.Dictionary.DictionaryLanguageConfigDTO> (),
- DictionaryCode = Guid.NewGuid().ToString("N"),
- DictionaryType = DictionaryTypeEnum.DeviceModel,
- Value = request.DeviceModel,
- ParentCode = typeModel.DictionaryCode,
- },
- ExtensionData = string.Empty
- };
- var res = await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(createDictionaryItemDBRequest);
- }
- }
- }
- var deviceName = !string.IsNullOrWhiteSpace(deviceDto.Description) ? deviceDto.Description : deviceDto.Name;
- if (string.IsNullOrWhiteSpace(deviceName))
- {
- deviceName = deviceDto.ShortCode;
- }
- var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceDto.DeviceCode, ConfigurationManager.Host, IpToLong(request.Ip), request.InstallVersion, request.IsOldPlatform,request.ProxyType);
- var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
- if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
- {
- _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
- }
- _rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
- {
- DeviceShortCode = deviceDto.ShortCode,
- CloseDevicePush = true,
- });
- return new ConnectResult
- {
- Token = tokenInfo.Code,
- UniqueCode = deviceDto.ShortCode,
- DeviceCode = deviceDto.DeviceCode
- };
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"device connect server failed, err:{ex}");
- throw;
- }
- }
- /// <summary>
- /// Ip转Long
- /// </summary>
- /// <param name="ip"></param>
- /// <returns></returns>
- private long IpToLong(string ip)
- {
- try
- {
- if (System.Net.IPAddress.TryParse(ip, out IPAddress ipAddress))
- {
- char[] separator = new char[] { '.' };
- string[] items = ip.Split(separator);
- var ipLong = long.Parse(items[0]) << 24 | long.Parse(items[1]) << 16 | long.Parse(items[2]) << 8 | long.Parse(items[3]);
- return ipLong;
- }
- // else
- // {
- // Logger.WriteLineWarn($"IpToLong failed, err ip formatter, ip: {ip}");
- // }
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"IpToLong failed, ip: {ip}, ex:{ex}");
- }
- return 0;
- }
- private void SetDeviceMergedOutput(string deviceModel, string cpuModel, DeviceInfoDTO deviceDto)
- {
- var highCpu = _highCpuLevels?.Split(',');
- if (deviceModel.ToUpper().StartsWith("SP002"))
- {
- deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
- }
- else if (highCpu != null && highCpu.Contains(cpuModel))
- {
- deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
- }
- else if (Regex.IsMatch(cpuModel, "[iI][0-9]*-"))
- {
- var matches = Regex.Match(cpuModel, "[iI]([0-9]*)-");
- if (matches.Success)
- {
- int.TryParse(matches.Groups[1].Value, out int cpuLevel);
- if (cpuLevel >= 5)
- {
- deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
- }
- else
- {
- deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
- }
- }
- else
- {
- deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
- }
- }
- else
- {
- deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
- deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
- }
- }
- /// <summary>查询当前设备信息</summary>
- /// <param name="request">请求对象</param>
- /// <returns>设备信息</returns>
- /// <remarks>POST</remarks>
- public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
- cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
- return cacheDeviceInfo;
- }
- /// <summary>设备与云服务断开连接</summary>
- /// <param name="request">请求对象</param>
- /// <returns>是否成功</returns>
- /// <value>true</value>
- public async Task<bool> DisConnectAsync(TokenRequest request)
- {
- try
- {
- await _authenticationService.LogOffAsync(request);
- return true;
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"device disconnect failed, ex:{ex}");
- throw;
- }
- }
- /// <summary>获取设备在线状态</summary>
- /// <param name="deviceCode"></param>
- /// <returns></returns>
- private async Task<bool> GetDeviceOnlineState(string deviceCode)
- {
- var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
- return tokenList.FirstOrDefault()?.IsOnline ?? false;
- }
- /// <summary>生成唯一 shortCode</summary>
- /// <returns></returns>
- private string GenerateShortCode()
- {
- try
- {
- lock (_createShortCodeLocker)
- {
- var uniqueId = new byte[6];
- var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
- for (int i = 0; i < 6; i++)
- {
- int randCode;
- do
- {
- randCode = rand.Next(50, 90);
- uniqueId[i] = Convert.ToByte(randCode);
- } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
- }
- return System.Text.Encoding.ASCII.GetString(uniqueId);
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"GenerateShortCode error {ex}");
- }
- return string.Empty;
- }
- /// <summary>
- /// 设置敏感信息是否加密请求
- /// </summary>
- /// <param name="request">设置敏感信息是否加密请求实体</param>
- /// <returns>是否成功</returns>
- public async Task<bool> SetDeviceIsEncryptedShowAsync(SetDeviceIsEncryptedShowRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- if (deviceDTO == null)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
- }
- deviceDTO.IsEncryptedShow = request.IsEncryptedShow;
- return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDTO.DeviceCode, deviceDTO, string.Empty);
- }
- }
- }
|