Device.cs 36 KB

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