Device.cs 35 KB

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