Device.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Security;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Xml;
  11. using System.Xml.Linq;
  12. using Emby.Dlna.Common;
  13. using Emby.Dlna.Ssdp;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Dlna.PlayTo
  16. {
  17. public class Device : IDisposable
  18. {
  19. private readonly IHttpClientFactory _httpClientFactory;
  20. private readonly ILogger _logger;
  21. private readonly object _timerLock = new object();
  22. private Timer? _timer;
  23. private int _muteVol;
  24. private int _volume;
  25. private DateTime _lastVolumeRefresh;
  26. private bool _volumeRefreshActive;
  27. private int _connectFailureCount;
  28. private bool _disposed;
  29. public Device(DeviceInfo deviceProperties, IHttpClientFactory httpClientFactory, ILogger logger)
  30. {
  31. Properties = deviceProperties;
  32. _httpClientFactory = httpClientFactory;
  33. _logger = logger;
  34. }
  35. public event EventHandler<PlaybackStartEventArgs>? PlaybackStart;
  36. public event EventHandler<PlaybackProgressEventArgs>? PlaybackProgress;
  37. public event EventHandler<PlaybackStoppedEventArgs>? PlaybackStopped;
  38. public event EventHandler<MediaChangedEventArgs>? MediaChanged;
  39. public DeviceInfo Properties { get; set; }
  40. public bool IsMuted { get; set; }
  41. public int Volume
  42. {
  43. get
  44. {
  45. RefreshVolumeIfNeeded().GetAwaiter().GetResult();
  46. return _volume;
  47. }
  48. set => _volume = value;
  49. }
  50. public TimeSpan? Duration { get; set; }
  51. public TimeSpan Position { get; set; } = TimeSpan.FromSeconds(0);
  52. public TransportState TransportState { get; private set; }
  53. public bool IsPlaying => TransportState == TransportState.PLAYING;
  54. public bool IsPaused => TransportState == TransportState.PAUSED_PLAYBACK;
  55. public bool IsStopped => TransportState == TransportState.STOPPED;
  56. public Action? OnDeviceUnavailable { get; set; }
  57. private TransportCommands? AvCommands { get; set; }
  58. private TransportCommands? RendererCommands { get; set; }
  59. public UBaseObject? CurrentMediaInfo { get; private set; }
  60. public void Start()
  61. {
  62. _logger.LogDebug("Dlna Device.Start");
  63. _timer = new Timer(TimerCallback, null, 1000, Timeout.Infinite);
  64. }
  65. private Task RefreshVolumeIfNeeded()
  66. {
  67. if (_volumeRefreshActive
  68. && DateTime.UtcNow >= _lastVolumeRefresh.AddSeconds(5))
  69. {
  70. _lastVolumeRefresh = DateTime.UtcNow;
  71. return RefreshVolume();
  72. }
  73. return Task.CompletedTask;
  74. }
  75. private async Task RefreshVolume(CancellationToken cancellationToken = default)
  76. {
  77. if (_disposed)
  78. {
  79. return;
  80. }
  81. try
  82. {
  83. await GetVolume(cancellationToken).ConfigureAwait(false);
  84. await GetMute(cancellationToken).ConfigureAwait(false);
  85. }
  86. catch (Exception ex)
  87. {
  88. _logger.LogError(ex, "Error updating device volume info for {DeviceName}", Properties.Name);
  89. }
  90. }
  91. private void RestartTimer(bool immediate = false)
  92. {
  93. lock (_timerLock)
  94. {
  95. if (_disposed)
  96. {
  97. return;
  98. }
  99. _volumeRefreshActive = true;
  100. var time = immediate ? 100 : 10000;
  101. _timer?.Change(time, Timeout.Infinite);
  102. }
  103. }
  104. /// <summary>
  105. /// Restarts the timer in inactive mode.
  106. /// </summary>
  107. private void RestartTimerInactive()
  108. {
  109. lock (_timerLock)
  110. {
  111. if (_disposed)
  112. {
  113. return;
  114. }
  115. _volumeRefreshActive = false;
  116. _timer?.Change(Timeout.Infinite, Timeout.Infinite);
  117. }
  118. }
  119. public Task VolumeDown(CancellationToken cancellationToken)
  120. {
  121. var sendVolume = Math.Max(Volume - 5, 0);
  122. return SetVolume(sendVolume, cancellationToken);
  123. }
  124. public Task VolumeUp(CancellationToken cancellationToken)
  125. {
  126. var sendVolume = Math.Min(Volume + 5, 100);
  127. return SetVolume(sendVolume, cancellationToken);
  128. }
  129. public Task ToggleMute(CancellationToken cancellationToken)
  130. {
  131. if (IsMuted)
  132. {
  133. return Unmute(cancellationToken);
  134. }
  135. return Mute(cancellationToken);
  136. }
  137. public async Task Mute(CancellationToken cancellationToken)
  138. {
  139. var success = await SetMute(true, cancellationToken).ConfigureAwait(true);
  140. if (!success)
  141. {
  142. await SetVolume(0, cancellationToken).ConfigureAwait(false);
  143. }
  144. }
  145. public async Task Unmute(CancellationToken cancellationToken)
  146. {
  147. var success = await SetMute(false, cancellationToken).ConfigureAwait(true);
  148. if (!success)
  149. {
  150. var sendVolume = _muteVol <= 0 ? 20 : _muteVol;
  151. await SetVolume(sendVolume, cancellationToken).ConfigureAwait(false);
  152. }
  153. }
  154. private DeviceService? GetServiceRenderingControl()
  155. {
  156. var services = Properties.Services;
  157. return services.FirstOrDefault(s => string.Equals(s.ServiceType, "urn:schemas-upnp-org:service:RenderingControl:1", StringComparison.OrdinalIgnoreCase)) ??
  158. services.FirstOrDefault(s => (s.ServiceType ?? string.Empty).StartsWith("urn:schemas-upnp-org:service:RenderingControl", StringComparison.OrdinalIgnoreCase));
  159. }
  160. private DeviceService? GetAvTransportService()
  161. {
  162. var services = Properties.Services;
  163. return services.FirstOrDefault(s => string.Equals(s.ServiceType, "urn:schemas-upnp-org:service:AVTransport:1", StringComparison.OrdinalIgnoreCase)) ??
  164. services.FirstOrDefault(s => (s.ServiceType ?? string.Empty).StartsWith("urn:schemas-upnp-org:service:AVTransport", StringComparison.OrdinalIgnoreCase));
  165. }
  166. private async Task<bool> SetMute(bool mute, CancellationToken cancellationToken)
  167. {
  168. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  169. var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetMute");
  170. if (command is null)
  171. {
  172. return false;
  173. }
  174. var service = GetServiceRenderingControl();
  175. if (service is null)
  176. {
  177. return false;
  178. }
  179. _logger.LogDebug("Setting mute");
  180. var value = mute ? 1 : 0;
  181. await new DlnaHttpClient(_logger, _httpClientFactory)
  182. .SendCommandAsync(
  183. Properties.BaseUrl,
  184. service,
  185. command.Name,
  186. rendererCommands!.BuildPost(command, service.ServiceType, value), // null checked above
  187. cancellationToken: cancellationToken)
  188. .ConfigureAwait(false);
  189. IsMuted = mute;
  190. return true;
  191. }
  192. /// <summary>
  193. /// Sets volume on a scale of 0-100.
  194. /// </summary>
  195. /// <param name="value">The volume on a scale of 0-100.</param>
  196. /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
  197. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  198. public async Task SetVolume(int value, CancellationToken cancellationToken)
  199. {
  200. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  201. var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetVolume");
  202. if (command is null)
  203. {
  204. return;
  205. }
  206. var service = GetServiceRenderingControl() ?? throw new InvalidOperationException("Unable to find service");
  207. // Set it early and assume it will succeed
  208. // Remote control will perform better
  209. Volume = value;
  210. await new DlnaHttpClient(_logger, _httpClientFactory)
  211. .SendCommandAsync(
  212. Properties.BaseUrl,
  213. service,
  214. command.Name,
  215. rendererCommands!.BuildPost(command, service.ServiceType, value), // null checked above
  216. cancellationToken: cancellationToken)
  217. .ConfigureAwait(false);
  218. }
  219. public async Task Seek(TimeSpan value, CancellationToken cancellationToken)
  220. {
  221. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  222. var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Seek");
  223. if (command is null)
  224. {
  225. return;
  226. }
  227. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  228. await new DlnaHttpClient(_logger, _httpClientFactory)
  229. .SendCommandAsync(
  230. Properties.BaseUrl,
  231. service,
  232. command.Name,
  233. avCommands!.BuildPost(command, service.ServiceType, string.Format(CultureInfo.InvariantCulture, "{0:hh}:{0:mm}:{0:ss}", value), "REL_TIME"), // null checked above
  234. cancellationToken: cancellationToken)
  235. .ConfigureAwait(false);
  236. RestartTimer(true);
  237. }
  238. public async Task SetAvTransport(string url, string? header, string metaData, CancellationToken cancellationToken)
  239. {
  240. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  241. url = url.Replace("&", "&amp;", StringComparison.Ordinal);
  242. _logger.LogDebug("{0} - SetAvTransport Uri: {1} DlnaHeaders: {2}", Properties.Name, url, header);
  243. var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "SetAVTransportURI");
  244. if (command is null)
  245. {
  246. return;
  247. }
  248. var dictionary = new Dictionary<string, string>
  249. {
  250. { "CurrentURI", url },
  251. { "CurrentURIMetaData", CreateDidlMeta(metaData) }
  252. };
  253. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  254. var post = avCommands!.BuildPost(command, service.ServiceType, url, dictionary); // null checked above
  255. await new DlnaHttpClient(_logger, _httpClientFactory)
  256. .SendCommandAsync(
  257. Properties.BaseUrl,
  258. service,
  259. command.Name,
  260. post,
  261. header: header,
  262. cancellationToken: cancellationToken)
  263. .ConfigureAwait(false);
  264. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  265. try
  266. {
  267. await SetPlay(avCommands, cancellationToken).ConfigureAwait(false);
  268. }
  269. catch
  270. {
  271. // Some devices will throw an error if you tell it to play when it's already playing
  272. // Others won't
  273. }
  274. RestartTimer(true);
  275. }
  276. /*
  277. * SetNextAvTransport is used to specify to the DLNA device what is the next track to play.
  278. * Without that information, the next track command on the device does not work.
  279. */
  280. public async Task SetNextAvTransport(string url, string? header, string metaData, CancellationToken cancellationToken = default)
  281. {
  282. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  283. url = url.Replace("&", "&amp;", StringComparison.Ordinal);
  284. _logger.LogDebug("{PropertyName} - SetNextAvTransport Uri: {Url} DlnaHeaders: {Header}", Properties.Name, url, header);
  285. var command = avCommands?.ServiceActions.FirstOrDefault(c => string.Equals(c.Name, "SetNextAVTransportURI", StringComparison.OrdinalIgnoreCase));
  286. if (command is null)
  287. {
  288. return;
  289. }
  290. var dictionary = new Dictionary<string, string>
  291. {
  292. { "NextURI", url },
  293. { "NextURIMetaData", CreateDidlMeta(metaData) }
  294. };
  295. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  296. var post = avCommands!.BuildPost(command, service.ServiceType, url, dictionary); // null checked above
  297. await new DlnaHttpClient(_logger, _httpClientFactory)
  298. .SendCommandAsync(Properties.BaseUrl, service, command.Name, post, header, cancellationToken)
  299. .ConfigureAwait(false);
  300. }
  301. private static string CreateDidlMeta(string value)
  302. {
  303. if (string.IsNullOrEmpty(value))
  304. {
  305. return string.Empty;
  306. }
  307. return SecurityElement.Escape(value);
  308. }
  309. private Task SetPlay(TransportCommands avCommands, CancellationToken cancellationToken)
  310. {
  311. var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "Play");
  312. if (command is null)
  313. {
  314. return Task.CompletedTask;
  315. }
  316. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  317. return new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  318. Properties.BaseUrl,
  319. service,
  320. command.Name,
  321. avCommands.BuildPost(command, service.ServiceType, 1),
  322. cancellationToken: cancellationToken);
  323. }
  324. public async Task SetPlay(CancellationToken cancellationToken)
  325. {
  326. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  327. if (avCommands is null)
  328. {
  329. return;
  330. }
  331. await SetPlay(avCommands, cancellationToken).ConfigureAwait(false);
  332. RestartTimer(true);
  333. }
  334. public async Task SetStop(CancellationToken cancellationToken)
  335. {
  336. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  337. var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Stop");
  338. if (command is null)
  339. {
  340. return;
  341. }
  342. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  343. await new DlnaHttpClient(_logger, _httpClientFactory)
  344. .SendCommandAsync(
  345. Properties.BaseUrl,
  346. service,
  347. command.Name,
  348. avCommands!.BuildPost(command, service.ServiceType, 1), // null checked above
  349. cancellationToken: cancellationToken)
  350. .ConfigureAwait(false);
  351. RestartTimer(true);
  352. }
  353. public async Task SetPause(CancellationToken cancellationToken)
  354. {
  355. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  356. var command = avCommands?.ServiceActions.FirstOrDefault(c => c.Name == "Pause");
  357. if (command is null)
  358. {
  359. return;
  360. }
  361. var service = GetAvTransportService() ?? throw new InvalidOperationException("Unable to find service");
  362. await new DlnaHttpClient(_logger, _httpClientFactory)
  363. .SendCommandAsync(
  364. Properties.BaseUrl,
  365. service,
  366. command.Name,
  367. avCommands!.BuildPost(command, service.ServiceType, 1), // null checked above
  368. cancellationToken: cancellationToken)
  369. .ConfigureAwait(false);
  370. TransportState = TransportState.PAUSED_PLAYBACK;
  371. RestartTimer(true);
  372. }
  373. private async void TimerCallback(object? sender)
  374. {
  375. if (_disposed)
  376. {
  377. return;
  378. }
  379. try
  380. {
  381. var cancellationToken = CancellationToken.None;
  382. var avCommands = await GetAVProtocolAsync(cancellationToken).ConfigureAwait(false);
  383. if (avCommands is null)
  384. {
  385. return;
  386. }
  387. var transportState = await GetTransportInfo(avCommands, cancellationToken).ConfigureAwait(false);
  388. if (_disposed)
  389. {
  390. return;
  391. }
  392. if (transportState.HasValue)
  393. {
  394. // If we're not playing anything no need to get additional data
  395. if (transportState.Value == TransportState.STOPPED)
  396. {
  397. UpdateMediaInfo(null, transportState.Value);
  398. }
  399. else
  400. {
  401. var tuple = await GetPositionInfo(avCommands, cancellationToken).ConfigureAwait(false);
  402. var currentObject = tuple.Track;
  403. if (tuple.Success && currentObject is null)
  404. {
  405. currentObject = await GetMediaInfo(avCommands, cancellationToken).ConfigureAwait(false);
  406. }
  407. if (currentObject is not null)
  408. {
  409. UpdateMediaInfo(currentObject, transportState.Value);
  410. }
  411. }
  412. _connectFailureCount = 0;
  413. if (_disposed)
  414. {
  415. return;
  416. }
  417. // If we're not playing anything make sure we don't get data more often than necessary to keep the Session alive
  418. if (transportState.Value == TransportState.STOPPED)
  419. {
  420. RestartTimerInactive();
  421. }
  422. else
  423. {
  424. RestartTimer();
  425. }
  426. }
  427. else
  428. {
  429. RestartTimerInactive();
  430. }
  431. }
  432. catch (Exception ex)
  433. {
  434. if (_disposed)
  435. {
  436. return;
  437. }
  438. _logger.LogError(ex, "Error updating device info for {DeviceName}", Properties.Name);
  439. _connectFailureCount++;
  440. if (_connectFailureCount >= 3)
  441. {
  442. var action = OnDeviceUnavailable;
  443. if (action is not null)
  444. {
  445. _logger.LogDebug("Disposing device due to loss of connection");
  446. action();
  447. return;
  448. }
  449. }
  450. RestartTimerInactive();
  451. }
  452. }
  453. private async Task GetVolume(CancellationToken cancellationToken)
  454. {
  455. if (_disposed)
  456. {
  457. return;
  458. }
  459. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  460. var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetVolume");
  461. if (command is null)
  462. {
  463. return;
  464. }
  465. var service = GetServiceRenderingControl();
  466. if (service is null)
  467. {
  468. return;
  469. }
  470. var result = await new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  471. Properties.BaseUrl,
  472. service,
  473. command.Name,
  474. rendererCommands!.BuildPost(command, service.ServiceType), // null checked above
  475. cancellationToken: cancellationToken).ConfigureAwait(false);
  476. if (result is null || result.Document is null)
  477. {
  478. return;
  479. }
  480. var volume = result.Document.Descendants(UPnpNamespaces.RenderingControl + "GetVolumeResponse").Select(i => i.Element("CurrentVolume")).FirstOrDefault(i => i is not null);
  481. var volumeValue = volume?.Value;
  482. if (string.IsNullOrWhiteSpace(volumeValue))
  483. {
  484. return;
  485. }
  486. Volume = int.Parse(volumeValue, CultureInfo.InvariantCulture);
  487. if (Volume > 0)
  488. {
  489. _muteVol = Volume;
  490. }
  491. }
  492. private async Task GetMute(CancellationToken cancellationToken)
  493. {
  494. if (_disposed)
  495. {
  496. return;
  497. }
  498. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  499. var command = rendererCommands?.ServiceActions.FirstOrDefault(c => c.Name == "GetMute");
  500. if (command is null)
  501. {
  502. return;
  503. }
  504. var service = GetServiceRenderingControl();
  505. if (service is null)
  506. {
  507. return;
  508. }
  509. var result = await new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  510. Properties.BaseUrl,
  511. service,
  512. command.Name,
  513. rendererCommands!.BuildPost(command, service.ServiceType), // null checked above
  514. cancellationToken: cancellationToken).ConfigureAwait(false);
  515. if (result is null || result.Document is null)
  516. {
  517. return;
  518. }
  519. var valueNode = result.Document.Descendants(UPnpNamespaces.RenderingControl + "GetMuteResponse")
  520. .Select(i => i.Element("CurrentMute"))
  521. .FirstOrDefault(i => i is not null);
  522. IsMuted = string.Equals(valueNode?.Value, "1", StringComparison.OrdinalIgnoreCase);
  523. }
  524. private async Task<TransportState?> GetTransportInfo(TransportCommands avCommands, CancellationToken cancellationToken)
  525. {
  526. var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetTransportInfo");
  527. if (command is null)
  528. {
  529. return null;
  530. }
  531. var service = GetAvTransportService();
  532. if (service is null)
  533. {
  534. return null;
  535. }
  536. var result = await new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  537. Properties.BaseUrl,
  538. service,
  539. command.Name,
  540. avCommands.BuildPost(command, service.ServiceType),
  541. cancellationToken: cancellationToken).ConfigureAwait(false);
  542. if (result is null || result.Document is null)
  543. {
  544. return null;
  545. }
  546. var transportState =
  547. result.Document.Descendants(UPnpNamespaces.AvTransport + "GetTransportInfoResponse").Select(i => i.Element("CurrentTransportState")).FirstOrDefault(i => i is not null);
  548. var transportStateValue = transportState?.Value;
  549. if (transportStateValue is not null
  550. && Enum.TryParse(transportStateValue, true, out TransportState state))
  551. {
  552. return state;
  553. }
  554. return null;
  555. }
  556. private async Task<UBaseObject?> GetMediaInfo(TransportCommands avCommands, CancellationToken cancellationToken)
  557. {
  558. var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetMediaInfo");
  559. if (command is null)
  560. {
  561. return null;
  562. }
  563. var service = GetAvTransportService();
  564. if (service is null)
  565. {
  566. throw new InvalidOperationException("Unable to find service");
  567. }
  568. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  569. if (rendererCommands is null)
  570. {
  571. return null;
  572. }
  573. var result = await new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  574. Properties.BaseUrl,
  575. service,
  576. command.Name,
  577. rendererCommands.BuildPost(command, service.ServiceType),
  578. cancellationToken: cancellationToken).ConfigureAwait(false);
  579. if (result is null || result.Document is null)
  580. {
  581. return null;
  582. }
  583. var track = result.Document.Descendants("CurrentURIMetaData").FirstOrDefault();
  584. if (track is null)
  585. {
  586. return null;
  587. }
  588. var e = track.Element(UPnpNamespaces.Items) ?? track;
  589. var elementString = (string)e;
  590. if (!string.IsNullOrWhiteSpace(elementString))
  591. {
  592. return UpnpContainer.Create(e);
  593. }
  594. track = result.Document.Descendants("CurrentURI").FirstOrDefault();
  595. if (track is null)
  596. {
  597. return null;
  598. }
  599. e = track.Element(UPnpNamespaces.Items) ?? track;
  600. elementString = (string)e;
  601. if (!string.IsNullOrWhiteSpace(elementString))
  602. {
  603. return new UBaseObject
  604. {
  605. Url = elementString
  606. };
  607. }
  608. return null;
  609. }
  610. private async Task<(bool Success, UBaseObject? Track)> GetPositionInfo(TransportCommands avCommands, CancellationToken cancellationToken)
  611. {
  612. var command = avCommands.ServiceActions.FirstOrDefault(c => c.Name == "GetPositionInfo");
  613. if (command is null)
  614. {
  615. return (false, null);
  616. }
  617. var service = GetAvTransportService();
  618. if (service is null)
  619. {
  620. throw new InvalidOperationException("Unable to find service");
  621. }
  622. var rendererCommands = await GetRenderingProtocolAsync(cancellationToken).ConfigureAwait(false);
  623. if (rendererCommands is null)
  624. {
  625. return (false, null);
  626. }
  627. var result = await new DlnaHttpClient(_logger, _httpClientFactory).SendCommandAsync(
  628. Properties.BaseUrl,
  629. service,
  630. command.Name,
  631. rendererCommands.BuildPost(command, service.ServiceType),
  632. cancellationToken: cancellationToken).ConfigureAwait(false);
  633. if (result is null || result.Document is null)
  634. {
  635. return (false, null);
  636. }
  637. var trackUriElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackURI")).FirstOrDefault(i => i is not null);
  638. var trackUri = trackUriElem?.Value;
  639. var durationElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("TrackDuration")).FirstOrDefault(i => i is not null);
  640. var duration = durationElem?.Value;
  641. if (!string.IsNullOrWhiteSpace(duration)
  642. && !string.Equals(duration, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
  643. {
  644. Duration = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
  645. }
  646. else
  647. {
  648. Duration = null;
  649. }
  650. var positionElem = result.Document.Descendants(UPnpNamespaces.AvTransport + "GetPositionInfoResponse").Select(i => i.Element("RelTime")).FirstOrDefault(i => i is not null);
  651. var position = positionElem?.Value;
  652. if (!string.IsNullOrWhiteSpace(position) && !string.Equals(position, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
  653. {
  654. Position = TimeSpan.Parse(position, CultureInfo.InvariantCulture);
  655. }
  656. var track = result.Document.Descendants("TrackMetaData").FirstOrDefault();
  657. if (track is null)
  658. {
  659. // If track is null, some vendors do this, use GetMediaInfo instead.
  660. return (true, null);
  661. }
  662. var trackString = (string)track;
  663. if (string.IsNullOrWhiteSpace(trackString) || string.Equals(trackString, "NOT_IMPLEMENTED", StringComparison.OrdinalIgnoreCase))
  664. {
  665. return (true, null);
  666. }
  667. XElement? uPnpResponse = null;
  668. try
  669. {
  670. uPnpResponse = ParseResponse(trackString);
  671. }
  672. catch (Exception ex)
  673. {
  674. _logger.LogError(ex, "Uncaught exception while parsing xml");
  675. }
  676. if (uPnpResponse is null)
  677. {
  678. _logger.LogError("Failed to parse xml: \n {Xml}", trackString);
  679. return (true, null);
  680. }
  681. var e = uPnpResponse.Element(UPnpNamespaces.Items);
  682. var uTrack = CreateUBaseObject(e, trackUri);
  683. return (true, uTrack);
  684. }
  685. private XElement? ParseResponse(string xml)
  686. {
  687. // Handle different variations sent back by devices.
  688. try
  689. {
  690. return XElement.Parse(xml);
  691. }
  692. catch (XmlException)
  693. {
  694. }
  695. // first try to add a root node with a dlna namespace.
  696. try
  697. {
  698. return XElement.Parse("<data xmlns:dlna=\"urn:schemas-dlna-org:device-1-0\">" + xml + "</data>")
  699. .Descendants()
  700. .First();
  701. }
  702. catch (XmlException)
  703. {
  704. }
  705. // some devices send back invalid xml
  706. try
  707. {
  708. return XElement.Parse(xml.Replace("&", "&amp;", StringComparison.Ordinal));
  709. }
  710. catch (XmlException)
  711. {
  712. }
  713. return null;
  714. }
  715. private static UBaseObject CreateUBaseObject(XElement? container, string? trackUri)
  716. {
  717. ArgumentNullException.ThrowIfNull(container);
  718. var url = container.GetValue(UPnpNamespaces.Res);
  719. if (string.IsNullOrWhiteSpace(url))
  720. {
  721. url = trackUri;
  722. }
  723. return new UBaseObject
  724. {
  725. Id = container.GetAttributeValue(UPnpNamespaces.Id),
  726. ParentId = container.GetAttributeValue(UPnpNamespaces.ParentId),
  727. Title = container.GetValue(UPnpNamespaces.Title),
  728. IconUrl = container.GetValue(UPnpNamespaces.Artwork),
  729. SecondText = string.Empty,
  730. Url = url,
  731. ProtocolInfo = GetProtocolInfo(container),
  732. MetaData = container.ToString()
  733. };
  734. }
  735. private static string[] GetProtocolInfo(XElement container)
  736. {
  737. ArgumentNullException.ThrowIfNull(container);
  738. var resElement = container.Element(UPnpNamespaces.Res);
  739. var info = resElement?.Attribute(UPnpNamespaces.ProtocolInfo);
  740. if (info is not null && !string.IsNullOrWhiteSpace(info.Value))
  741. {
  742. return info.Value.Split(':');
  743. }
  744. return new string[4];
  745. }
  746. private async Task<TransportCommands?> GetAVProtocolAsync(CancellationToken cancellationToken)
  747. {
  748. if (AvCommands is not null)
  749. {
  750. return AvCommands;
  751. }
  752. if (_disposed)
  753. {
  754. throw new ObjectDisposedException(GetType().Name);
  755. }
  756. var avService = GetAvTransportService();
  757. if (avService is null)
  758. {
  759. return null;
  760. }
  761. string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
  762. var httpClient = new DlnaHttpClient(_logger, _httpClientFactory);
  763. var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
  764. if (document is null)
  765. {
  766. return null;
  767. }
  768. AvCommands = TransportCommands.Create(document);
  769. return AvCommands;
  770. }
  771. private async Task<TransportCommands?> GetRenderingProtocolAsync(CancellationToken cancellationToken)
  772. {
  773. if (RendererCommands is not null)
  774. {
  775. return RendererCommands;
  776. }
  777. if (_disposed)
  778. {
  779. throw new ObjectDisposedException(GetType().Name);
  780. }
  781. var avService = GetServiceRenderingControl();
  782. ArgumentNullException.ThrowIfNull(avService);
  783. string url = NormalizeUrl(Properties.BaseUrl, avService.ScpdUrl);
  784. var httpClient = new DlnaHttpClient(_logger, _httpClientFactory);
  785. _logger.LogDebug("Dlna Device.GetRenderingProtocolAsync");
  786. var document = await httpClient.GetDataAsync(url, cancellationToken).ConfigureAwait(false);
  787. if (document is null)
  788. {
  789. return null;
  790. }
  791. RendererCommands = TransportCommands.Create(document);
  792. return RendererCommands;
  793. }
  794. private string NormalizeUrl(string baseUrl, string url)
  795. {
  796. // If it's already a complete url, don't stick anything onto the front of it
  797. if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  798. {
  799. return url;
  800. }
  801. if (!url.Contains('/', StringComparison.Ordinal))
  802. {
  803. url = "/dmr/" + url;
  804. }
  805. if (!url.StartsWith('/'))
  806. {
  807. url = "/" + url;
  808. }
  809. return baseUrl + url;
  810. }
  811. public static async Task<Device?> CreateuPnpDeviceAsync(Uri url, IHttpClientFactory httpClientFactory, ILogger logger, CancellationToken cancellationToken)
  812. {
  813. var ssdpHttpClient = new DlnaHttpClient(logger, httpClientFactory);
  814. var document = await ssdpHttpClient.GetDataAsync(url.ToString(), cancellationToken).ConfigureAwait(false);
  815. if (document is null)
  816. {
  817. return null;
  818. }
  819. var friendlyNames = new List<string>();
  820. var name = document.Descendants(UPnpNamespaces.Ud.GetName("friendlyName")).FirstOrDefault();
  821. if (name is not null && !string.IsNullOrWhiteSpace(name.Value))
  822. {
  823. friendlyNames.Add(name.Value);
  824. }
  825. var room = document.Descendants(UPnpNamespaces.Ud.GetName("roomName")).FirstOrDefault();
  826. if (room is not null && !string.IsNullOrWhiteSpace(room.Value))
  827. {
  828. friendlyNames.Add(room.Value);
  829. }
  830. var deviceProperties = new DeviceInfo()
  831. {
  832. Name = string.Join(' ', friendlyNames),
  833. BaseUrl = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", url.Host, url.Port)
  834. };
  835. var model = document.Descendants(UPnpNamespaces.Ud.GetName("modelName")).FirstOrDefault();
  836. if (model is not null)
  837. {
  838. deviceProperties.ModelName = model.Value;
  839. }
  840. var modelNumber = document.Descendants(UPnpNamespaces.Ud.GetName("modelNumber")).FirstOrDefault();
  841. if (modelNumber is not null)
  842. {
  843. deviceProperties.ModelNumber = modelNumber.Value;
  844. }
  845. var uuid = document.Descendants(UPnpNamespaces.Ud.GetName("UDN")).FirstOrDefault();
  846. if (uuid is not null)
  847. {
  848. deviceProperties.UUID = uuid.Value;
  849. }
  850. var manufacturer = document.Descendants(UPnpNamespaces.Ud.GetName("manufacturer")).FirstOrDefault();
  851. if (manufacturer is not null)
  852. {
  853. deviceProperties.Manufacturer = manufacturer.Value;
  854. }
  855. var manufacturerUrl = document.Descendants(UPnpNamespaces.Ud.GetName("manufacturerURL")).FirstOrDefault();
  856. if (manufacturerUrl is not null)
  857. {
  858. deviceProperties.ManufacturerUrl = manufacturerUrl.Value;
  859. }
  860. var presentationUrl = document.Descendants(UPnpNamespaces.Ud.GetName("presentationURL")).FirstOrDefault();
  861. if (presentationUrl is not null)
  862. {
  863. deviceProperties.PresentationUrl = presentationUrl.Value;
  864. }
  865. var modelUrl = document.Descendants(UPnpNamespaces.Ud.GetName("modelURL")).FirstOrDefault();
  866. if (modelUrl is not null)
  867. {
  868. deviceProperties.ModelUrl = modelUrl.Value;
  869. }
  870. var serialNumber = document.Descendants(UPnpNamespaces.Ud.GetName("serialNumber")).FirstOrDefault();
  871. if (serialNumber is not null)
  872. {
  873. deviceProperties.SerialNumber = serialNumber.Value;
  874. }
  875. var modelDescription = document.Descendants(UPnpNamespaces.Ud.GetName("modelDescription")).FirstOrDefault();
  876. if (modelDescription is not null)
  877. {
  878. deviceProperties.ModelDescription = modelDescription.Value;
  879. }
  880. var icon = document.Descendants(UPnpNamespaces.Ud.GetName("icon")).FirstOrDefault();
  881. if (icon is not null)
  882. {
  883. deviceProperties.Icon = CreateIcon(icon);
  884. }
  885. foreach (var services in document.Descendants(UPnpNamespaces.Ud.GetName("serviceList")))
  886. {
  887. if (services is null)
  888. {
  889. continue;
  890. }
  891. var servicesList = services.Descendants(UPnpNamespaces.Ud.GetName("service"));
  892. if (servicesList is null)
  893. {
  894. continue;
  895. }
  896. foreach (var element in servicesList)
  897. {
  898. var service = Create(element);
  899. if (service is not null)
  900. {
  901. deviceProperties.Services.Add(service);
  902. }
  903. }
  904. }
  905. return new Device(deviceProperties, httpClientFactory, logger);
  906. }
  907. private static DeviceIcon CreateIcon(XElement element)
  908. {
  909. ArgumentNullException.ThrowIfNull(element);
  910. var width = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("width"));
  911. var height = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("height"));
  912. _ = int.TryParse(width, NumberStyles.Integer, CultureInfo.InvariantCulture, out var widthValue);
  913. _ = int.TryParse(height, NumberStyles.Integer, CultureInfo.InvariantCulture, out var heightValue);
  914. return new DeviceIcon
  915. {
  916. Depth = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("depth")) ?? string.Empty,
  917. Height = heightValue,
  918. MimeType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("mimetype")) ?? string.Empty,
  919. Url = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("url")) ?? string.Empty,
  920. Width = widthValue
  921. };
  922. }
  923. private static DeviceService Create(XElement element)
  924. => new DeviceService()
  925. {
  926. ControlUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("controlURL")) ?? string.Empty,
  927. EventSubUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("eventSubURL")) ?? string.Empty,
  928. ScpdUrl = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("SCPDURL")) ?? string.Empty,
  929. ServiceId = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceId")) ?? string.Empty,
  930. ServiceType = element.GetDescendantValue(UPnpNamespaces.Ud.GetName("serviceType")) ?? string.Empty
  931. };
  932. private void UpdateMediaInfo(UBaseObject? mediaInfo, TransportState state)
  933. {
  934. TransportState = state;
  935. var previousMediaInfo = CurrentMediaInfo;
  936. CurrentMediaInfo = mediaInfo;
  937. if (mediaInfo is null)
  938. {
  939. if (previousMediaInfo is not null)
  940. {
  941. OnPlaybackStop(previousMediaInfo);
  942. }
  943. }
  944. else if (previousMediaInfo is null)
  945. {
  946. if (state != TransportState.STOPPED)
  947. {
  948. OnPlaybackStart(mediaInfo);
  949. }
  950. }
  951. else if (mediaInfo.Equals(previousMediaInfo))
  952. {
  953. OnPlaybackProgress(mediaInfo);
  954. }
  955. else
  956. {
  957. OnMediaChanged(previousMediaInfo, mediaInfo);
  958. }
  959. }
  960. private void OnPlaybackStart(UBaseObject mediaInfo)
  961. {
  962. if (string.IsNullOrWhiteSpace(mediaInfo.Url))
  963. {
  964. return;
  965. }
  966. PlaybackStart?.Invoke(this, new PlaybackStartEventArgs(mediaInfo));
  967. }
  968. private void OnPlaybackProgress(UBaseObject mediaInfo)
  969. {
  970. if (string.IsNullOrWhiteSpace(mediaInfo.Url))
  971. {
  972. return;
  973. }
  974. PlaybackProgress?.Invoke(this, new PlaybackProgressEventArgs(mediaInfo));
  975. }
  976. private void OnPlaybackStop(UBaseObject mediaInfo)
  977. {
  978. PlaybackStopped?.Invoke(this, new PlaybackStoppedEventArgs(mediaInfo));
  979. }
  980. private void OnMediaChanged(UBaseObject old, UBaseObject newMedia)
  981. {
  982. MediaChanged?.Invoke(this, new MediaChangedEventArgs(old, newMedia));
  983. }
  984. /// <inheritdoc />
  985. public void Dispose()
  986. {
  987. Dispose(true);
  988. GC.SuppressFinalize(this);
  989. }
  990. /// <summary>
  991. /// Releases unmanaged and optionally managed resources.
  992. /// </summary>
  993. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  994. protected virtual void Dispose(bool disposing)
  995. {
  996. if (_disposed)
  997. {
  998. return;
  999. }
  1000. if (disposing)
  1001. {
  1002. _timer?.Dispose();
  1003. }
  1004. _timer = null;
  1005. Properties = null!;
  1006. _disposed = true;
  1007. }
  1008. /// <inheritdoc />
  1009. public override string ToString()
  1010. {
  1011. return string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Properties.Name, Properties.BaseUrl);
  1012. }
  1013. }
  1014. }