Device.cs 39 KB

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