Device.cs 37 KB

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