Device.cs 43 KB

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