Device.cs 36 KB

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