Device.cs 34 KB

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