1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using WingInterfaceLibrary.DTO.Device;
- using WingInterfaceLibrary.Interface;
- using WingInterfaceLibrary.Request.Device;
- using WingInterfaceLibrary.DTO.Dictionary;
- using WingServerCommon.Log;
- using WingServerCommon.Service;
- using WingInterfaceLibrary.Interface.DBInterface;
- using WingInterfaceLibrary.DB.Request;
- using WingServerCommon.Mapper;
- using WingInterfaceLibrary.Request;
- using WingInterfaceLibrary.Request.Authentication;
- using WingInterfaceLibrary.DTO.User;
- using WingInterfaceLibrary.DTO.Management;
- using WingServerCommon.Config;
- using WingDeviceService.Common;
- using WingInterfaceLibrary.Request.User;
- using WingInterfaceLibrary.Enum;
- using WingInterfaceLibrary.DTO.Organization;
- using WingInterfaceLibrary.DTO.DiagnosisModule;
- using WingServerCommon.Config.Parameters;
- using WingServerCommon.Interfaces.Cache;
- using WingInterfaceLibrary.LiveConsultation;
- using WingInterfaceLibrary.Result.Languge;
- using WingInterfaceLibrary.Internal.Interface;
- using WingInterfaceLibrary.Notifications;
- using WingInterfaceLibrary.Internal.Request;
- using WingInterfaceLibrary.Rtc;
- using WingInterfaceLibrary.Enum.CommentEnum;
- using WingInterfaceLibrary.DTO.RTC;
- using Newtonsoft.Json;
- using WingInterfaceLibrary.Notifications.Live;
- using WingInterfaceLibrary.Enum.NotificationEnum;
- using WingInterfaceLibrary.DTO.LiveRoom;
- using WingInterfaceLibrary.Request.DBRequest;
- using WingInterfaceLibrary.DTO.Record;
- using WingInterfaceLibrary.DTO.Consultation;
- using WingServerCommon.Interfaces.Cache;
- using System.Collections.Concurrent;
- namespace WingDeviceService.Service
- {
- /// <summary>
- /// 设备管理服务
- /// </summary>
- public partial class DeviceService : JsonRpcService, IDeviceService
- {
- private ConcurrentDictionary<string, CacheControllingParameter> _controllingParameterDevices = new ConcurrentDictionary<string, CacheControllingParameter>();
- private IUserDBService _userServiceProxy;
- private IDeviceInfoDBService _deviceInfoDBServiceProxy;
- private IAuthenticationService _authenticationService;
- private IOrganizationDBService _organizationDBService;
- private INotificationService _notificationService;
- private IRecordsInfoDBService _recordsInfoDBService;
- private IPatientInfoDBService _patientInfoDBService;
- private IDiagnosisModuleDBService _diagnosisModuleService;
- private IRemedicalService _remedicalService;
- private IWingRtcService _wingRtcService;
- private IRtcService _rtcService;
- private int _heartRateSeconds;
- private DeviceHeartRateManager _deviceHeartRateManager;
- private string _webSocketUrl = string.Empty;
- private int _liveConsultationRateSeconds = 0;
- private bool _isRTCSelf = false;
- private int _sdkAppId = 0;
- private int _remoteControlAskTimeoutSec = 0;
- private int _reportStateIntervalSeconds = 0;
- private int _reportStateTimeout = 0;
- private ILiveConsultationService _liveConsultationService;
- private IConsultationRecordDBService _consultationRecordDBService;
- private IRemedicalDBService _remedicalDBService;
- /// <summary>
- /// Init service
- /// </summary>
- public override void Load(JsonRpcClientPool jsonRpcClientPool)
- {
- base.Load(jsonRpcClientPool);
- _userServiceProxy = GetProxy<IUserDBService>();
- _authenticationService = GetProxy<IAuthenticationService>();
- _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
- _organizationDBService = GetProxy<IOrganizationDBService>();
- _notificationService = GetProxy<INotificationService>();
- _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
- _patientInfoDBService = GetProxy<IPatientInfoDBService>();
- _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
- _remedicalService = GetProxy<IRemedicalService>();
- _wingRtcService = GetProxy<IWingRtcService>();
- _rtcService = GetProxy<IRtcService>();
- _liveConsultationService = GetProxy<ILiveConsultationService>();
- _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
- _remedicalDBService = GetProxy<IRemedicalDBService>();
- _heartRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
- _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
- _webSocketUrl = ConfigurationManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
- _liveConsultationRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "HeartRateSeconds").Value;
- _isRTCSelf = ConfigurationManager.GetParammeter<BoolParameter>("Rtc", "IsSelf").Value;
- var sdkAppIdString = ConfigurationManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
- if (int.TryParse(sdkAppIdString, out int sdkAppId))
- {
- _sdkAppId = sdkAppId;
- }
- _remoteControlAskTimeoutSec = ConfigurationManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
- var _reportStateIntervalSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateIntervalSeconds").Value;
- var _reportStateTimeout = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateTimeout").Value;
- }
- /// <summary>
- /// 设备心跳
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> HeartRateAsync(TokenRequest request)
- {
- _deviceHeartRateManager.AddOrUpdate(request.Token);
- var result = SetOnlineState(request.Token, true);
- return result;
- }
- private bool SetOnlineState(string token, bool isOnline)
- {
- return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
- }
- /// <summary>
- /// 添加分享设备关联用户请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
- {
- var userCodes = request.UserCodes;
- var deviceCode = request.DeviceCode;
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- if (userCodes == null || userCodes.Count <= 0)
- {
- ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
- }
- //查询设备对象
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- foreach (var userCode in userCodes)
- {
- var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (existUser == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- }
- await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
- {
- DeviceCodes = new List<string> { deviceCode },
- UserCodes = userCodes.ToList()
- });
- return true;
- }
- /// <summary>
- /// 根据设备code获取设备信息
- /// </summary>
- /// <param name="request">设备code请求实体</param>
- /// <returns>返回查询到的设备对象信息</returns>
- public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
- {
- //验证
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
- }
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- //根据机构编号查询机构名称
- var organizationName = "";
- if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
- {
- var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
- organizationName = organization?.OrganizationName ?? string.Empty;
- }
- //根据机构编号查询科室名称
- var departmentName = "";
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
- departmentName = department?.OrganizationName ?? string.Empty;
- }
- //是否在线 todo
- var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
- var result = new DeviceExtendInfoDTO()
- {
- DepartmentName = departmentName,
- OrganizationName = organizationName,
- IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
- DeviceCode = deviceDb.DeviceCode,
- SerialNumber = deviceDb.SerialNumber,
- Name = deviceDb.Name,
- Description = deviceDb.Description,
- DeviceModel = deviceDb.DeviceModel,
- DeviceType = deviceDb.DeviceType,
- HeadPicUrl = deviceDb.HeadPicUrl,
- DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
- SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
- OrganizationCode = deviceDb.OrganizationCode,
- DepartmentCode = deviceDb.DepartmentCode,
- ShortCode = deviceDb.ShortCode,
- LanguageConfigs = deviceTypeModel.LanguageConfigs
- };
- return result;
- }
- /// <summary>
- /// 根据设备动态唯一码获取设备信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
- {
- //验证
- if (string.IsNullOrWhiteSpace(request.ShortCode))
- {
- ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
- }
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
- if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- return await MapToExtendDTO(deviceDb);
- }
- public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
- {
- throw new System.NotImplementedException();
- }
- public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
- {
- var userCodes = request.UserCodes;
- var deviceCode = request.DeviceCode;
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- //用户编码集合检查
- if (userCodes == null || userCodes.Count <= 0)
- {
- ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
- }
- //查询设备对象
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
- foreach (var userCode in userCodes)
- {
- var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (user != null)
- {
- if (user.BindDevices.Contains(deviceCode))
- {
- user.BindDevices.Remove(deviceCode);
- updateUsers.Add(new TableDataItem<UserPasswordDTO>()
- {
- Data = user.MappingTo<UserPasswordDTO>(),
- });
- }
- }
- }
- if (updateUsers.Count > 0)
- {
- var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
- await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
- }
- return true;
- }
- /// <summary>
- /// 机构设备移除-根据机构code和设备code解除其绑定关系
- /// </summary>
- /// <param name="request">移除设备请求实体</param>
- /// <returns>移除是否成功:true-成功;false-失败</returns>
- public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
- {
- //验证
- if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
- }
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
- }
- //根据设备code和机构code查询相关数据,查到则删除关联
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- deviceDb.DepartmentCode = "";
- deviceDb.OrganizationCode = "";
- }
- else
- {
- deviceDb.OrganizationCode = "";
- }
- bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
- return removeDeviceResult;
- }
- private async Task<string> GetClientIdByTokenAsync(string token)
- {
- var request = new TokenRequest() { Token = token };
- var result = await _authenticationService.GetTokenAsync(request);
- return result.ClientId; //return User code
- }
- /// <summary>
- /// 查询个人名下所有设备列表接口
- /// </summary>
- /// <param name="request">查询个人名下所有设备列表请求实体</param>
- /// <returns>返回设备信息列表</returns>
- public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
- {
- //验证
- var userCode = await GetClientIdByTokenAsync(request.Token);
- //查询用户是否存在
- var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userInfoDO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- //查询用户的医院是否存在
- if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
- }
- var deviceInfoDOList = new List<DeviceInfoDTO>();
- if (!userInfoDO.IsDirector)
- {
- //普通用户,查询用户绑定的设备
- if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
- {
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
- }
- }
- else
- {
- //机构负责人
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
- }
- if (!deviceInfoDOList.Any())
- {
- return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
- }
- var deviceList = await MapToExtendDTO(deviceInfoDOList);
- //条件筛选
- if (!string.IsNullOrWhiteSpace(request.DeviceType))
- {
- deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceExtendInfoDTO>();
- }
- if (!string.IsNullOrWhiteSpace(request.DeviceModel))
- {
- deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceExtendInfoDTO>();
- }
- if (!string.IsNullOrWhiteSpace(request.KeyWord))
- {
- var keyword = request.KeyWord.Trim().ToLower();
- deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List<DeviceExtendInfoDTO>();
- }
- if (request.IsOnline != null)
- {
- deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List<DeviceExtendInfoDTO>();
- }
- var pagedResult = new PageCollection<DeviceExtendInfoDTO>
- {
- CurrentPage = request.PageIndex,
- PageSize = request.PageSize,
- DataCount = deviceList.Count,
- PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
- };
- return pagedResult;
- }
- /// <summary>
- /// 绑定设备
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
- {
- //验证
- var userCode = await GetClientIdByTokenAsync(request.Token);
- //查询用户是否存在
- var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userInfoDO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
- }
- if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
- }
- try
- {
- var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
- deviceDb.Name = request.Name;
- deviceDb.SerialNumber = request.SerialNumber;
- deviceDb.Description = request.Description;
- if (!string.IsNullOrEmpty(request.HeadPicUrl))
- {
- deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
- }
- deviceDb.DepartmentCode = request.DepartmentCode;
- deviceDb.IsAutoShared = request.IsAutoShared;
- deviceDb.OrganizationCode = request.OrganizationCode;
- await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
- if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
- {
- var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
- //迁移数据超声机上传检查记录
- await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
- //迁移数据超声机上传病人
- await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
- }
- if (deviceDb.IsAutoShared)
- {
- var users = new List<UserDTO>();
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
- }
- else
- {
- users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
- }
- var userCodes = users.Select(f => f.UserCode).ToList();
- await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
- {
- DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
- UserCodes = userCodes.Select(f => f.ToString()).ToList()
- });
- }
- return true;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"BindDeviceAsync error {ex}");
- }
- return false;
- }
- /// <summary>
- /// 修改设备
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
- {
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
- }
- if (string.IsNullOrWhiteSpace(request.Name))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
- }
- deviceDb.Name = request.Name;
- if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
- {
- deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
- }
- else
- {
- deviceDb.HeadPicUrl = string.Empty;
- }
- deviceDb.DepartmentCode = request.DepartmentCode;
- //修改自动分享
- deviceDb.IsAutoShared = request.IsAutoShared;
- if (deviceDb.IsAutoShared)
- {
- var users = new List<UserDTO>();
- if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
- {
- users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
- }
- else
- {
- users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
- }
- var userCodes = users.Select(f => f.UserCode).ToList();
- //先解绑,再绑定,避免绑定重复设备code
- var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
- foreach (var user in users)
- {
- var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
- user.BindDevices?.Remove(deviceDb.DeviceCode);
- await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
- }
- await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
- {
- DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
- UserCodes = userCodes.Select(f => f.ToString()).ToList()
- });
- }
- return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
- }
- /// <summary>
- /// 创建字典
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
- {
- return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
- {
- Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
- ExtensionData = string.Empty
- });
- }
- /// <summary>
- /// 查找设备型号所有字典项
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
- {
- var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
- {
- DictionaryType = (int)request.DictionaryType,
- ParentCode = request.DeviceTypeCode
- });
- return dictionaryDOList;
- }
- /// <summary>
- /// 查找设备类型所有字典项
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
- {
- var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
- {
- DictionaryType = (int)request.DictionaryType
- });
- return dictionaryDOList;
- }
- /// <summary>
- /// 根据组织编码查询所属全部设备信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
- {
- var result = new List<DeviceExtendInfoDTO>();
- var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
- if (deviceInfoDOList?.Count > 0)
- {
- //根据机构编号查询机构名称
- var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
- var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
- var organizationName = organization?.OrganizationName ?? string.Empty;
- //根据机构编号查询科室名称
- var organizationFilter = new Dictionary<string, string>();
- organizationFilter.Add("RootCode", organizationCode);
- var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
- var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
- var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
- var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
- foreach (var c in deviceInfoDOList)
- {
- var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
- result.Add(new DeviceExtendInfoDTO
- {
- DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
- OrganizationName = organizationName,
- IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
- DeviceCode = c.DeviceCode,
- SerialNumber = c.SerialNumber,
- Name = c.Name,
- Description = c.Description,
- DeviceModel = c.DeviceModel,
- DeviceType = c.DeviceType,
- HeadPicUrl = c.HeadPicUrl,
- DeviceSoftwareVersion = c.DeviceSoftwareVersion,
- SDKSoftwareVersion = c.SDKSoftwareVersion,
- OrganizationCode = c.OrganizationCode,
- DepartmentCode = c.DepartmentCode,
- ShortCode = c.ShortCode,
- LanguageConfigs = deviceTypeModel?.LanguageConfigs
- });
- }
- }
- return result;
- }
- public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
- {
- throw new NotImplementedException();
- }
- public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
- {
- //验证
- var userCode = await GetClientIdByTokenAsync(request.Token);
- //查询用户是否存在
- var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userInfoDO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- var result = new List<SelectItemDTO>();
- //查询用户的医院是否存在
- if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
- }
- var deviceInfoDOList = new List<DeviceInfoDTO>();
- if (userInfoDO.IsDirector)
- {
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
- }
- else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
- {
- //查询用户绑定的设备
- if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
- {
- return result;
- }
- //根据用户名下的设备id查询所有的设备信息
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
- }
- else
- {
- var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
- if (experts.Any())
- {
- var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
- if (bindDeviceCodes.Any())
- {
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
- }
- }
- else
- {
- deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
- }
- }
- if (deviceInfoDOList?.Count > 0)
- {
- result = deviceInfoDOList.Select(c => new SelectItemDTO()
- {
- Key = c.DeviceCode,
- Value = c.Name
- }).ToList();
- }
- return result;
- }
- /// <summary>
- /// 设备端调用,查询获取服务器配置信息接口
- /// </summary>
- /// <param name="request">Token验证</param>
- /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
- public async Task<DeviceServerSettingResult> QueryServerConfigAsync(TokenRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- var org = new OrganizationDTO();
- if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
- {
- org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
- if (org == null)
- {
- org = new OrganizationDTO();
- }
- }
- var dictionary = new Dictionary<string, string>();
- //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
- //TODO 配置信息: 直播配置、存储配置、
- //存储上传图像或者视频是 是否本地上传缩略图
- var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
- dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
- dictionary.Add("PatientType", org.PatientType.ToString());
- dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
- dictionary.Add("NotificationUrl", _webSocketUrl);
- dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
- dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
- var result = new DeviceServerSettingResult()
- {
- ServerConfigList = dictionary,
- IsUploadThumbnail = isUploadThumbnail,
- PatientType = org.PatientType,
- HeartRateSeconds = _heartRateSeconds,
- NotificationUrl = _webSocketUrl,
- LiveConsultationRateSeconds = _liveConsultationRateSeconds,
- MergedChannel = deviceInfo.MergedChannel,
- MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
- MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
- IsSelfRtcService = _isRTCSelf,
- RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec
- };
- return result;
- }
- /// <summary>
- /// 添加或迁移设备到医院请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
- {
- var shortCode = request.UniqueCode;
- #region Params Check
- var userCode = await GetClientIdByTokenAsync(request.Token);
- if (string.IsNullOrEmpty(shortCode))
- {
- ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
- }
- var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
- if (device == null)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
- if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
- }
- //用户
- var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userDTO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- if (!userDTO.IsDirector)
- {
- ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
- }
- var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
- if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
- {
- ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
- }
- #endregion
- try
- {
- var newOrgode = org.OrganizationCode;
- //设备更新医院
- if (!string.IsNullOrEmpty(device.DepartmentCode))
- {
- device.DepartmentCode = "";
- }
- if (!string.IsNullOrEmpty(device.Name))
- {
- device.Name = "";
- }
- device.HeadPicUrl = "";
- device.Description = "";
- device.IsAutoShared = false;
- device.OrganizationCode = newOrgode;
- bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
- if (success)
- {
- // 删除已知绑定的用户
- var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
- var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
- foreach (var user in users)
- {
- user.BindDevices.Remove(device.DeviceCode);
- updateUsers.Add(new TableDataItem<UserPasswordDTO>()
- {
- Data = user.MappingTo<UserPasswordDTO>(),
- });
- }
- if (updateUsers.Count > 0)
- {
- var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
- await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
- }
- if (oldOrg.Isinvented) // 虚拟医院
- {
- //迁移数据超声机上传检查记录
- await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
- //迁移数据超声机上传病人
- await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
- }
- }
- return success;
- }
- catch (System.Exception ex)
- {
- Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
- }
- return false;
- }
- /// <summary>
- /// 补齐设备扩展信息
- /// </summary>
- /// <param name="deviceInfoDOList"></param>
- /// <returns></returns>
- private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
- {
- var deviceList = new List<DeviceExtendInfoDTO>();
- if (deviceInfoDOList != null && deviceInfoDOList.Any())
- {
- //查询机构
- var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
- orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
- var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
- //查询机构负责人
- var organizationDirectorCodes = new List<string>();
- foreach (var org in organizations)
- {
- if (org.Directors != null && org.Directors.Any())
- {
- organizationDirectorCodes.AddRange(org.Directors);
- }
- }
- var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
- var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
- var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
- var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
- foreach (var dto in deviceInfoDOList)
- {
- var device = dto.MappingTo<DeviceExtendInfoDTO>();
- device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
- device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
- device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
- var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
- if (organization != null)
- {
- device.OrganizationName = organization.OrganizationName;
- if (organization.Directors != null && organization.Directors.Any())
- {
- var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
- device.OrganizationDirectorCode = director?.UserCode;
- device.OrganizationDirectorUserName = director?.UserName;
- device.OrganizationDirectorFullName = director?.FullName;
- }
- }
- deviceList.Add(device);
- }
- }
- return deviceList;
- }
- /// <summary>
- /// 补齐设备扩展信息
- /// </summary>
- /// <param name="deviceInfoDOList"></param>
- /// <returns></returns>
- private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
- {
- var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
- return deviceList.FirstOrDefault();
- }
- /// <summary>
- /// 获取设备绑定用户codes
- /// </summary>
- /// <param name="request">获取设备绑定用户codes请求实体</param>
- /// <returns>test01,test02</returns>
- public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
- {
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- //查询设备对象
- var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
- if (deviceDb == null)
- {
- ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
- }
- var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
- if (userListResult != null && userListResult.Count > 0)
- {
- return userListResult.Select(u => u.UserCode).ToList();
- }
- return new List<string>();
- }
- /// <summary>
- /// 查询设备AI应用的状态
- /// </summary>
- /// <param name="request">请求参数</param>
- /// <returns>AI应用集合</returns>
- public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
- {
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
- }
- /// <summary>
- /// 修改设备AI应用启用状态
- /// </summary>
- /// <param name="request">修改设备AI应用启用状态请求实体</param>
- /// <returns>是否成功</returns>
- /// <para>DeviceErrorCodeEnum</para>
- public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
- {
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(request.DeviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
- }
- var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
- {
- DeviceCode = request.DeviceCode,
- DiagnosisModule = request.DiagnosisModule,
- Enabled = request.Enabled
- });
- CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
- return result;
- }
- /// <summary>
- /// 设备离开会诊房间
- /// </summary>
- /// <param name="request">设备离开会诊房间请求实体</param>
- /// <returns></returns>
- public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var result = new DeviceLeaveLiveConsultationResult
- {
- Success = false,
- };
- return result;
- }
- /// <summary>
- /// 通用异常处理方法
- /// </summary>
- /// <param name="customerRpcCodeEnum">异常标识码</param>
- /// <param name="msg">异常信息</param>
- /// <param name="internalMessage">内部异常信息,非必填</param>
- private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
- {
- ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
- }
- /// <summary>
- /// 上报设备画面尺寸相关信息
- /// </summary>
- /// <param name="request"></param>
- /// <docFirstDirectory>设备端API</docFirstDirectory>
- /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
- /// <docThirdDirectory>会诊</docThirdDirectory>
- /// <returns></returns>
- public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
- {
- var result = new ReportVideoDeviceInfoResult();
- if (request.VideoDeviceInfos == null || request.VideoDeviceInfos.Count == 0)
- {
- //视屏设备画面信息为空
- ThrowCustomerException(CustomerRpcCode.VideoDeviceInfosEmpty, "VideoDeviceInfosEmpty");
- }
- if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
- {
- //视屏设备ID为空
- ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
- }
- var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
- if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
- {
- //视屏设备ID重复
- ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
- }
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- var videoDeviceInfos = new List<VideoDeviceDTO>();
- foreach (var video in request.VideoDeviceInfos)
- {
- var videoDeviceInfo = new VideoDeviceDTO
- {
- VideoDeviceId = video.VideoDeviceId,
- VideoDeviceSourceType = video.VideoDeviceSourceType,
- Width = video.Width,
- Height = video.Height,
- OutputWidth = video.Width,
- OutputHeight = video.Height,
- VideoFps = video.VideoFps,
- VideoBitrate = video.VideoBitrate,
- MinVideoBitrate = video.MinVideoBitrate
- };
- videoDeviceInfos.Add(videoDeviceInfo);
- }
- deviceDTO.VideoDeviceInfos = videoDeviceInfos;
- var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
- {
- DeviceCode = deviceDTO.DeviceCode,
- LiveOpened = request.LiveOpened,
- VideoDeviceInfos = videoDeviceInfos
- };
- await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
- CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(deviceDTO.DeviceCode);
- result.Success = true;
- result.VideoDeviceOutputInfos = videoDeviceInfos;
- return result;
- }
- /// <summary>
- /// 查找有效设备总数量
- /// </summary>
- /// <returns></returns>
- public async Task<long> GetActiveDeviceCount()
- {
- return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
- }
- /// <summary>
- /// 设备发送调参初始化数据
- /// </summary>
- /// <param name="request">调参数据请求</param>
- /// <returns></returns>
- public async Task<bool> SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
- {
- var deviceCode = await GetClientIdByTokenAsync(request.Token);
- var userCode = request.ControlUserCode;
- //发送控制人通知
- if (string.IsNullOrWhiteSpace(userCode))
- {
- ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
- }
- var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userDTO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- var notify = new DeviceParametersNotification()
- {
- DeviceCode = deviceCode,
- IsResponse = true
- };
- var cacheControllingParameter = new CacheControllingParameter()
- {
- Code = deviceCode,
- ProbeApplication = Newtonsoft.Json.JsonConvert.SerializeObject(request.ProbeApplication),
- Parameter = Newtonsoft.Json.JsonConvert.SerializeObject(request.Parameter),
- };
- _controllingParameterDevices.AddOrUpdate(deviceCode, (k) => cacheControllingParameter, (k, exist) =>
- {
- return cacheControllingParameter;
- });
- var notificationRequest = new SendNotificationRequest()
- {
- ClientId = userCode,
- Message = notify,
- JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
- NotificationType = notify.NotificationType,
- TransactionType = TransactionTypeEnum.ControlParameter,
- RelevanceCode = userCode,
- ReceiverType = ApplicantTypeEnum.Client
- };
- await _notificationService.PostMessageAsync(notificationRequest);
- return true;
- }
- /// <summary>
- /// 获取设备参数调节数据请求
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<DeviceControlParameterDataDTO> GetControlParametersAsync(GetControlParametersRequest request)
- {
- var deviceCode = request.DeviceCode;
- //检查设备编码不为空
- if (string.IsNullOrWhiteSpace(deviceCode))
- {
- ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
- }
- _controllingParameterDevices.TryGetValue(deviceCode, out var controlParameterData);
- if (controlParameterData != null)
- {
- return new DeviceControlParameterDataDTO()
- {
- DeviceCode = controlParameterData.Code,
- ProbeApplication = controlParameterData.ProbeApplication,
- Parameter = controlParameterData.Parameter
- };
- }
- return null;
- }
- /// <summary>
- /// 用户进入设备直播房间
- /// </summary>
- /// <param name="request">用户进入设备直播房间请求实体</param>
- /// <returns></returns>
- public async Task<JoinDeviceLiveRoomResult> JoinDeviceLiveRoomAsync(JoinDeviceLiveRoomRequest request)
- {
- var userInfo = await _authenticationService.GetTokenAsync(request);
- var deviceCode = request.DeviceCode;
- var deviceInfo = CacheMaintenance.Instance.Get<IDeviceInfosManager>().Get(deviceCode);
- var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
- {
- DeviceCode = deviceCode
- });
- LiveMemberDTO deviceMemberInfo;
- if (liveRoom != null)
- {
- if (liveRoom.LiveRoomCode == deviceCode)
- {
- //设备正在推流
- deviceMemberInfo = liveRoom.DeviceInfos.FirstOrDefault(x => x.Code == deviceCode);
- if (deviceMemberInfo?.Status == LiveMemberStatus.Joined)
- {
- //添加观众
- await _rtcService.SaveViewerAsync(new SaveViewerRequest
- {
- LiveRoomCode = liveRoom.LiveRoomCode,
- UserCode = userInfo.ClientId,
- UserName = userInfo.AccountName,
- });
- return new JoinDeviceLiveRoomResult
- {
- RoomNo = liveRoom.RtcRoomId,
- RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
- };
- }
- }
- }
- //新增或更新设备直播间
- var deviceName = !string.IsNullOrWhiteSpace(deviceInfo.Name) ? deviceInfo.Name : deviceInfo.ShortCode;
- var deviceLiveInfo = new LiveMemberDTO
- {
- Code = deviceCode,
- Name = deviceName,
- MemberType = LiveMemberEnum.Device,
- HeadImageToken = deviceInfo.HeadPicUrl,
- Status = LiveMemberStatus.Accepted,
- };
- var room = new LiveRoomDTO
- {
- LiveRoomCode = deviceCode,
- Name = deviceName,
- RelatedCode = deviceCode,
- BusinessModule = BusinessModuleEnum.LivingConsultation,
- Status = LiveRoomStatus.Default,
- UserInfos = new List<LiveMemberDTO>(),
- DeviceInfos = new List<LiveMemberDTO> { deviceLiveInfo }
- };
- await _rtcService.AddOrUpdateLiveRoomAsync(new AddOrUpdateLiveRoomRequest
- {
- LiveRoom = room,
- });
- var initiateResult = await _rtcService.InitiateAsync(new InitiateRequest
- {
- LiveRoomCode = deviceCode,
- InitiatorCode = deviceCode,
- });
- deviceMemberInfo = initiateResult.DeviceInfos.FirstOrDefault(x => x.Code == deviceCode);
- //添加观众
- await _rtcService.SaveViewerAsync(new SaveViewerRequest
- {
- LiveRoomCode = initiateResult.LiveRoomCode,
- UserCode = userInfo.ClientId,
- UserName = userInfo.AccountName,
- });
- return new JoinDeviceLiveRoomResult
- {
- RoomNo = initiateResult.RtcRoomId,
- RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
- ReportStateIntervalSeconds = _reportStateIntervalSeconds,
- };
- }
- /// <summary>
- /// 用户离开设备直播房间
- /// </summary>
- /// <param name="request">用户离开设备直播房间请求实体</param>
- /// <returns></returns>
- public async Task<bool> LeaveDeviceLiveRoomAsync(LeaveDeviceLiveRoomRequest request)
- {
- var userInfo = await _authenticationService.GetTokenAsync(request);
- var userCode = userInfo.ClientId;
- var deviceCode = request.DeviceCode;
- var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
- {
- DeviceCode = deviceCode
- });
- if (liveRoom != null)
- {
- //移除观众
- var removeViewerResult = await _rtcService.RemoveViewerAsync(new RemoveViewerRequest
- {
- LiveRoomCode = liveRoom.LiveRoomCode,
- UserCode = userInfo.ClientId,
- });
- var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
- if (!liveRoom.ViewerInfos.Any(x => x.UserCode != userCode && x.LastReportTime >= expireTime))
- {
- await _rtcService.CloseAsync(new CloseRequest
- {
- LiveRoomCode = liveRoom.LiveRoomCode
- });
- }
- }
- return true;
- }
- /// <summary>
- /// 上报观看直播状态
- /// </summary>
- /// <param name="request">上报观看直播状态请求实体</param>
- /// <returns></returns>
- public async Task<bool> ReportLiveViewStateAsync(ReportLiveViewStateRequest request)
- {
- var userInfo = await _authenticationService.GetTokenAsync(request);
- var deviceCode = request.DeviceCode;
- var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
- {
- DeviceCode = deviceCode
- });
- if (liveRoom != null)
- {
- //添加观众
- var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
- {
- LiveRoomCode = liveRoom.LiveRoomCode,
- UserCode = userInfo.ClientId,
- UserName = userInfo.AccountName,
- });
- }
- return true;
- }
- /// <summary>
- /// 上报直播状态
- /// </summary>
- /// <param name="request">上报直播状态请求实体</param>
- /// <returns></returns>
- public async Task<bool> ReportLiveStateAsync(ReportLiveStateRequest request)
- {
- var tokenInfo = await _authenticationService.GetTokenAsync(request);
- var deviceCode = tokenInfo.ClientId;
- switch (request.LiveState)
- {
- case DeviceLiveStateEnum.Error:
- case DeviceLiveStateEnum.Warning:
- Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
- break;
- default:
- Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
- break;
- }
- if (request.LiveState == DeviceLiveStateEnum.Pushing || request.LiveState == DeviceLiveStateEnum.Closed)
- {
- var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
- {
- DeviceCode = deviceCode
- });
- if (liveRoom != null)
- {
- var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
- var validViewers = liveRoom.ViewerInfos.Where(x => x.LastReportTime >= expireTime)?.ToList() ?? new List<LiveViewerDTO>();
- if (request.LiveState == DeviceLiveStateEnum.Closed && validViewers.Any())
- {
- //关闭直播 to users
- var message = new DeviceLiveFinishedNotification
- {
- LiveRoomCode = liveRoom.LiveRoomCode,
- };
- await BroadcastNotificationAsync(liveRoom.LiveRoomCode, validViewers.Select(x => x.UserCode).ToList(), message);
- }
- if (request.LiveState == DeviceLiveStateEnum.Pushing && !validViewers.Any())
- {
- await _rtcService.CloseAsync(new CloseRequest
- {
- LiveRoomCode = liveRoom.LiveRoomCode
- });
- }
- }
- }
- return await Task.FromResult(true);
- }
- /// <summary>
- /// 获取实时音视频参数
- /// </summary>
- /// <param name="request">获取实时音视频参数请求实体</param>
- /// <returns></returns>
- public async Task<CreateLiveRoomInfoResult> CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
- {
- Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
- var userCode = Guid.NewGuid().ToString("N");
- var getUserSignRequest = new GetUserSignRequest
- {
- UserId = userCode,
- };
- var getUserSignResult = await _wingRtcService.GetUserSignAsync(getUserSignRequest);
- var userSign = getUserSignResult.UserSign;
- var getRoomIdRequest = new GetRoomIdRequest
- {
- UniqueId = userCode,
- };
- var getRoomIdResult = await _wingRtcService.GetRoomIdAsync(getRoomIdRequest);
- var intRoomNo = (int)getRoomIdResult.RoomId;
- Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
- return new CreateLiveRoomInfoResult
- {
- IsTrtc = !_isRTCSelf,
- UserCode = userCode,
- UserSign = userSign,
- AppId = _sdkAppId,
- RoomNo = intRoomNo,
- };
- }
- private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> clientIds, NotificationDTO message)
- {
- var broadcastNotificationRequest = new BroadcastNotificationRequest
- {
- ClientIds = clientIds,
- Message = message,
- TransactionType = TransactionTypeEnum.Live,
- RelevanceCode = roomId,
- ReceiverType = ApplicantTypeEnum.Client,
- WSConnectType = WSConnectTypeEnum.Default
- };
- return await _notificationService.BroadcastMessageAsync(broadcastNotificationRequest);
- }
- /// <summary>
- /// 拒绝远程控制
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> RejectRemoteControl(RemoteControlRequest request)
- {
- string deviceCode = await GetClientIdByTokenAsync(request.Token);
- string userCode = request.ControlUserCode;
- //发送控制人通知
- if (string.IsNullOrWhiteSpace(userCode))
- {
- ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
- }
- var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userDTO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- var notify = new DeviceRejectRemoteControlNotification()
- {
- DeviceCode = deviceCode,
- };
- var notificationRequest = new SendNotificationRequest()
- {
- ClientId = userCode,
- Message = notify,
- JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
- NotificationType = notify.NotificationType,
- TransactionType = TransactionTypeEnum.RemoteControl,
- RelevanceCode = userCode,
- ReceiverType = ApplicantTypeEnum.Client
- };
- await _notificationService.PostMessageAsync(notificationRequest);
- //更改房间调参状态
- // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
- // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
- // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
- // {
- // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
- // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
- // }
- var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
- await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
- return true;
- }
- /// <summary>
- /// 断开远程控制
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> DisconnectRemoteControl(RemoteControlRequest request)
- {
- string deviceCode = await GetClientIdByTokenAsync(request.Token);
- string userCode = request.ControlUserCode;
- //发送控制人通知
- if (string.IsNullOrWhiteSpace(userCode))
- {
- ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
- }
- var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
- if (userDTO == null)
- {
- ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
- }
- var notify = new DeviceDisconnectRemoteControlNotification()
- {
- DeviceCode = deviceCode,
- };
- var notificationRequest = new SendNotificationRequest()
- {
- ClientId = userCode,
- Message = notify,
- JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
- NotificationType = notify.NotificationType,
- TransactionType = TransactionTypeEnum.RemoteControl,
- RelevanceCode = userCode,
- ReceiverType = ApplicantTypeEnum.Client
- };
- await _notificationService.PostMessageAsync(notificationRequest);
- //更改房间调参状态
- // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
- // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
- // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
- // {
- // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
- // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
- // }
- var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
- await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
- return true;
- }
- public async Task<bool> UploadConsultationDataAsync(UploadConsultationDataRequest request)
- {
- var deviceInfo = await GetDeviceByTokenAsync(request);
- var consultationCode = request.ConsultationCode;
- if (string.IsNullOrWhiteSpace(consultationCode))
- {
- ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
- }
- if (string.IsNullOrWhiteSpace(request.FileToken))
- {
- ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
- }
- var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
- var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
- if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
- {
- ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
- }
- var dataDTO = new RemedicalInfoDTO();
- dataDTO.DeviceCode = deviceInfo.DeviceCode;
- dataDTO.RecordCode = consultationRecord.ConsultationCode;
- dataDTO.ApplicationCategory = request.ApplicationCategory;
- dataDTO.Application = request.Application;
- dataDTO.TerminalImages = new TerminalImageDTO();
- var originImageUrl = request.FileToken;
- dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
- dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
- dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
- dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
- dataDTO.TerminalImages.ImageSize = request.FileSize;
- dataDTO.FileDataType = request.FileDataType;
- dataDTO.MeasuredResult = request.MeasuredResult;
- dataDTO.CommentResult = request.CommentResult;
- dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
- dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
- //更新会诊记录
- if (consultationRecord.ConsultationFileList == null)
- {
- consultationRecord.ConsultationFileList = new List<ConsultationFileDTO>();
- }
- var consultationFileDTO = new ConsultationFileDTO
- {
- SourceUrl = originImageUrl,
- CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
- PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
- FileDataType = request.FileDataType,
- CreateTime = DateTime.UtcNow,
- ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
- RemedicalCode = dataDTO.RemedicalCode
- };
- consultationRecord.ConsultationFileList.Add(consultationFileDTO);
- var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
- return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
- }
- }
- }
|