DeviceService.cs 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using WingInterfaceLibrary.DTO.Device;
  6. using WingInterfaceLibrary.Interface;
  7. using WingInterfaceLibrary.Request.Device;
  8. using WingInterfaceLibrary.DTO.Dictionary;
  9. using WingServerCommon.Log;
  10. using WingServerCommon.Service;
  11. using WingInterfaceLibrary.Interface.DBInterface;
  12. using WingInterfaceLibrary.DB.Request;
  13. using WingServerCommon.Mapper;
  14. using WingInterfaceLibrary.Request;
  15. using WingInterfaceLibrary.Request.Authentication;
  16. using WingInterfaceLibrary.DTO.User;
  17. using WingInterfaceLibrary.DTO.Management;
  18. using WingServerCommon.Config;
  19. using WingDeviceService.Common;
  20. using WingInterfaceLibrary.Request.User;
  21. using WingInterfaceLibrary.Enum;
  22. using WingInterfaceLibrary.DTO.Organization;
  23. using WingInterfaceLibrary.DTO.DiagnosisModule;
  24. using WingServerCommon.Config.Parameters;
  25. using WingServerCommon.Interfaces.Cache;
  26. using WingInterfaceLibrary.LiveConsultation;
  27. using WingInterfaceLibrary.Result.Languge;
  28. using WingInterfaceLibrary.Internal.Interface;
  29. using WingInterfaceLibrary.Notifications;
  30. using WingInterfaceLibrary.Internal.Request;
  31. using WingInterfaceLibrary.Rtc;
  32. using WingInterfaceLibrary.Enum.CommentEnum;
  33. using WingInterfaceLibrary.DTO.RTC;
  34. using Newtonsoft.Json;
  35. using WingInterfaceLibrary.Notifications.Live;
  36. using WingInterfaceLibrary.Enum.NotificationEnum;
  37. using WingInterfaceLibrary.DTO.LiveRoom;
  38. using WingInterfaceLibrary.Request.DBRequest;
  39. using WingInterfaceLibrary.DTO.Record;
  40. using WingInterfaceLibrary.DTO.Consultation;
  41. using WingServerCommon.Interfaces.Cache;
  42. using System.Collections.Concurrent;
  43. namespace WingDeviceService.Service
  44. {
  45. /// <summary>
  46. /// 设备管理服务
  47. /// </summary>
  48. public partial class DeviceService : JsonRpcService, IDeviceService
  49. {
  50. private ConcurrentDictionary<string, CacheControllingParameter> _controllingParameterDevices = new ConcurrentDictionary<string, CacheControllingParameter>();
  51. private IUserDBService _userServiceProxy;
  52. private IDeviceInfoDBService _deviceInfoDBServiceProxy;
  53. private IAuthenticationService _authenticationService;
  54. private IOrganizationDBService _organizationDBService;
  55. private INotificationService _notificationService;
  56. private IRecordsInfoDBService _recordsInfoDBService;
  57. private IPatientInfoDBService _patientInfoDBService;
  58. private IDiagnosisModuleDBService _diagnosisModuleService;
  59. private IRemedicalService _remedicalService;
  60. private IWingRtcService _wingRtcService;
  61. private IRtcService _rtcService;
  62. private int _heartRateSeconds;
  63. private DeviceHeartRateManager _deviceHeartRateManager;
  64. private string _webSocketUrl = string.Empty;
  65. private int _liveConsultationRateSeconds = 0;
  66. private bool _isRTCSelf = false;
  67. private int _sdkAppId = 0;
  68. private int _remoteControlAskTimeoutSec = 0;
  69. private int _reportStateIntervalSeconds = 0;
  70. private int _reportStateTimeout = 0;
  71. private ILiveConsultationService _liveConsultationService;
  72. private IConsultationRecordDBService _consultationRecordDBService;
  73. private IRemedicalDBService _remedicalDBService;
  74. /// <summary>
  75. /// Init service
  76. /// </summary>
  77. public override void Load(JsonRpcClientPool jsonRpcClientPool)
  78. {
  79. base.Load(jsonRpcClientPool);
  80. _userServiceProxy = GetProxy<IUserDBService>();
  81. _authenticationService = GetProxy<IAuthenticationService>();
  82. _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
  83. _organizationDBService = GetProxy<IOrganizationDBService>();
  84. _notificationService = GetProxy<INotificationService>();
  85. _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
  86. _patientInfoDBService = GetProxy<IPatientInfoDBService>();
  87. _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
  88. _remedicalService = GetProxy<IRemedicalService>();
  89. _wingRtcService = GetProxy<IWingRtcService>();
  90. _rtcService = GetProxy<IRtcService>();
  91. _liveConsultationService = GetProxy<ILiveConsultationService>();
  92. _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
  93. _remedicalDBService = GetProxy<IRemedicalDBService>();
  94. _heartRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
  95. _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
  96. _webSocketUrl = ConfigurationManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
  97. _liveConsultationRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "HeartRateSeconds").Value;
  98. _isRTCSelf = ConfigurationManager.GetParammeter<BoolParameter>("Rtc", "IsSelf").Value;
  99. var sdkAppIdString = ConfigurationManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
  100. if (int.TryParse(sdkAppIdString, out int sdkAppId))
  101. {
  102. _sdkAppId = sdkAppId;
  103. }
  104. _remoteControlAskTimeoutSec = ConfigurationManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
  105. var _reportStateIntervalSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateIntervalSeconds").Value;
  106. var _reportStateTimeout = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateTimeout").Value;
  107. }
  108. /// <summary>
  109. /// 设备心跳
  110. /// </summary>
  111. /// <param name="request"></param>
  112. /// <returns></returns>
  113. public async Task<bool> HeartRateAsync(TokenRequest request)
  114. {
  115. _deviceHeartRateManager.AddOrUpdate(request.Token);
  116. var result = SetOnlineState(request.Token, true);
  117. return result;
  118. }
  119. private bool SetOnlineState(string token, bool isOnline)
  120. {
  121. return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
  122. }
  123. /// <summary>
  124. /// 添加分享设备关联用户请求
  125. /// </summary>
  126. /// <param name="request"></param>
  127. /// <returns></returns>
  128. public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
  129. {
  130. var userCodes = request.UserCodes;
  131. var deviceCode = request.DeviceCode;
  132. //检查设备编码不为空
  133. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  134. {
  135. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  136. }
  137. if (userCodes == null || userCodes.Count <= 0)
  138. {
  139. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  140. }
  141. //查询设备对象
  142. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  143. if (deviceDb == null)
  144. {
  145. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  146. }
  147. foreach (var userCode in userCodes)
  148. {
  149. var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
  150. if (existUser == null)
  151. {
  152. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  153. }
  154. }
  155. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  156. {
  157. DeviceCodes = new List<string> { deviceCode },
  158. UserCodes = userCodes.ToList()
  159. });
  160. return true;
  161. }
  162. /// <summary>
  163. /// 根据设备code获取设备信息
  164. /// </summary>
  165. /// <param name="request">设备code请求实体</param>
  166. /// <returns>返回查询到的设备对象信息</returns>
  167. public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
  168. {
  169. //验证
  170. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  171. {
  172. ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
  173. }
  174. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  175. if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
  176. {
  177. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  178. }
  179. //根据机构编号查询机构名称
  180. var organizationName = "";
  181. if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
  182. {
  183. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
  184. organizationName = organization?.OrganizationName ?? string.Empty;
  185. }
  186. //根据机构编号查询科室名称
  187. var departmentName = "";
  188. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  189. {
  190. var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
  191. departmentName = department?.OrganizationName ?? string.Empty;
  192. }
  193. //是否在线 todo
  194. var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
  195. var result = new DeviceExtendInfoDTO()
  196. {
  197. DepartmentName = departmentName,
  198. OrganizationName = organizationName,
  199. IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
  200. DeviceCode = deviceDb.DeviceCode,
  201. SerialNumber = deviceDb.SerialNumber,
  202. Name = deviceDb.Name,
  203. Description = deviceDb.Description,
  204. DeviceModel = deviceDb.DeviceModel,
  205. DeviceType = deviceDb.DeviceType,
  206. HeadPicUrl = deviceDb.HeadPicUrl,
  207. DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
  208. SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
  209. OrganizationCode = deviceDb.OrganizationCode,
  210. DepartmentCode = deviceDb.DepartmentCode,
  211. ShortCode = deviceDb.ShortCode,
  212. LanguageConfigs = deviceTypeModel.LanguageConfigs
  213. };
  214. return result;
  215. }
  216. /// <summary>
  217. /// 根据设备动态唯一码获取设备信息
  218. /// </summary>
  219. /// <param name="request"></param>
  220. /// <returns></returns>
  221. public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
  222. {
  223. //验证
  224. if (string.IsNullOrWhiteSpace(request.ShortCode))
  225. {
  226. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
  227. }
  228. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  229. if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
  230. {
  231. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  232. }
  233. return await MapToExtendDTO(deviceDb);
  234. }
  235. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
  236. {
  237. throw new System.NotImplementedException();
  238. }
  239. public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
  240. {
  241. var userCodes = request.UserCodes;
  242. var deviceCode = request.DeviceCode;
  243. //检查设备编码不为空
  244. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  245. {
  246. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  247. }
  248. //用户编码集合检查
  249. if (userCodes == null || userCodes.Count <= 0)
  250. {
  251. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  252. }
  253. //查询设备对象
  254. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  255. if (deviceDb == null)
  256. {
  257. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  258. }
  259. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  260. foreach (var userCode in userCodes)
  261. {
  262. var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
  263. if (user != null)
  264. {
  265. if (user.BindDevices.Contains(deviceCode))
  266. {
  267. user.BindDevices.Remove(deviceCode);
  268. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  269. {
  270. Data = user.MappingTo<UserPasswordDTO>(),
  271. });
  272. }
  273. }
  274. }
  275. if (updateUsers.Count > 0)
  276. {
  277. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  278. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  279. }
  280. return true;
  281. }
  282. /// <summary>
  283. /// 机构设备移除-根据机构code和设备code解除其绑定关系
  284. /// </summary>
  285. /// <param name="request">移除设备请求实体</param>
  286. /// <returns>移除是否成功:true-成功;false-失败</returns>
  287. public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
  288. {
  289. //验证
  290. if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
  291. {
  292. ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
  293. }
  294. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  295. if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
  296. {
  297. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
  298. }
  299. //根据设备code和机构code查询相关数据,查到则删除关联
  300. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  301. {
  302. deviceDb.DepartmentCode = "";
  303. deviceDb.OrganizationCode = "";
  304. }
  305. else
  306. {
  307. deviceDb.OrganizationCode = "";
  308. }
  309. bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  310. return removeDeviceResult;
  311. }
  312. private async Task<string> GetClientIdByTokenAsync(string token)
  313. {
  314. var request = new TokenRequest() { Token = token };
  315. var result = await _authenticationService.GetTokenAsync(request);
  316. return result.ClientId; //return User code
  317. }
  318. /// <summary>
  319. /// 查询个人名下所有设备列表接口
  320. /// </summary>
  321. /// <param name="request">查询个人名下所有设备列表请求实体</param>
  322. /// <returns>返回设备信息列表</returns>
  323. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
  324. {
  325. //验证
  326. var userCode = await GetClientIdByTokenAsync(request.Token);
  327. //查询用户是否存在
  328. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  329. if (userInfoDO == null)
  330. {
  331. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  332. }
  333. //查询用户的医院是否存在
  334. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  335. {
  336. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  337. }
  338. var deviceInfoDOList = new List<DeviceInfoDTO>();
  339. if (!userInfoDO.IsDirector)
  340. {
  341. //普通用户,查询用户绑定的设备
  342. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
  343. {
  344. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  345. }
  346. }
  347. else
  348. {
  349. //机构负责人
  350. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  351. }
  352. if (!deviceInfoDOList.Any())
  353. {
  354. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  355. }
  356. var deviceList = await MapToExtendDTO(deviceInfoDOList);
  357. //条件筛选
  358. if (!string.IsNullOrWhiteSpace(request.DeviceType))
  359. {
  360. deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  361. }
  362. if (!string.IsNullOrWhiteSpace(request.DeviceModel))
  363. {
  364. deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  365. }
  366. if (!string.IsNullOrWhiteSpace(request.KeyWord))
  367. {
  368. var keyword = request.KeyWord.Trim().ToLower();
  369. deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List<DeviceExtendInfoDTO>();
  370. }
  371. if (request.IsOnline != null)
  372. {
  373. deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  374. }
  375. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  376. {
  377. CurrentPage = request.PageIndex,
  378. PageSize = request.PageSize,
  379. DataCount = deviceList.Count,
  380. PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
  381. };
  382. return pagedResult;
  383. }
  384. /// <summary>
  385. /// 绑定设备
  386. /// </summary>
  387. /// <param name="request"></param>
  388. /// <returns></returns>
  389. public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
  390. {
  391. //验证
  392. var userCode = await GetClientIdByTokenAsync(request.Token);
  393. //查询用户是否存在
  394. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  395. if (userInfoDO == null)
  396. {
  397. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  398. }
  399. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  400. if (deviceDb == null)
  401. {
  402. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  403. }
  404. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  405. {
  406. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  407. }
  408. try
  409. {
  410. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
  411. deviceDb.Name = request.Name;
  412. deviceDb.SerialNumber = request.SerialNumber;
  413. deviceDb.Description = request.Description;
  414. if (!string.IsNullOrEmpty(request.HeadPicUrl))
  415. {
  416. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  417. }
  418. deviceDb.DepartmentCode = request.DepartmentCode;
  419. deviceDb.IsAutoShared = request.IsAutoShared;
  420. deviceDb.OrganizationCode = request.OrganizationCode;
  421. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  422. if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
  423. {
  424. var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
  425. //迁移数据超声机上传检查记录
  426. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  427. //迁移数据超声机上传病人
  428. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  429. }
  430. if (deviceDb.IsAutoShared)
  431. {
  432. var users = new List<UserDTO>();
  433. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  434. {
  435. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  436. }
  437. else
  438. {
  439. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  440. }
  441. var userCodes = users.Select(f => f.UserCode).ToList();
  442. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  443. {
  444. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  445. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  446. });
  447. }
  448. return true;
  449. }
  450. catch (Exception ex)
  451. {
  452. Logger.WriteLineError($"BindDeviceAsync error {ex}");
  453. }
  454. return false;
  455. }
  456. /// <summary>
  457. /// 修改设备
  458. /// </summary>
  459. /// <param name="request"></param>
  460. /// <returns></returns>
  461. public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
  462. {
  463. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  464. if (deviceDb == null)
  465. {
  466. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  467. }
  468. if (string.IsNullOrWhiteSpace(request.Name))
  469. {
  470. ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
  471. }
  472. deviceDb.Name = request.Name;
  473. if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
  474. {
  475. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  476. }
  477. else
  478. {
  479. deviceDb.HeadPicUrl = string.Empty;
  480. }
  481. deviceDb.DepartmentCode = request.DepartmentCode;
  482. //修改自动分享
  483. deviceDb.IsAutoShared = request.IsAutoShared;
  484. if (deviceDb.IsAutoShared)
  485. {
  486. var users = new List<UserDTO>();
  487. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  488. {
  489. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  490. }
  491. else
  492. {
  493. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  494. }
  495. var userCodes = users.Select(f => f.UserCode).ToList();
  496. //先解绑,再绑定,避免绑定重复设备code
  497. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  498. foreach (var user in users)
  499. {
  500. var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
  501. user.BindDevices?.Remove(deviceDb.DeviceCode);
  502. await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
  503. }
  504. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  505. {
  506. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  507. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  508. });
  509. }
  510. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  511. }
  512. /// <summary>
  513. /// 创建字典
  514. /// </summary>
  515. /// <param name="request"></param>
  516. /// <returns></returns>
  517. public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
  518. {
  519. return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
  520. {
  521. Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
  522. ExtensionData = string.Empty
  523. });
  524. }
  525. /// <summary>
  526. /// 查找设备型号所有字典项
  527. /// </summary>
  528. /// <param name="request"></param>
  529. /// <returns></returns>
  530. public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
  531. {
  532. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  533. {
  534. DictionaryType = (int)request.DictionaryType,
  535. ParentCode = request.DeviceTypeCode
  536. });
  537. return dictionaryDOList;
  538. }
  539. /// <summary>
  540. /// 查找设备类型所有字典项
  541. /// </summary>
  542. /// <param name="request"></param>
  543. /// <returns></returns>
  544. public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
  545. {
  546. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  547. {
  548. DictionaryType = (int)request.DictionaryType
  549. });
  550. return dictionaryDOList;
  551. }
  552. /// <summary>
  553. /// 根据组织编码查询所属全部设备信息
  554. /// </summary>
  555. /// <param name="request"></param>
  556. /// <returns></returns>
  557. public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
  558. {
  559. var result = new List<DeviceExtendInfoDTO>();
  560. var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
  561. if (deviceInfoDOList?.Count > 0)
  562. {
  563. //根据机构编号查询机构名称
  564. var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
  565. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
  566. var organizationName = organization?.OrganizationName ?? string.Empty;
  567. //根据机构编号查询科室名称
  568. var organizationFilter = new Dictionary<string, string>();
  569. organizationFilter.Add("RootCode", organizationCode);
  570. var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
  571. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  572. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  573. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  574. foreach (var c in deviceInfoDOList)
  575. {
  576. var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
  577. result.Add(new DeviceExtendInfoDTO
  578. {
  579. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  580. OrganizationName = organizationName,
  581. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  582. DeviceCode = c.DeviceCode,
  583. SerialNumber = c.SerialNumber,
  584. Name = c.Name,
  585. Description = c.Description,
  586. DeviceModel = c.DeviceModel,
  587. DeviceType = c.DeviceType,
  588. HeadPicUrl = c.HeadPicUrl,
  589. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  590. SDKSoftwareVersion = c.SDKSoftwareVersion,
  591. OrganizationCode = c.OrganizationCode,
  592. DepartmentCode = c.DepartmentCode,
  593. ShortCode = c.ShortCode,
  594. LanguageConfigs = deviceTypeModel?.LanguageConfigs
  595. });
  596. }
  597. }
  598. return result;
  599. }
  600. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  601. {
  602. throw new NotImplementedException();
  603. }
  604. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  605. {
  606. //验证
  607. var userCode = await GetClientIdByTokenAsync(request.Token);
  608. //查询用户是否存在
  609. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  610. if (userInfoDO == null)
  611. {
  612. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  613. }
  614. var result = new List<SelectItemDTO>();
  615. //查询用户的医院是否存在
  616. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  617. {
  618. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  619. }
  620. var deviceInfoDOList = new List<DeviceInfoDTO>();
  621. if (userInfoDO.IsDirector)
  622. {
  623. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  624. }
  625. else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  626. {
  627. //查询用户绑定的设备
  628. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  629. {
  630. return result;
  631. }
  632. //根据用户名下的设备id查询所有的设备信息
  633. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  634. }
  635. else
  636. {
  637. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  638. if (experts.Any())
  639. {
  640. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  641. if (bindDeviceCodes.Any())
  642. {
  643. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  644. }
  645. }
  646. else
  647. {
  648. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  649. }
  650. }
  651. if (deviceInfoDOList?.Count > 0)
  652. {
  653. result = deviceInfoDOList.Select(c => new SelectItemDTO()
  654. {
  655. Key = c.DeviceCode,
  656. Value = c.Name
  657. }).ToList();
  658. }
  659. return result;
  660. }
  661. /// <summary>
  662. /// 设备端调用,查询获取服务器配置信息接口
  663. /// </summary>
  664. /// <param name="request">Token验证</param>
  665. /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
  666. public async Task<DeviceServerSettingResult> QueryServerConfigAsync(TokenRequest request)
  667. {
  668. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  669. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  670. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  671. {
  672. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  673. }
  674. var org = new OrganizationDTO();
  675. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  676. {
  677. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  678. if (org == null)
  679. {
  680. org = new OrganizationDTO();
  681. }
  682. }
  683. var dictionary = new Dictionary<string, string>();
  684. //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
  685. //TODO 配置信息: 直播配置、存储配置、
  686. //存储上传图像或者视频是 是否本地上传缩略图
  687. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  688. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  689. dictionary.Add("PatientType", org.PatientType.ToString());
  690. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  691. dictionary.Add("NotificationUrl", _webSocketUrl);
  692. dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
  693. dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
  694. var result = new DeviceServerSettingResult()
  695. {
  696. ServerConfigList = dictionary,
  697. IsUploadThumbnail = isUploadThumbnail,
  698. PatientType = org.PatientType,
  699. HeartRateSeconds = _heartRateSeconds,
  700. NotificationUrl = _webSocketUrl,
  701. LiveConsultationRateSeconds = _liveConsultationRateSeconds,
  702. MergedChannel = deviceInfo.MergedChannel,
  703. MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
  704. MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
  705. IsSelfRtcService = _isRTCSelf,
  706. RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec
  707. };
  708. return result;
  709. }
  710. /// <summary>
  711. /// 添加或迁移设备到医院请求
  712. /// </summary>
  713. /// <param name="request"></param>
  714. /// <returns></returns>
  715. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  716. {
  717. var shortCode = request.UniqueCode;
  718. #region Params Check
  719. var userCode = await GetClientIdByTokenAsync(request.Token);
  720. if (string.IsNullOrEmpty(shortCode))
  721. {
  722. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  723. }
  724. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  725. if (device == null)
  726. {
  727. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  728. }
  729. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  730. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  731. {
  732. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  733. }
  734. //用户
  735. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  736. if (userDTO == null)
  737. {
  738. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  739. }
  740. if (!userDTO.IsDirector)
  741. {
  742. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  743. }
  744. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  745. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  746. {
  747. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  748. }
  749. #endregion
  750. try
  751. {
  752. var newOrgode = org.OrganizationCode;
  753. //设备更新医院
  754. if (!string.IsNullOrEmpty(device.DepartmentCode))
  755. {
  756. device.DepartmentCode = "";
  757. }
  758. if (!string.IsNullOrEmpty(device.Name))
  759. {
  760. device.Name = "";
  761. }
  762. device.HeadPicUrl = "";
  763. device.Description = "";
  764. device.IsAutoShared = false;
  765. device.OrganizationCode = newOrgode;
  766. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  767. if (success)
  768. {
  769. // 删除已知绑定的用户
  770. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  771. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  772. foreach (var user in users)
  773. {
  774. user.BindDevices.Remove(device.DeviceCode);
  775. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  776. {
  777. Data = user.MappingTo<UserPasswordDTO>(),
  778. });
  779. }
  780. if (updateUsers.Count > 0)
  781. {
  782. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  783. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  784. }
  785. if (oldOrg.Isinvented) // 虚拟医院
  786. {
  787. //迁移数据超声机上传检查记录
  788. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  789. //迁移数据超声机上传病人
  790. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  791. }
  792. }
  793. return success;
  794. }
  795. catch (System.Exception ex)
  796. {
  797. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  798. }
  799. return false;
  800. }
  801. /// <summary>
  802. /// 补齐设备扩展信息
  803. /// </summary>
  804. /// <param name="deviceInfoDOList"></param>
  805. /// <returns></returns>
  806. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
  807. {
  808. var deviceList = new List<DeviceExtendInfoDTO>();
  809. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  810. {
  811. //查询机构
  812. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  813. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  814. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  815. //查询机构负责人
  816. var organizationDirectorCodes = new List<string>();
  817. foreach (var org in organizations)
  818. {
  819. if (org.Directors != null && org.Directors.Any())
  820. {
  821. organizationDirectorCodes.AddRange(org.Directors);
  822. }
  823. }
  824. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  825. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  826. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  827. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  828. foreach (var dto in deviceInfoDOList)
  829. {
  830. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  831. device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
  832. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  833. device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
  834. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  835. if (organization != null)
  836. {
  837. device.OrganizationName = organization.OrganizationName;
  838. if (organization.Directors != null && organization.Directors.Any())
  839. {
  840. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  841. device.OrganizationDirectorCode = director?.UserCode;
  842. device.OrganizationDirectorUserName = director?.UserName;
  843. device.OrganizationDirectorFullName = director?.FullName;
  844. }
  845. }
  846. deviceList.Add(device);
  847. }
  848. }
  849. return deviceList;
  850. }
  851. /// <summary>
  852. /// 补齐设备扩展信息
  853. /// </summary>
  854. /// <param name="deviceInfoDOList"></param>
  855. /// <returns></returns>
  856. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  857. {
  858. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  859. return deviceList.FirstOrDefault();
  860. }
  861. /// <summary>
  862. /// 获取设备绑定用户codes
  863. /// </summary>
  864. /// <param name="request">获取设备绑定用户codes请求实体</param>
  865. /// <returns>test01,test02</returns>
  866. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  867. {
  868. //检查设备编码不为空
  869. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  870. {
  871. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  872. }
  873. //查询设备对象
  874. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  875. if (deviceDb == null)
  876. {
  877. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  878. }
  879. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  880. if (userListResult != null && userListResult.Count > 0)
  881. {
  882. return userListResult.Select(u => u.UserCode).ToList();
  883. }
  884. return new List<string>();
  885. }
  886. /// <summary>
  887. /// 查询设备AI应用的状态
  888. /// </summary>
  889. /// <param name="request">请求参数</param>
  890. /// <returns>AI应用集合</returns>
  891. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  892. {
  893. //检查设备编码不为空
  894. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  895. {
  896. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  897. }
  898. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  899. }
  900. /// <summary>
  901. /// 修改设备AI应用启用状态
  902. /// </summary>
  903. /// <param name="request">修改设备AI应用启用状态请求实体</param>
  904. /// <returns>是否成功</returns>
  905. /// <para>DeviceErrorCodeEnum</para>
  906. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  907. {
  908. //检查设备编码不为空
  909. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  910. {
  911. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  912. }
  913. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  914. {
  915. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  916. }
  917. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  918. {
  919. DeviceCode = request.DeviceCode,
  920. DiagnosisModule = request.DiagnosisModule,
  921. Enabled = request.Enabled
  922. });
  923. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  924. return result;
  925. }
  926. /// <summary>
  927. /// 设备离开会诊房间
  928. /// </summary>
  929. /// <param name="request">设备离开会诊房间请求实体</param>
  930. /// <returns></returns>
  931. public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
  932. {
  933. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  934. var result = new DeviceLeaveLiveConsultationResult
  935. {
  936. Success = false,
  937. };
  938. return result;
  939. }
  940. /// <summary>
  941. /// 通用异常处理方法
  942. /// </summary>
  943. /// <param name="customerRpcCodeEnum">异常标识码</param>
  944. /// <param name="msg">异常信息</param>
  945. /// <param name="internalMessage">内部异常信息,非必填</param>
  946. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  947. {
  948. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  949. }
  950. /// <summary>
  951. /// 上报设备画面尺寸相关信息
  952. /// </summary>
  953. /// <param name="request"></param>
  954. /// <docFirstDirectory>设备端API</docFirstDirectory>
  955. /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
  956. /// <docThirdDirectory>会诊</docThirdDirectory>
  957. /// <returns></returns>
  958. public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
  959. {
  960. var result = new ReportVideoDeviceInfoResult();
  961. if (request.VideoDeviceInfos == null || request.VideoDeviceInfos.Count == 0)
  962. {
  963. //视屏设备画面信息为空
  964. ThrowCustomerException(CustomerRpcCode.VideoDeviceInfosEmpty, "VideoDeviceInfosEmpty");
  965. }
  966. if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
  967. {
  968. //视屏设备ID为空
  969. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
  970. }
  971. var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
  972. if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
  973. {
  974. //视屏设备ID重复
  975. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
  976. }
  977. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  978. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  979. var videoDeviceInfos = new List<VideoDeviceDTO>();
  980. foreach (var video in request.VideoDeviceInfos)
  981. {
  982. var videoDeviceInfo = new VideoDeviceDTO
  983. {
  984. VideoDeviceId = video.VideoDeviceId,
  985. VideoDeviceSourceType = video.VideoDeviceSourceType,
  986. Width = video.Width,
  987. Height = video.Height,
  988. OutputWidth = video.Width,
  989. OutputHeight = video.Height,
  990. VideoFps = video.VideoFps,
  991. VideoBitrate = video.VideoBitrate,
  992. MinVideoBitrate = video.MinVideoBitrate
  993. };
  994. videoDeviceInfos.Add(videoDeviceInfo);
  995. }
  996. deviceDTO.VideoDeviceInfos = videoDeviceInfos;
  997. var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
  998. {
  999. DeviceCode = deviceDTO.DeviceCode,
  1000. LiveOpened = request.LiveOpened,
  1001. VideoDeviceInfos = videoDeviceInfos
  1002. };
  1003. await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
  1004. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(deviceDTO.DeviceCode);
  1005. result.Success = true;
  1006. result.VideoDeviceOutputInfos = videoDeviceInfos;
  1007. return result;
  1008. }
  1009. /// <summary>
  1010. /// 查找有效设备总数量
  1011. /// </summary>
  1012. /// <returns></returns>
  1013. public async Task<long> GetActiveDeviceCount()
  1014. {
  1015. return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
  1016. }
  1017. /// <summary>
  1018. /// 设备发送调参初始化数据
  1019. /// </summary>
  1020. /// <param name="request">调参数据请求</param>
  1021. /// <returns></returns>
  1022. public async Task<bool> SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
  1023. {
  1024. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1025. var userCode = request.ControlUserCode;
  1026. //发送控制人通知
  1027. if (string.IsNullOrWhiteSpace(userCode))
  1028. {
  1029. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1030. }
  1031. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1032. if (userDTO == null)
  1033. {
  1034. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1035. }
  1036. var notify = new DeviceParametersNotification()
  1037. {
  1038. DeviceCode = deviceCode,
  1039. IsResponse = true
  1040. };
  1041. var cacheControllingParameter = new CacheControllingParameter()
  1042. {
  1043. Code = deviceCode,
  1044. ProbeApplication = Newtonsoft.Json.JsonConvert.SerializeObject(request.ProbeApplication),
  1045. Parameter = Newtonsoft.Json.JsonConvert.SerializeObject(request.Parameter),
  1046. };
  1047. _controllingParameterDevices.AddOrUpdate(deviceCode, (k) => cacheControllingParameter, (k, exist) =>
  1048. {
  1049. return cacheControllingParameter;
  1050. });
  1051. var notificationRequest = new SendNotificationRequest()
  1052. {
  1053. ClientId = userCode,
  1054. Message = notify,
  1055. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1056. NotificationType = notify.NotificationType,
  1057. TransactionType = TransactionTypeEnum.ControlParameter,
  1058. RelevanceCode = userCode,
  1059. ReceiverType = ApplicantTypeEnum.Client
  1060. };
  1061. await _notificationService.PostMessageAsync(notificationRequest);
  1062. return true;
  1063. }
  1064. /// <summary>
  1065. /// 获取设备参数调节数据请求
  1066. /// </summary>
  1067. /// <param name="request"></param>
  1068. /// <returns></returns>
  1069. public async Task<DeviceControlParameterDataDTO> GetControlParametersAsync(GetControlParametersRequest request)
  1070. {
  1071. var deviceCode = request.DeviceCode;
  1072. //检查设备编码不为空
  1073. if (string.IsNullOrWhiteSpace(deviceCode))
  1074. {
  1075. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1076. }
  1077. _controllingParameterDevices.TryGetValue(deviceCode, out var controlParameterData);
  1078. if (controlParameterData != null)
  1079. {
  1080. return new DeviceControlParameterDataDTO()
  1081. {
  1082. DeviceCode = controlParameterData.Code,
  1083. ProbeApplication = controlParameterData.ProbeApplication,
  1084. Parameter = controlParameterData.Parameter
  1085. };
  1086. }
  1087. return null;
  1088. }
  1089. /// <summary>
  1090. /// 用户进入设备直播房间
  1091. /// </summary>
  1092. /// <param name="request">用户进入设备直播房间请求实体</param>
  1093. /// <returns></returns>
  1094. public async Task<JoinDeviceLiveRoomResult> JoinDeviceLiveRoomAsync(JoinDeviceLiveRoomRequest request)
  1095. {
  1096. var userInfo = await _authenticationService.GetTokenAsync(request);
  1097. var deviceCode = request.DeviceCode;
  1098. var deviceInfo = CacheMaintenance.Instance.Get<IDeviceInfosManager>().Get(deviceCode);
  1099. var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
  1100. {
  1101. DeviceCode = deviceCode
  1102. });
  1103. LiveMemberDTO deviceMemberInfo;
  1104. if (liveRoom != null)
  1105. {
  1106. if (liveRoom.LiveRoomCode == deviceCode)
  1107. {
  1108. //设备正在推流
  1109. deviceMemberInfo = liveRoom.DeviceInfos.FirstOrDefault(x => x.Code == deviceCode);
  1110. if (deviceMemberInfo?.Status == LiveMemberStatus.Joined)
  1111. {
  1112. //添加观众
  1113. await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1114. {
  1115. LiveRoomCode = liveRoom.LiveRoomCode,
  1116. UserCode = userInfo.ClientId,
  1117. UserName = userInfo.AccountName,
  1118. });
  1119. return new JoinDeviceLiveRoomResult
  1120. {
  1121. RoomNo = liveRoom.RtcRoomId,
  1122. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1123. };
  1124. }
  1125. }
  1126. }
  1127. //新增或更新设备直播间
  1128. var deviceName = !string.IsNullOrWhiteSpace(deviceInfo.Name) ? deviceInfo.Name : deviceInfo.ShortCode;
  1129. var deviceLiveInfo = new LiveMemberDTO
  1130. {
  1131. Code = deviceCode,
  1132. Name = deviceName,
  1133. MemberType = LiveMemberEnum.Device,
  1134. HeadImageToken = deviceInfo.HeadPicUrl,
  1135. Status = LiveMemberStatus.Accepted,
  1136. };
  1137. var room = new LiveRoomDTO
  1138. {
  1139. LiveRoomCode = deviceCode,
  1140. Name = deviceName,
  1141. RelatedCode = deviceCode,
  1142. BusinessModule = BusinessModuleEnum.LivingConsultation,
  1143. Status = LiveRoomStatus.Default,
  1144. UserInfos = new List<LiveMemberDTO>(),
  1145. DeviceInfos = new List<LiveMemberDTO> { deviceLiveInfo }
  1146. };
  1147. await _rtcService.AddOrUpdateLiveRoomAsync(new AddOrUpdateLiveRoomRequest
  1148. {
  1149. LiveRoom = room,
  1150. });
  1151. var initiateResult = await _rtcService.InitiateAsync(new InitiateRequest
  1152. {
  1153. LiveRoomCode = deviceCode,
  1154. InitiatorCode = deviceCode,
  1155. });
  1156. deviceMemberInfo = initiateResult.DeviceInfos.FirstOrDefault(x => x.Code == deviceCode);
  1157. //添加观众
  1158. await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1159. {
  1160. LiveRoomCode = initiateResult.LiveRoomCode,
  1161. UserCode = userInfo.ClientId,
  1162. UserName = userInfo.AccountName,
  1163. });
  1164. return new JoinDeviceLiveRoomResult
  1165. {
  1166. RoomNo = initiateResult.RtcRoomId,
  1167. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1168. ReportStateIntervalSeconds = _reportStateIntervalSeconds,
  1169. };
  1170. }
  1171. /// <summary>
  1172. /// 用户离开设备直播房间
  1173. /// </summary>
  1174. /// <param name="request">用户离开设备直播房间请求实体</param>
  1175. /// <returns></returns>
  1176. public async Task<bool> LeaveDeviceLiveRoomAsync(LeaveDeviceLiveRoomRequest request)
  1177. {
  1178. var userInfo = await _authenticationService.GetTokenAsync(request);
  1179. var userCode = userInfo.ClientId;
  1180. var deviceCode = request.DeviceCode;
  1181. var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
  1182. {
  1183. DeviceCode = deviceCode
  1184. });
  1185. if (liveRoom != null)
  1186. {
  1187. //移除观众
  1188. var removeViewerResult = await _rtcService.RemoveViewerAsync(new RemoveViewerRequest
  1189. {
  1190. LiveRoomCode = liveRoom.LiveRoomCode,
  1191. UserCode = userInfo.ClientId,
  1192. });
  1193. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1194. if (!liveRoom.ViewerInfos.Any(x => x.UserCode != userCode && x.LastReportTime >= expireTime))
  1195. {
  1196. await _rtcService.CloseAsync(new CloseRequest
  1197. {
  1198. LiveRoomCode = liveRoom.LiveRoomCode
  1199. });
  1200. }
  1201. }
  1202. return true;
  1203. }
  1204. /// <summary>
  1205. /// 上报观看直播状态
  1206. /// </summary>
  1207. /// <param name="request">上报观看直播状态请求实体</param>
  1208. /// <returns></returns>
  1209. public async Task<bool> ReportLiveViewStateAsync(ReportLiveViewStateRequest request)
  1210. {
  1211. var userInfo = await _authenticationService.GetTokenAsync(request);
  1212. var deviceCode = request.DeviceCode;
  1213. var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
  1214. {
  1215. DeviceCode = deviceCode
  1216. });
  1217. if (liveRoom != null)
  1218. {
  1219. //添加观众
  1220. var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1221. {
  1222. LiveRoomCode = liveRoom.LiveRoomCode,
  1223. UserCode = userInfo.ClientId,
  1224. UserName = userInfo.AccountName,
  1225. });
  1226. }
  1227. return true;
  1228. }
  1229. /// <summary>
  1230. /// 上报直播状态
  1231. /// </summary>
  1232. /// <param name="request">上报直播状态请求实体</param>
  1233. /// <returns></returns>
  1234. public async Task<bool> ReportLiveStateAsync(ReportLiveStateRequest request)
  1235. {
  1236. var tokenInfo = await _authenticationService.GetTokenAsync(request);
  1237. var deviceCode = tokenInfo.ClientId;
  1238. switch (request.LiveState)
  1239. {
  1240. case DeviceLiveStateEnum.Error:
  1241. case DeviceLiveStateEnum.Warning:
  1242. Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1243. break;
  1244. default:
  1245. Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1246. break;
  1247. }
  1248. if (request.LiveState == DeviceLiveStateEnum.Pushing || request.LiveState == DeviceLiveStateEnum.Closed)
  1249. {
  1250. var liveRoom = await _rtcService.GetInitiatingRoomByDeviceCodeAsync(new GetInitiatingRoomByDeviceCodeRequest
  1251. {
  1252. DeviceCode = deviceCode
  1253. });
  1254. if (liveRoom != null)
  1255. {
  1256. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1257. var validViewers = liveRoom.ViewerInfos.Where(x => x.LastReportTime >= expireTime)?.ToList() ?? new List<LiveViewerDTO>();
  1258. if (request.LiveState == DeviceLiveStateEnum.Closed && validViewers.Any())
  1259. {
  1260. //关闭直播 to users
  1261. var message = new DeviceLiveFinishedNotification
  1262. {
  1263. LiveRoomCode = liveRoom.LiveRoomCode,
  1264. };
  1265. await BroadcastNotificationAsync(liveRoom.LiveRoomCode, validViewers.Select(x => x.UserCode).ToList(), message);
  1266. }
  1267. if (request.LiveState == DeviceLiveStateEnum.Pushing && !validViewers.Any())
  1268. {
  1269. await _rtcService.CloseAsync(new CloseRequest
  1270. {
  1271. LiveRoomCode = liveRoom.LiveRoomCode
  1272. });
  1273. }
  1274. }
  1275. }
  1276. return await Task.FromResult(true);
  1277. }
  1278. /// <summary>
  1279. /// 获取实时音视频参数
  1280. /// </summary>
  1281. /// <param name="request">获取实时音视频参数请求实体</param>
  1282. /// <returns></returns>
  1283. public async Task<CreateLiveRoomInfoResult> CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
  1284. {
  1285. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
  1286. var userCode = Guid.NewGuid().ToString("N");
  1287. var getUserSignRequest = new GetUserSignRequest
  1288. {
  1289. UserId = userCode,
  1290. };
  1291. var getUserSignResult = await _wingRtcService.GetUserSignAsync(getUserSignRequest);
  1292. var userSign = getUserSignResult.UserSign;
  1293. var getRoomIdRequest = new GetRoomIdRequest
  1294. {
  1295. UniqueId = userCode,
  1296. };
  1297. var getRoomIdResult = await _wingRtcService.GetRoomIdAsync(getRoomIdRequest);
  1298. var intRoomNo = (int)getRoomIdResult.RoomId;
  1299. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
  1300. return new CreateLiveRoomInfoResult
  1301. {
  1302. IsTrtc = !_isRTCSelf,
  1303. UserCode = userCode,
  1304. UserSign = userSign,
  1305. AppId = _sdkAppId,
  1306. RoomNo = intRoomNo,
  1307. };
  1308. }
  1309. private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> clientIds, NotificationDTO message)
  1310. {
  1311. var broadcastNotificationRequest = new BroadcastNotificationRequest
  1312. {
  1313. ClientIds = clientIds,
  1314. Message = message,
  1315. TransactionType = TransactionTypeEnum.Live,
  1316. RelevanceCode = roomId,
  1317. ReceiverType = ApplicantTypeEnum.Client,
  1318. WSConnectType = WSConnectTypeEnum.Default
  1319. };
  1320. return await _notificationService.BroadcastMessageAsync(broadcastNotificationRequest);
  1321. }
  1322. /// <summary>
  1323. /// 拒绝远程控制
  1324. /// </summary>
  1325. /// <param name="request"></param>
  1326. /// <returns></returns>
  1327. public async Task<bool> RejectRemoteControl(RemoteControlRequest request)
  1328. {
  1329. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1330. string userCode = request.ControlUserCode;
  1331. //发送控制人通知
  1332. if (string.IsNullOrWhiteSpace(userCode))
  1333. {
  1334. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1335. }
  1336. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1337. if (userDTO == null)
  1338. {
  1339. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1340. }
  1341. var notify = new DeviceRejectRemoteControlNotification()
  1342. {
  1343. DeviceCode = deviceCode,
  1344. };
  1345. var notificationRequest = new SendNotificationRequest()
  1346. {
  1347. ClientId = userCode,
  1348. Message = notify,
  1349. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1350. NotificationType = notify.NotificationType,
  1351. TransactionType = TransactionTypeEnum.RemoteControl,
  1352. RelevanceCode = userCode,
  1353. ReceiverType = ApplicantTypeEnum.Client
  1354. };
  1355. await _notificationService.PostMessageAsync(notificationRequest);
  1356. //更改房间调参状态
  1357. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1358. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1359. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1360. // {
  1361. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1362. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1363. // }
  1364. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1365. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1366. return true;
  1367. }
  1368. /// <summary>
  1369. /// 断开远程控制
  1370. /// </summary>
  1371. /// <param name="request"></param>
  1372. /// <returns></returns>
  1373. public async Task<bool> DisconnectRemoteControl(RemoteControlRequest request)
  1374. {
  1375. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1376. string userCode = request.ControlUserCode;
  1377. //发送控制人通知
  1378. if (string.IsNullOrWhiteSpace(userCode))
  1379. {
  1380. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1381. }
  1382. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1383. if (userDTO == null)
  1384. {
  1385. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1386. }
  1387. var notify = new DeviceDisconnectRemoteControlNotification()
  1388. {
  1389. DeviceCode = deviceCode,
  1390. };
  1391. var notificationRequest = new SendNotificationRequest()
  1392. {
  1393. ClientId = userCode,
  1394. Message = notify,
  1395. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1396. NotificationType = notify.NotificationType,
  1397. TransactionType = TransactionTypeEnum.RemoteControl,
  1398. RelevanceCode = userCode,
  1399. ReceiverType = ApplicantTypeEnum.Client
  1400. };
  1401. await _notificationService.PostMessageAsync(notificationRequest);
  1402. //更改房间调参状态
  1403. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1404. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1405. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1406. // {
  1407. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1408. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1409. // }
  1410. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1411. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1412. return true;
  1413. }
  1414. public async Task<bool> UploadConsultationDataAsync(UploadConsultationDataRequest request)
  1415. {
  1416. var deviceInfo = await GetDeviceByTokenAsync(request);
  1417. var consultationCode = request.ConsultationCode;
  1418. if (string.IsNullOrWhiteSpace(consultationCode))
  1419. {
  1420. ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
  1421. }
  1422. if (string.IsNullOrWhiteSpace(request.FileToken))
  1423. {
  1424. ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
  1425. }
  1426. var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
  1427. var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
  1428. if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
  1429. {
  1430. ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
  1431. }
  1432. var dataDTO = new RemedicalInfoDTO();
  1433. dataDTO.DeviceCode = deviceInfo.DeviceCode;
  1434. dataDTO.RecordCode = consultationRecord.ConsultationCode;
  1435. dataDTO.ApplicationCategory = request.ApplicationCategory;
  1436. dataDTO.Application = request.Application;
  1437. dataDTO.TerminalImages = new TerminalImageDTO();
  1438. var originImageUrl = request.FileToken;
  1439. dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
  1440. dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
  1441. dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
  1442. dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
  1443. dataDTO.TerminalImages.ImageSize = request.FileSize;
  1444. dataDTO.FileDataType = request.FileDataType;
  1445. dataDTO.MeasuredResult = request.MeasuredResult;
  1446. dataDTO.CommentResult = request.CommentResult;
  1447. dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
  1448. dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
  1449. //更新会诊记录
  1450. if (consultationRecord.ConsultationFileList == null)
  1451. {
  1452. consultationRecord.ConsultationFileList = new List<ConsultationFileDTO>();
  1453. }
  1454. var consultationFileDTO = new ConsultationFileDTO
  1455. {
  1456. SourceUrl = originImageUrl,
  1457. CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
  1458. PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
  1459. FileDataType = request.FileDataType,
  1460. CreateTime = DateTime.UtcNow,
  1461. ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
  1462. RemedicalCode = dataDTO.RemedicalCode
  1463. };
  1464. consultationRecord.ConsultationFileList.Add(consultationFileDTO);
  1465. var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
  1466. return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
  1467. }
  1468. }
  1469. }