Device.cs 37 KB

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