Device.cs 40 KB

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