Device.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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)
  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. throw new InvalidOperationException("Unable to find service");
  371. }
  372. var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType))
  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. throw new InvalidOperationException("Unable to find service");
  395. }
  396. var result = await new SsdpHttpClient(_httpClient, _config).SendCommandAsync(Properties.BaseUrl, service, command.Name, RendererCommands.BuildPost(command, service.ServiceType))
  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))
  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))
  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))
  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. 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, trackUri);
  507. return new Tuple<bool, uBaseObject>(true, uTrack);
  508. }
  509. private static uBaseObject CreateUBaseObject(XElement container, string trackUri)
  510. {
  511. if (container == null)
  512. {
  513. throw new ArgumentNullException("container");
  514. }
  515. var url = container.GetValue(uPnpNamespaces.Res);
  516. if (string.IsNullOrWhiteSpace(url))
  517. {
  518. url = trackUri;
  519. }
  520. return new uBaseObject
  521. {
  522. Id = container.GetAttributeValue(uPnpNamespaces.Id),
  523. ParentId = container.GetAttributeValue(uPnpNamespaces.ParentId),
  524. Title = container.GetValue(uPnpNamespaces.title),
  525. IconUrl = container.GetValue(uPnpNamespaces.Artwork),
  526. SecondText = "",
  527. Url = url,
  528. ProtocolInfo = GetProtocolInfo(container),
  529. MetaData = container.ToString()
  530. };
  531. }
  532. private static string[] GetProtocolInfo(XElement container)
  533. {
  534. if (container == null)
  535. {
  536. throw new ArgumentNullException("container");
  537. }
  538. var resElement = container.Element(uPnpNamespaces.Res);
  539. if (resElement != null)
  540. {
  541. var info = resElement.Attribute(uPnpNamespaces.ProtocolInfo);
  542. if (info != null && !string.IsNullOrWhiteSpace(info.Value))
  543. {
  544. return info.Value.Split(':');
  545. }
  546. }
  547. return new string[4];
  548. }
  549. #endregion
  550. #region From XML
  551. private async Task GetAVProtocolAsync()
  552. {
  553. var avService = Properties.Services.FirstOrDefault(s => s.ServiceType == ServiceAvtransportType);
  554. if (avService == null)
  555. return;
  556. var url = avService.ScpdUrl;
  557. if (!url.Contains("/"))
  558. url = "/dmr/" + url;
  559. if (!url.StartsWith("/"))
  560. url = "/" + url;
  561. var httpClient = new SsdpHttpClient(_httpClient, _config);
  562. var document = await httpClient.GetDataAsync(Properties.BaseUrl + url);
  563. AvCommands = TransportCommands.Create(document);
  564. }
  565. private async Task GetRenderingProtocolAsync()
  566. {
  567. var avService = Properties.Services.FirstOrDefault(s => s.ServiceType == ServiceRenderingType);
  568. if (avService == null)
  569. return;
  570. string url = avService.ScpdUrl;
  571. if (!url.Contains("/"))
  572. url = "/dmr/" + url;
  573. if (!url.StartsWith("/"))
  574. url = "/" + url;
  575. var httpClient = new SsdpHttpClient(_httpClient, _config);
  576. var document = await httpClient.GetDataAsync(Properties.BaseUrl + url);
  577. RendererCommands = TransportCommands.Create(document);
  578. }
  579. private TransportCommands AvCommands
  580. {
  581. get;
  582. set;
  583. }
  584. internal TransportCommands RendererCommands
  585. {
  586. get;
  587. set;
  588. }
  589. public static async Task<Device> CreateuPnpDeviceAsync(Uri url, IHttpClient httpClient, IServerConfigurationManager config, ILogger logger)
  590. {
  591. var ssdpHttpClient = new SsdpHttpClient(httpClient, config);
  592. var document = await ssdpHttpClient.GetDataAsync(url.ToString()).ConfigureAwait(false);
  593. var deviceProperties = new DeviceInfo();
  594. var friendlyNames = new List<string>();
  595. var name = document.Descendants(uPnpNamespaces.ud.GetName("friendlyName")).FirstOrDefault();
  596. if (name != null && !string.IsNullOrWhiteSpace(name.Value))
  597. friendlyNames.Add(name.Value);
  598. var room = document.Descendants(uPnpNamespaces.ud.GetName("roomName")).FirstOrDefault();
  599. if (room != null && !string.IsNullOrWhiteSpace(room.Value))
  600. friendlyNames.Add(room.Value);
  601. deviceProperties.Name = string.Join(" ", friendlyNames.ToArray());
  602. var model = document.Descendants(uPnpNamespaces.ud.GetName("modelName")).FirstOrDefault();
  603. if (model != null)
  604. deviceProperties.ModelName = model.Value;
  605. var modelNumber = document.Descendants(uPnpNamespaces.ud.GetName("modelNumber")).FirstOrDefault();
  606. if (modelNumber != null)
  607. deviceProperties.ModelNumber = modelNumber.Value;
  608. var uuid = document.Descendants(uPnpNamespaces.ud.GetName("UDN")).FirstOrDefault();
  609. if (uuid != null)
  610. deviceProperties.UUID = uuid.Value;
  611. var manufacturer = document.Descendants(uPnpNamespaces.ud.GetName("manufacturer")).FirstOrDefault();
  612. if (manufacturer != null)
  613. deviceProperties.Manufacturer = manufacturer.Value;
  614. var manufacturerUrl = document.Descendants(uPnpNamespaces.ud.GetName("manufacturerURL")).FirstOrDefault();
  615. if (manufacturerUrl != null)
  616. deviceProperties.ManufacturerUrl = manufacturerUrl.Value;
  617. var presentationUrl = document.Descendants(uPnpNamespaces.ud.GetName("presentationURL")).FirstOrDefault();
  618. if (presentationUrl != null)
  619. deviceProperties.PresentationUrl = presentationUrl.Value;
  620. var modelUrl = document.Descendants(uPnpNamespaces.ud.GetName("modelURL")).FirstOrDefault();
  621. if (modelUrl != null)
  622. deviceProperties.ModelUrl = modelUrl.Value;
  623. var serialNumber = document.Descendants(uPnpNamespaces.ud.GetName("serialNumber")).FirstOrDefault();
  624. if (serialNumber != null)
  625. deviceProperties.SerialNumber = serialNumber.Value;
  626. var modelDescription = document.Descendants(uPnpNamespaces.ud.GetName("modelDescription")).FirstOrDefault();
  627. if (modelDescription != null)
  628. deviceProperties.ModelDescription = modelDescription.Value;
  629. deviceProperties.BaseUrl = String.Format("http://{0}:{1}", url.Host, url.Port);
  630. var icon = document.Descendants(uPnpNamespaces.ud.GetName("icon")).FirstOrDefault();
  631. if (icon != null)
  632. {
  633. deviceProperties.Icon = CreateIcon(icon);
  634. }
  635. var isRenderer = false;
  636. foreach (var services in document.Descendants(uPnpNamespaces.ud.GetName("serviceList")))
  637. {
  638. if (services == null)
  639. continue;
  640. var servicesList = services.Descendants(uPnpNamespaces.ud.GetName("service"));
  641. if (servicesList == null)
  642. continue;
  643. foreach (var element in servicesList)
  644. {
  645. var service = Create(element);
  646. if (service != null)
  647. {
  648. deviceProperties.Services.Add(service);
  649. if (service.ServiceType == ServiceAvtransportType)
  650. {
  651. isRenderer = true;
  652. }
  653. }
  654. }
  655. }
  656. var device = new Device(deviceProperties, httpClient, logger, config);
  657. if (isRenderer)
  658. {
  659. await device.GetRenderingProtocolAsync().ConfigureAwait(false);
  660. await device.GetAVProtocolAsync().ConfigureAwait(false);
  661. }
  662. return device;
  663. }
  664. #endregion
  665. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  666. private static DeviceIcon CreateIcon(XElement element)
  667. {
  668. if (element == null)
  669. {
  670. throw new ArgumentNullException("element");
  671. }
  672. var mimeType = element.GetDescendantValue(uPnpNamespaces.ud.GetName("mimetype"));
  673. var width = element.GetDescendantValue(uPnpNamespaces.ud.GetName("width"));
  674. var height = element.GetDescendantValue(uPnpNamespaces.ud.GetName("height"));
  675. var depth = element.GetDescendantValue(uPnpNamespaces.ud.GetName("depth"));
  676. var url = element.GetDescendantValue(uPnpNamespaces.ud.GetName("url"));
  677. var widthValue = int.Parse(width, NumberStyles.Any, UsCulture);
  678. var heightValue = int.Parse(height, NumberStyles.Any, UsCulture);
  679. return new DeviceIcon
  680. {
  681. Depth = depth,
  682. Height = heightValue,
  683. MimeType = mimeType,
  684. Url = url,
  685. Width = widthValue
  686. };
  687. }
  688. private static DeviceService Create(XElement element)
  689. {
  690. var type = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceType"));
  691. var id = element.GetDescendantValue(uPnpNamespaces.ud.GetName("serviceId"));
  692. var scpdUrl = element.GetDescendantValue(uPnpNamespaces.ud.GetName("SCPDURL"));
  693. var controlURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("controlURL"));
  694. var eventSubURL = element.GetDescendantValue(uPnpNamespaces.ud.GetName("eventSubURL"));
  695. return new DeviceService
  696. {
  697. ControlUrl = controlURL,
  698. EventSubUrl = eventSubURL,
  699. ScpdUrl = scpdUrl,
  700. ServiceId = id,
  701. ServiceType = type
  702. };
  703. }
  704. public event EventHandler<PlaybackStartEventArgs> PlaybackStart;
  705. public event EventHandler<PlaybackProgressEventArgs> PlaybackProgress;
  706. public event EventHandler<PlaybackStoppedEventArgs> PlaybackStopped;
  707. public event EventHandler<MediaChangedEventArgs> MediaChanged;
  708. public uBaseObject CurrentMediaInfo { get; private set; }
  709. private void UpdateMediaInfo(uBaseObject mediaInfo, TRANSPORTSTATE state)
  710. {
  711. TransportState = state;
  712. var previousMediaInfo = CurrentMediaInfo;
  713. CurrentMediaInfo = mediaInfo;
  714. if (previousMediaInfo == null && mediaInfo != null)
  715. {
  716. if (state != TRANSPORTSTATE.STOPPED)
  717. {
  718. OnPlaybackStart(mediaInfo);
  719. }
  720. }
  721. else if (mediaInfo != null && previousMediaInfo != null && !mediaInfo.Equals(previousMediaInfo))
  722. {
  723. OnMediaChanged(previousMediaInfo, mediaInfo);
  724. }
  725. else if (mediaInfo == null && previousMediaInfo != null)
  726. {
  727. OnPlaybackStop(previousMediaInfo);
  728. }
  729. else if (mediaInfo != null && mediaInfo.Equals(previousMediaInfo))
  730. {
  731. OnPlaybackProgress(mediaInfo);
  732. }
  733. }
  734. private void OnPlaybackStart(uBaseObject mediaInfo)
  735. {
  736. if (PlaybackStart != null)
  737. {
  738. PlaybackStart.Invoke(this, new PlaybackStartEventArgs
  739. {
  740. MediaInfo = mediaInfo
  741. });
  742. }
  743. }
  744. private void OnPlaybackProgress(uBaseObject mediaInfo)
  745. {
  746. if (PlaybackProgress != null)
  747. {
  748. PlaybackProgress.Invoke(this, new PlaybackProgressEventArgs
  749. {
  750. MediaInfo = mediaInfo
  751. });
  752. }
  753. }
  754. private void OnPlaybackStop(uBaseObject mediaInfo)
  755. {
  756. if (PlaybackStopped != null)
  757. {
  758. PlaybackStopped.Invoke(this, new PlaybackStoppedEventArgs
  759. {
  760. MediaInfo = mediaInfo
  761. });
  762. }
  763. }
  764. private void OnMediaChanged(uBaseObject old, uBaseObject newMedia)
  765. {
  766. if (MediaChanged != null)
  767. {
  768. MediaChanged.Invoke(this, new MediaChangedEventArgs
  769. {
  770. OldMediaInfo = old,
  771. NewMediaInfo = newMedia
  772. });
  773. }
  774. }
  775. #region IDisposable
  776. bool _disposed;
  777. public void Dispose()
  778. {
  779. if (!_disposed)
  780. {
  781. _disposed = true;
  782. DisposeTimer();
  783. DisposeVolumeTimer();
  784. }
  785. }
  786. private void DisposeTimer()
  787. {
  788. if (_timer != null)
  789. {
  790. _timer.Dispose();
  791. _timer = null;
  792. }
  793. }
  794. private void DisposeVolumeTimer()
  795. {
  796. if (_volumeTimer != null)
  797. {
  798. _volumeTimer.Dispose();
  799. _volumeTimer = null;
  800. }
  801. }
  802. #endregion
  803. public override string ToString()
  804. {
  805. return String.Format("{0} - {1}", Properties.Name, Properties.BaseUrl);
  806. }
  807. }
  808. }