123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262 |
- 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;
- namespace WingDeviceService.Service
- {
- /// <summary>
- /// 鉴权服务
- /// </summary>
- public partial class DeviceService : JsonRpcService, IConnectService
- {
- 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 (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");
- }
- 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
- var deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
- 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 = true
- };
- 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;
- deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
- {
- Data = deviceDto
- });
- //创建虚拟机构
- var inventedOrgCode = "invented_" + shortCode;
- var orgData = new TableDataItem<OrganizationDTO>
- {
- Data = new OrganizationDTO
- {
- OrganizationCode = inventedOrgCode,
- RootCode = inventedOrgCode,
- OrganizationName = shortCode,
- OrganizationType = OrganizationTypeEnum.Corporation,
- State = OrganizationStateEnum.Audited,
- RegionCode = "1000000",
- Isinvented = true
- },
- PlatformDatas = new Dictionary<string, string>(),
- ExtensionData = string.Empty,
- };
- await _organizationDBService.CreateOrganizationsAsync(new CreateOrganizationsDBRequest { Infos = new List<TableDataItem<OrganizationDTO>> { orgData } });
- }
- else
- {
- deviceDto.DeviceModel = request.DeviceModel;
- deviceDto.DeviceType = request.DeviceType;
- deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
- deviceDto.SystemVersion = request.SystemVersion;
- deviceDto.CPUModel = request.CPUModel;
- // 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);
- }
- var deviceName = deviceDto.Name;
- if (string.IsNullOrWhiteSpace(deviceName))
- {
- deviceName = deviceDto.ShortCode;
- }
- var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceDto.DeviceCode, ConfigurationManager.Host, 0);
- var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
- if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
- {
- _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
- }
- return new ConnectResult
- {
- Token = tokenInfo.Code,
- UniqueCode = deviceDto.ShortCode
- };
- }
- catch (Exception ex)
- {
- Logger.WriteLineWarn($"device connect server failed, err:{ex}");
- throw;
- }
- }
- /// <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);
- }
- }
- }
|