EmbyTV.cs 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Security;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.FileOrganization;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Events;
  15. using MediaBrowser.Model.LiveTv;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Model.Serialization;
  18. using System;
  19. using System.Collections.Concurrent;
  20. using System.Collections.Generic;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading;
  26. using System.Threading.Tasks;
  27. using System.Xml;
  28. using MediaBrowser.Model.IO;
  29. using MediaBrowser.Common.Events;
  30. using MediaBrowser.Common.Extensions;
  31. using MediaBrowser.Common.IO;
  32. using MediaBrowser.Controller;
  33. using MediaBrowser.Controller.Entities;
  34. using MediaBrowser.Controller.Entities.TV;
  35. using MediaBrowser.Controller.IO;
  36. using MediaBrowser.Model.Configuration;
  37. using MediaBrowser.Model.Diagnostics;
  38. using MediaBrowser.Model.FileOrganization;
  39. using MediaBrowser.Model.System;
  40. using MediaBrowser.Model.Threading;
  41. using MediaBrowser.Model.Extensions;
  42. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  43. {
  44. public class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable
  45. {
  46. private readonly IServerApplicationHost _appHost;
  47. private readonly ILogger _logger;
  48. private readonly IHttpClient _httpClient;
  49. private readonly IServerConfigurationManager _config;
  50. private readonly IJsonSerializer _jsonSerializer;
  51. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  52. private readonly TimerManager _timerProvider;
  53. private readonly LiveTvManager _liveTvManager;
  54. private readonly IFileSystem _fileSystem;
  55. private readonly ILibraryMonitor _libraryMonitor;
  56. private readonly ILibraryManager _libraryManager;
  57. private readonly IProviderManager _providerManager;
  58. private readonly IFileOrganizationService _organizationService;
  59. private readonly IMediaEncoder _mediaEncoder;
  60. private readonly IProcessFactory _processFactory;
  61. private readonly ISystemEvents _systemEvents;
  62. public static EmbyTV Current;
  63. public event EventHandler DataSourceChanged;
  64. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  65. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  66. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  67. public EmbyTV(IServerApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, ITimerFactory timerFactory, IProcessFactory processFactory, ISystemEvents systemEvents)
  68. {
  69. Current = this;
  70. _appHost = appHost;
  71. _logger = logger;
  72. _httpClient = httpClient;
  73. _config = config;
  74. _fileSystem = fileSystem;
  75. _libraryManager = libraryManager;
  76. _libraryMonitor = libraryMonitor;
  77. _providerManager = providerManager;
  78. _organizationService = organizationService;
  79. _mediaEncoder = mediaEncoder;
  80. _processFactory = processFactory;
  81. _systemEvents = systemEvents;
  82. _liveTvManager = (LiveTvManager)liveTvManager;
  83. _jsonSerializer = jsonSerializer;
  84. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  85. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory);
  86. _timerProvider.TimerFired += _timerProvider_TimerFired;
  87. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  88. }
  89. private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  90. {
  91. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  92. {
  93. OnRecordingFoldersChanged();
  94. }
  95. }
  96. public void Start()
  97. {
  98. _timerProvider.RestartTimers();
  99. _systemEvents.Resume += _systemEvents_Resume;
  100. CreateRecordingFolders();
  101. }
  102. private void _systemEvents_Resume(object sender, EventArgs e)
  103. {
  104. _timerProvider.RestartTimers();
  105. }
  106. private void OnRecordingFoldersChanged()
  107. {
  108. CreateRecordingFolders();
  109. }
  110. internal void CreateRecordingFolders()
  111. {
  112. try
  113. {
  114. CreateRecordingFoldersInternal();
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error creating recording folders", ex);
  119. }
  120. }
  121. internal void CreateRecordingFoldersInternal()
  122. {
  123. var recordingFolders = GetRecordingFolders();
  124. var virtualFolders = _libraryManager.GetVirtualFolders()
  125. .ToList();
  126. var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
  127. var pathsAdded = new List<string>();
  128. foreach (var recordingFolder in recordingFolders)
  129. {
  130. var pathsToCreate = recordingFolder.Locations
  131. .Where(i => !allExistingPaths.Any(p => _fileSystem.AreEqual(p, i)))
  132. .ToList();
  133. if (pathsToCreate.Count == 0)
  134. {
  135. continue;
  136. }
  137. var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo { Path = i }).ToArray();
  138. var libraryOptions = new LibraryOptions
  139. {
  140. PathInfos = mediaPathInfos
  141. };
  142. try
  143. {
  144. _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, libraryOptions, true);
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error creating virtual folder", ex);
  149. }
  150. pathsAdded.AddRange(pathsToCreate);
  151. }
  152. var config = GetConfiguration();
  153. var pathsToRemove = config.MediaLocationsCreated
  154. .Except(recordingFolders.SelectMany(i => i.Locations))
  155. .ToList();
  156. if (pathsAdded.Count > 0 || pathsToRemove.Count > 0)
  157. {
  158. pathsAdded.InsertRange(0, config.MediaLocationsCreated);
  159. config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  160. _config.SaveConfiguration("livetv", config);
  161. }
  162. foreach (var path in pathsToRemove)
  163. {
  164. RemovePathFromLibrary(path);
  165. }
  166. }
  167. private void RemovePathFromLibrary(string path)
  168. {
  169. _logger.Debug("Removing path from library: {0}", path);
  170. var requiresRefresh = false;
  171. var virtualFolders = _libraryManager.GetVirtualFolders()
  172. .ToList();
  173. foreach (var virtualFolder in virtualFolders)
  174. {
  175. if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase))
  176. {
  177. continue;
  178. }
  179. if (virtualFolder.Locations.Count == 1)
  180. {
  181. // remove entire virtual folder
  182. try
  183. {
  184. _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true);
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error removing virtual folder", ex);
  189. }
  190. }
  191. else
  192. {
  193. try
  194. {
  195. _libraryManager.RemoveMediaPath(virtualFolder.Name, path);
  196. requiresRefresh = true;
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.ErrorException("Error removing media path", ex);
  201. }
  202. }
  203. }
  204. if (requiresRefresh)
  205. {
  206. _libraryManager.ValidateMediaLibrary(new Progress<Double>(), CancellationToken.None);
  207. }
  208. }
  209. public string Name
  210. {
  211. get { return "Emby"; }
  212. }
  213. public string DataPath
  214. {
  215. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  216. }
  217. private string DefaultRecordingPath
  218. {
  219. get
  220. {
  221. return Path.Combine(DataPath, "recordings");
  222. }
  223. }
  224. private string RecordingPath
  225. {
  226. get
  227. {
  228. var path = GetConfiguration().RecordingPath;
  229. return string.IsNullOrWhiteSpace(path)
  230. ? DefaultRecordingPath
  231. : path;
  232. }
  233. }
  234. public string HomePageUrl
  235. {
  236. get { return "http://emby.media"; }
  237. }
  238. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  239. {
  240. var status = new LiveTvServiceStatusInfo();
  241. var list = new List<LiveTvTunerInfo>();
  242. foreach (var hostInstance in _liveTvManager.TunerHosts)
  243. {
  244. try
  245. {
  246. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  247. list.AddRange(tuners);
  248. }
  249. catch (Exception ex)
  250. {
  251. _logger.ErrorException("Error getting tuners", ex);
  252. }
  253. }
  254. status.Tuners = list;
  255. status.Status = LiveTvServiceStatus.Ok;
  256. status.Version = _appHost.ApplicationVersion.ToString();
  257. status.IsVisible = false;
  258. return status;
  259. }
  260. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  261. {
  262. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  263. List<ChannelInfo> channels = null;
  264. foreach (var timer in seriesTimers)
  265. {
  266. List<ProgramInfo> epgData;
  267. if (timer.RecordAnyChannel)
  268. {
  269. if (channels == null)
  270. {
  271. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  272. }
  273. var channelIds = channels.Select(i => i.Id).ToList();
  274. epgData = GetEpgDataForChannels(channelIds);
  275. }
  276. else
  277. {
  278. epgData = GetEpgDataForChannel(timer.ChannelId);
  279. }
  280. await UpdateTimersForSeriesTimer(epgData, timer, false, true).ConfigureAwait(false);
  281. }
  282. }
  283. public async Task RefreshTimers(CancellationToken cancellationToken, IProgress<double> progress)
  284. {
  285. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  286. foreach (var timer in timers)
  287. {
  288. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  289. {
  290. OnTimerOutOfDate(timer);
  291. continue;
  292. }
  293. if (string.IsNullOrWhiteSpace(timer.ProgramId) || string.IsNullOrWhiteSpace(timer.ChannelId))
  294. {
  295. continue;
  296. }
  297. var epg = GetEpgDataForChannel(timer.ChannelId);
  298. var program = epg.FirstOrDefault(i => string.Equals(i.Id, timer.ProgramId, StringComparison.OrdinalIgnoreCase));
  299. if (program == null)
  300. {
  301. OnTimerOutOfDate(timer);
  302. continue;
  303. }
  304. RecordingHelper.CopyProgramInfoToTimerInfo(program, timer);
  305. _timerProvider.Update(timer);
  306. }
  307. }
  308. private void OnTimerOutOfDate(TimerInfo timer)
  309. {
  310. _timerProvider.Delete(timer);
  311. }
  312. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  313. {
  314. var list = new List<ChannelInfo>();
  315. foreach (var hostInstance in _liveTvManager.TunerHosts)
  316. {
  317. try
  318. {
  319. var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
  320. list.AddRange(channels);
  321. }
  322. catch (Exception ex)
  323. {
  324. _logger.ErrorException("Error getting channels", ex);
  325. }
  326. }
  327. foreach (var provider in GetListingProviders())
  328. {
  329. var enabledChannels = list
  330. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  331. .ToList();
  332. if (enabledChannels.Count > 0)
  333. {
  334. try
  335. {
  336. await AddMetadata(provider.Item1, provider.Item2, enabledChannels, enableCache, cancellationToken).ConfigureAwait(false);
  337. }
  338. catch (NotSupportedException)
  339. {
  340. }
  341. catch (Exception ex)
  342. {
  343. _logger.ErrorException("Error adding metadata", ex);
  344. }
  345. }
  346. }
  347. return list;
  348. }
  349. private async Task AddMetadata(IListingsProvider provider, ListingsProviderInfo info, List<ChannelInfo> tunerChannels, bool enableCache, CancellationToken cancellationToken)
  350. {
  351. var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
  352. foreach (var tunerChannel in tunerChannels)
  353. {
  354. var epgChannel = GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  355. if (epgChannel != null)
  356. {
  357. if (!string.IsNullOrWhiteSpace(epgChannel.Name))
  358. {
  359. tunerChannel.Name = epgChannel.Name;
  360. }
  361. if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
  362. {
  363. tunerChannel.ImageUrl = epgChannel.ImageUrl;
  364. tunerChannel.HasImage = true;
  365. }
  366. }
  367. }
  368. }
  369. private readonly ConcurrentDictionary<string, List<ChannelInfo>> _epgChannels =
  370. new ConcurrentDictionary<string, List<ChannelInfo>>(StringComparer.OrdinalIgnoreCase);
  371. private async Task<List<ChannelInfo>> GetEpgChannels(IListingsProvider provider, ListingsProviderInfo info, bool enableCache, CancellationToken cancellationToken)
  372. {
  373. List<ChannelInfo> result;
  374. if (!enableCache || !_epgChannels.TryGetValue(info.Id, out result))
  375. {
  376. result = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false);
  377. foreach (var channel in result)
  378. {
  379. _logger.Info("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
  380. }
  381. _epgChannels.AddOrUpdate(info.Id, result, (k, v) => result);
  382. }
  383. return result;
  384. }
  385. private async Task<ChannelInfo> GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken)
  386. {
  387. var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false);
  388. return GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  389. }
  390. private string GetMappedChannel(string channelId, List<NameValuePair> mappings)
  391. {
  392. foreach (NameValuePair mapping in mappings)
  393. {
  394. if (StringHelper.EqualsIgnoreCase(mapping.Name, channelId))
  395. {
  396. return mapping.Value;
  397. }
  398. }
  399. return channelId;
  400. }
  401. private ChannelInfo GetEpgChannelFromTunerChannel(ListingsProviderInfo info, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
  402. {
  403. return GetEpgChannelFromTunerChannel(info.ChannelMappings.ToList(), tunerChannel, epgChannels);
  404. }
  405. public ChannelInfo GetEpgChannelFromTunerChannel(List<NameValuePair> mappings, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
  406. {
  407. if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
  408. {
  409. var mappedTunerChannelId = GetMappedChannel(tunerChannel.Id, mappings);
  410. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  411. {
  412. mappedTunerChannelId = tunerChannel.Id;
  413. }
  414. var channel = epgChannels.FirstOrDefault(i => string.Equals(mappedTunerChannelId, i.Id, StringComparison.OrdinalIgnoreCase));
  415. if (channel != null)
  416. {
  417. return channel;
  418. }
  419. }
  420. if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
  421. {
  422. var tunerChannelId = tunerChannel.TunerChannelId;
  423. if (tunerChannelId.IndexOf(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase) != -1)
  424. {
  425. tunerChannelId = tunerChannelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  426. }
  427. var mappedTunerChannelId = GetMappedChannel(tunerChannelId, mappings);
  428. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  429. {
  430. mappedTunerChannelId = tunerChannelId;
  431. }
  432. var channel = epgChannels.FirstOrDefault(i => string.Equals(mappedTunerChannelId, i.Id, StringComparison.OrdinalIgnoreCase));
  433. if (channel != null)
  434. {
  435. return channel;
  436. }
  437. }
  438. if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
  439. {
  440. var tunerChannelNumber = GetMappedChannel(tunerChannel.Number, mappings);
  441. if (string.IsNullOrWhiteSpace(tunerChannelNumber))
  442. {
  443. tunerChannelNumber = tunerChannel.Number;
  444. }
  445. var channel = epgChannels.FirstOrDefault(i => string.Equals(tunerChannelNumber, i.Number, StringComparison.OrdinalIgnoreCase));
  446. if (channel != null)
  447. {
  448. return channel;
  449. }
  450. }
  451. if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
  452. {
  453. var normalizedName = NormalizeName(tunerChannel.Name);
  454. var channel = epgChannels.FirstOrDefault(i => string.Equals(normalizedName, NormalizeName(i.Name ?? string.Empty), StringComparison.OrdinalIgnoreCase));
  455. if (channel != null)
  456. {
  457. return channel;
  458. }
  459. }
  460. return null;
  461. }
  462. private string NormalizeName(string value)
  463. {
  464. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  465. }
  466. public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
  467. {
  468. var list = new List<ChannelInfo>();
  469. foreach (var hostInstance in _liveTvManager.TunerHosts)
  470. {
  471. try
  472. {
  473. var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
  474. list.AddRange(channels);
  475. }
  476. catch (Exception ex)
  477. {
  478. _logger.ErrorException("Error getting channels", ex);
  479. }
  480. }
  481. return list
  482. .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
  483. .ToList();
  484. }
  485. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  486. {
  487. return GetChannelsAsync(false, cancellationToken);
  488. }
  489. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  490. {
  491. var timers = _timerProvider
  492. .GetAll()
  493. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  494. .ToList();
  495. foreach (var timer in timers)
  496. {
  497. CancelTimerInternal(timer.Id, true);
  498. }
  499. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  500. if (remove != null)
  501. {
  502. _seriesTimerProvider.Delete(remove);
  503. }
  504. return Task.FromResult(true);
  505. }
  506. private void CancelTimerInternal(string timerId, bool isSeriesCancelled)
  507. {
  508. var timer = _timerProvider.GetTimer(timerId);
  509. if (timer != null)
  510. {
  511. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
  512. {
  513. _timerProvider.Delete(timer);
  514. }
  515. else
  516. {
  517. timer.Status = RecordingStatus.Cancelled;
  518. _timerProvider.AddOrUpdate(timer, false);
  519. }
  520. }
  521. ActiveRecordingInfo activeRecordingInfo;
  522. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  523. {
  524. activeRecordingInfo.CancellationTokenSource.Cancel();
  525. }
  526. }
  527. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  528. {
  529. CancelTimerInternal(timerId, false);
  530. return Task.FromResult(true);
  531. }
  532. public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  533. {
  534. return Task.FromResult(true);
  535. }
  536. public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  537. {
  538. throw new NotImplementedException();
  539. }
  540. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  541. {
  542. throw new NotImplementedException();
  543. }
  544. public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
  545. {
  546. var existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId) ?
  547. null :
  548. _timerProvider.GetTimerByProgramId(timer.ProgramId);
  549. if (existingTimer != null)
  550. {
  551. if (existingTimer.Status == RecordingStatus.Cancelled ||
  552. existingTimer.Status == RecordingStatus.Completed)
  553. {
  554. existingTimer.Status = RecordingStatus.New;
  555. existingTimer.IsManual = true;
  556. _timerProvider.Update(existingTimer);
  557. return Task.FromResult(existingTimer.Id);
  558. }
  559. else
  560. {
  561. throw new ArgumentException("A scheduled recording already exists for this program.");
  562. }
  563. }
  564. timer.Id = Guid.NewGuid().ToString("N");
  565. ProgramInfo programInfo = null;
  566. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  567. {
  568. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  569. }
  570. if (programInfo == null)
  571. {
  572. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  573. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  574. }
  575. if (programInfo != null)
  576. {
  577. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  578. }
  579. timer.IsManual = true;
  580. _timerProvider.Add(timer);
  581. return Task.FromResult(timer.Id);
  582. }
  583. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  584. {
  585. info.Id = Guid.NewGuid().ToString("N");
  586. List<ProgramInfo> epgData;
  587. if (info.RecordAnyChannel)
  588. {
  589. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  590. var channelIds = channels.Select(i => i.Id).ToList();
  591. epgData = GetEpgDataForChannels(channelIds);
  592. }
  593. else
  594. {
  595. epgData = GetEpgDataForChannel(info.ChannelId);
  596. }
  597. // populate info.seriesID
  598. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  599. if (program != null)
  600. {
  601. info.SeriesId = program.SeriesId;
  602. }
  603. else
  604. {
  605. throw new InvalidOperationException("SeriesId for program not found");
  606. }
  607. // If any timers have already been manually created, make sure they don't get cancelled
  608. var existingTimers = (await GetTimersAsync(CancellationToken.None).ConfigureAwait(false))
  609. .Where(i =>
  610. {
  611. if (string.Equals(i.ProgramId, info.ProgramId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.ProgramId))
  612. {
  613. return true;
  614. }
  615. if (string.Equals(i.SeriesId, info.SeriesId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.SeriesId))
  616. {
  617. return true;
  618. }
  619. return false;
  620. })
  621. .ToList();
  622. _seriesTimerProvider.Add(info);
  623. foreach (var timer in existingTimers)
  624. {
  625. timer.SeriesTimerId = info.Id;
  626. timer.IsManual = true;
  627. _timerProvider.AddOrUpdate(timer, false);
  628. }
  629. await UpdateTimersForSeriesTimer(epgData, info, true, false).ConfigureAwait(false);
  630. return info.Id;
  631. }
  632. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  633. {
  634. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  635. if (instance != null)
  636. {
  637. instance.ChannelId = info.ChannelId;
  638. instance.Days = info.Days;
  639. instance.EndDate = info.EndDate;
  640. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  641. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  642. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  643. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  644. instance.Priority = info.Priority;
  645. instance.RecordAnyChannel = info.RecordAnyChannel;
  646. instance.RecordAnyTime = info.RecordAnyTime;
  647. instance.RecordNewOnly = info.RecordNewOnly;
  648. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  649. instance.KeepUpTo = info.KeepUpTo;
  650. instance.KeepUntil = info.KeepUntil;
  651. instance.StartDate = info.StartDate;
  652. _seriesTimerProvider.Update(instance);
  653. List<ProgramInfo> epgData;
  654. if (instance.RecordAnyChannel)
  655. {
  656. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  657. var channelIds = channels.Select(i => i.Id).ToList();
  658. epgData = GetEpgDataForChannels(channelIds);
  659. }
  660. else
  661. {
  662. epgData = GetEpgDataForChannel(instance.ChannelId);
  663. }
  664. await UpdateTimersForSeriesTimer(epgData, instance, true, true).ConfigureAwait(false);
  665. }
  666. }
  667. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  668. {
  669. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  670. if (existingTimer == null)
  671. {
  672. throw new ResourceNotFoundException();
  673. }
  674. // Only update if not currently active
  675. ActiveRecordingInfo activeRecordingInfo;
  676. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo))
  677. {
  678. existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds;
  679. existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds;
  680. existingTimer.IsPostPaddingRequired = updatedTimer.IsPostPaddingRequired;
  681. existingTimer.IsPrePaddingRequired = updatedTimer.IsPrePaddingRequired;
  682. _timerProvider.Update(existingTimer);
  683. }
  684. return Task.FromResult(true);
  685. }
  686. private void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer)
  687. {
  688. // Update the program info but retain the status
  689. existingTimer.ChannelId = updatedTimer.ChannelId;
  690. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  691. existingTimer.EndDate = updatedTimer.EndDate;
  692. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  693. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  694. existingTimer.Genres = updatedTimer.Genres;
  695. existingTimer.HomePageUrl = updatedTimer.HomePageUrl;
  696. existingTimer.IsKids = updatedTimer.IsKids;
  697. existingTimer.IsNews = updatedTimer.IsNews;
  698. existingTimer.IsMovie = updatedTimer.IsMovie;
  699. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  700. existingTimer.IsRepeat = updatedTimer.IsRepeat;
  701. existingTimer.IsSports = updatedTimer.IsSports;
  702. existingTimer.Name = updatedTimer.Name;
  703. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  704. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  705. existingTimer.Overview = updatedTimer.Overview;
  706. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  707. existingTimer.ProgramId = updatedTimer.ProgramId;
  708. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  709. existingTimer.StartDate = updatedTimer.StartDate;
  710. existingTimer.ShowId = updatedTimer.ShowId;
  711. }
  712. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  713. {
  714. throw new NotImplementedException();
  715. }
  716. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  717. {
  718. throw new NotImplementedException();
  719. }
  720. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  721. {
  722. throw new NotImplementedException();
  723. }
  724. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  725. {
  726. return _activeRecordings.Values.ToList().Select(GetRecordingInfo).ToList();
  727. }
  728. public string GetActiveRecordingPath(string id)
  729. {
  730. ActiveRecordingInfo info;
  731. if (_activeRecordings.TryGetValue(id, out info))
  732. {
  733. return info.Path;
  734. }
  735. return null;
  736. }
  737. private RecordingInfo GetRecordingInfo(ActiveRecordingInfo info)
  738. {
  739. var timer = info.Timer;
  740. var program = info.Program;
  741. var result = new RecordingInfo
  742. {
  743. ChannelId = timer.ChannelId,
  744. CommunityRating = timer.CommunityRating,
  745. DateLastUpdated = DateTime.UtcNow,
  746. EndDate = timer.EndDate,
  747. EpisodeTitle = timer.EpisodeTitle,
  748. Genres = timer.Genres,
  749. Id = "recording" + timer.Id,
  750. IsKids = timer.IsKids,
  751. IsMovie = timer.IsMovie,
  752. IsNews = timer.IsNews,
  753. IsRepeat = timer.IsRepeat,
  754. IsSeries = timer.IsProgramSeries,
  755. IsSports = timer.IsSports,
  756. Name = timer.Name,
  757. OfficialRating = timer.OfficialRating,
  758. OriginalAirDate = timer.OriginalAirDate,
  759. Overview = timer.Overview,
  760. ProgramId = timer.ProgramId,
  761. SeriesTimerId = timer.SeriesTimerId,
  762. StartDate = timer.StartDate,
  763. Status = RecordingStatus.InProgress,
  764. TimerId = timer.Id
  765. };
  766. if (program != null)
  767. {
  768. result.Audio = program.Audio;
  769. result.ImagePath = program.ImagePath;
  770. result.ImageUrl = program.ImageUrl;
  771. result.IsHD = program.IsHD;
  772. result.IsLive = program.IsLive;
  773. result.IsPremiere = program.IsPremiere;
  774. result.ShowId = program.ShowId;
  775. }
  776. return result;
  777. }
  778. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  779. {
  780. var excludeStatues = new List<RecordingStatus>
  781. {
  782. RecordingStatus.Completed
  783. };
  784. var timers = _timerProvider.GetAll()
  785. .Where(i => !excludeStatues.Contains(i.Status));
  786. return Task.FromResult(timers);
  787. }
  788. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  789. {
  790. var config = GetConfiguration();
  791. var defaults = new SeriesTimerInfo()
  792. {
  793. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  794. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  795. RecordAnyChannel = false,
  796. RecordAnyTime = true,
  797. RecordNewOnly = true,
  798. Days = new List<DayOfWeek>
  799. {
  800. DayOfWeek.Sunday,
  801. DayOfWeek.Monday,
  802. DayOfWeek.Tuesday,
  803. DayOfWeek.Wednesday,
  804. DayOfWeek.Thursday,
  805. DayOfWeek.Friday,
  806. DayOfWeek.Saturday
  807. }
  808. };
  809. if (program != null)
  810. {
  811. defaults.SeriesId = program.SeriesId;
  812. defaults.ProgramId = program.Id;
  813. defaults.RecordNewOnly = !program.IsRepeat;
  814. }
  815. defaults.SkipEpisodesInLibrary = defaults.RecordNewOnly;
  816. defaults.KeepUntil = KeepUntil.UntilDeleted;
  817. return Task.FromResult(defaults);
  818. }
  819. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  820. {
  821. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  822. }
  823. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  824. {
  825. try
  826. {
  827. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  828. }
  829. catch (OperationCanceledException)
  830. {
  831. throw;
  832. }
  833. catch (Exception ex)
  834. {
  835. _logger.ErrorException("Error getting programs", ex);
  836. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  837. }
  838. }
  839. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  840. {
  841. if (info.EnableAllTuners)
  842. {
  843. return true;
  844. }
  845. if (string.IsNullOrWhiteSpace(tunerHostId))
  846. {
  847. throw new ArgumentNullException("tunerHostId");
  848. }
  849. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  850. }
  851. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  852. {
  853. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  854. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  855. foreach (var provider in GetListingProviders())
  856. {
  857. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  858. {
  859. _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  860. continue;
  861. }
  862. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  863. var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
  864. List<ProgramInfo> programs;
  865. if (epgChannel == null)
  866. {
  867. _logger.Debug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  868. programs = new List<ProgramInfo>();
  869. }
  870. else
  871. {
  872. programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
  873. .ConfigureAwait(false)).ToList();
  874. }
  875. // Replace the value that came from the provider with a normalized value
  876. foreach (var program in programs)
  877. {
  878. program.ChannelId = channelId;
  879. if (provider.Item2.EnableNewProgramIds)
  880. {
  881. program.Id += "_" + channelId;
  882. }
  883. }
  884. if (programs.Count > 0)
  885. {
  886. SaveEpgDataForChannel(channelId, programs);
  887. return programs;
  888. }
  889. }
  890. return new List<ProgramInfo>();
  891. }
  892. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  893. {
  894. return GetConfiguration().ListingProviders
  895. .Select(i =>
  896. {
  897. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  898. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  899. })
  900. .Where(i => i != null)
  901. .ToList();
  902. }
  903. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  904. {
  905. throw new NotImplementedException();
  906. }
  907. private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
  908. private readonly List<LiveStream> _liveStreams = new List<LiveStream>();
  909. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  910. {
  911. var result = await GetChannelStreamWithDirectStreamProvider(channelId, streamId, cancellationToken).ConfigureAwait(false);
  912. return result.Item1;
  913. }
  914. public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, CancellationToken cancellationToken)
  915. {
  916. var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
  917. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(result.Item2, result.Item1 as IDirectStreamProvider);
  918. }
  919. private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, bool enableStreamSharing)
  920. {
  921. var json = _jsonSerializer.SerializeToString(mediaSource);
  922. mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  923. mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
  924. //if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
  925. //{
  926. // var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks;
  927. // ticks = Math.Max(0, ticks);
  928. // mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture);
  929. //}
  930. return mediaSource;
  931. }
  932. public async Task<LiveStream> GetLiveStream(string uniqueId)
  933. {
  934. await _liveStreamsSemaphore.WaitAsync().ConfigureAwait(false);
  935. try
  936. {
  937. return _liveStreams
  938. .FirstOrDefault(i => string.Equals(i.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase));
  939. }
  940. finally
  941. {
  942. _liveStreamsSemaphore.Release();
  943. }
  944. }
  945. private async Task<Tuple<LiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  946. {
  947. _logger.Info("Streaming Channel " + channelId);
  948. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  949. try
  950. {
  951. var result = _liveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  952. if (result != null && result.EnableStreamSharing)
  953. {
  954. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  955. result.SharedStreamIds.Add(openedMediaSource.Id);
  956. _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  957. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, result.TunerHost);
  958. }
  959. foreach (var hostInstance in _liveTvManager.TunerHosts)
  960. {
  961. try
  962. {
  963. result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  964. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  965. result.SharedStreamIds.Add(openedMediaSource.Id);
  966. _liveStreams.Add(result);
  967. result.TunerHost = hostInstance;
  968. result.OriginalStreamId = streamId;
  969. _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
  970. streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  971. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, hostInstance);
  972. }
  973. catch (FileNotFoundException)
  974. {
  975. }
  976. catch (OperationCanceledException)
  977. {
  978. }
  979. }
  980. }
  981. finally
  982. {
  983. _liveStreamsSemaphore.Release();
  984. }
  985. throw new Exception("Tuner not found.");
  986. }
  987. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  988. {
  989. if (string.IsNullOrWhiteSpace(channelId))
  990. {
  991. throw new ArgumentNullException("channelId");
  992. }
  993. foreach (var hostInstance in _liveTvManager.TunerHosts)
  994. {
  995. try
  996. {
  997. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  998. if (sources.Count > 0)
  999. {
  1000. return sources;
  1001. }
  1002. }
  1003. catch (NotImplementedException)
  1004. {
  1005. }
  1006. }
  1007. throw new NotImplementedException();
  1008. }
  1009. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  1010. {
  1011. ActiveRecordingInfo info;
  1012. recordingId = recordingId.Replace("recording", string.Empty);
  1013. if (_activeRecordings.TryGetValue(recordingId, out info))
  1014. {
  1015. var stream = new MediaSourceInfo
  1016. {
  1017. Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + recordingId + "/stream",
  1018. Id = recordingId,
  1019. SupportsDirectPlay = false,
  1020. SupportsDirectStream = true,
  1021. SupportsTranscoding = true,
  1022. IsInfiniteStream = true,
  1023. RequiresOpening = false,
  1024. RequiresClosing = false,
  1025. Protocol = MediaBrowser.Model.MediaInfo.MediaProtocol.Http,
  1026. BufferMs = 0
  1027. };
  1028. var isAudio = false;
  1029. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  1030. return new List<MediaSourceInfo>
  1031. {
  1032. stream
  1033. };
  1034. }
  1035. throw new FileNotFoundException();
  1036. }
  1037. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1038. {
  1039. // Ignore the consumer id
  1040. //id = id.Substring(id.IndexOf('_') + 1);
  1041. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1042. try
  1043. {
  1044. var stream = _liveStreams.FirstOrDefault(i => i.SharedStreamIds.Contains(id));
  1045. if (stream != null)
  1046. {
  1047. stream.SharedStreamIds.Remove(id);
  1048. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  1049. if (stream.ConsumerCount <= 0)
  1050. {
  1051. _liveStreams.Remove(stream);
  1052. _logger.Info("Closing live stream {0}", id);
  1053. await stream.Close().ConfigureAwait(false);
  1054. _logger.Info("Live stream {0} closed successfully", id);
  1055. }
  1056. }
  1057. else
  1058. {
  1059. _logger.Warn("Live stream not found: {0}, unable to close", id);
  1060. }
  1061. }
  1062. catch (OperationCanceledException)
  1063. {
  1064. }
  1065. catch (Exception ex)
  1066. {
  1067. _logger.ErrorException("Error closing live stream", ex);
  1068. }
  1069. finally
  1070. {
  1071. _liveStreamsSemaphore.Release();
  1072. }
  1073. }
  1074. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  1075. {
  1076. return Task.FromResult(0);
  1077. }
  1078. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1079. {
  1080. return Task.FromResult(0);
  1081. }
  1082. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  1083. {
  1084. var timer = e.Argument;
  1085. _logger.Info("Recording timer fired.");
  1086. try
  1087. {
  1088. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  1089. if (recordingEndDate <= DateTime.UtcNow)
  1090. {
  1091. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  1092. OnTimerOutOfDate(timer);
  1093. return;
  1094. }
  1095. var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false);
  1096. if (!registration.IsValid)
  1097. {
  1098. _logger.Warn("Emby Premiere required to use Emby DVR.");
  1099. OnTimerOutOfDate(timer);
  1100. return;
  1101. }
  1102. var activeRecordingInfo = new ActiveRecordingInfo
  1103. {
  1104. CancellationTokenSource = new CancellationTokenSource(),
  1105. Timer = timer
  1106. };
  1107. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  1108. {
  1109. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  1110. }
  1111. else
  1112. {
  1113. _logger.Info("Skipping RecordStream because it's already in progress.");
  1114. }
  1115. }
  1116. catch (OperationCanceledException)
  1117. {
  1118. }
  1119. catch (Exception ex)
  1120. {
  1121. _logger.ErrorException("Error recording stream", ex);
  1122. }
  1123. }
  1124. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  1125. {
  1126. var recordPath = RecordingPath;
  1127. var config = GetConfiguration();
  1128. seriesPath = null;
  1129. if (timer.IsProgramSeries)
  1130. {
  1131. var customRecordingPath = config.SeriesRecordingPath;
  1132. var allowSubfolder = true;
  1133. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1134. {
  1135. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1136. recordPath = customRecordingPath;
  1137. }
  1138. if (allowSubfolder && config.EnableRecordingSubfolders)
  1139. {
  1140. recordPath = Path.Combine(recordPath, "Series");
  1141. }
  1142. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1143. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  1144. recordPath = Path.Combine(recordPath, folderName);
  1145. seriesPath = recordPath;
  1146. if (timer.SeasonNumber.HasValue)
  1147. {
  1148. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  1149. recordPath = Path.Combine(recordPath, folderName);
  1150. }
  1151. }
  1152. else if (timer.IsMovie)
  1153. {
  1154. var customRecordingPath = config.MovieRecordingPath;
  1155. var allowSubfolder = true;
  1156. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1157. {
  1158. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1159. recordPath = customRecordingPath;
  1160. }
  1161. if (allowSubfolder && config.EnableRecordingSubfolders)
  1162. {
  1163. recordPath = Path.Combine(recordPath, "Movies");
  1164. }
  1165. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1166. if (timer.ProductionYear.HasValue)
  1167. {
  1168. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1169. }
  1170. recordPath = Path.Combine(recordPath, folderName);
  1171. }
  1172. else if (timer.IsKids)
  1173. {
  1174. if (config.EnableRecordingSubfolders)
  1175. {
  1176. recordPath = Path.Combine(recordPath, "Kids");
  1177. }
  1178. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1179. if (timer.ProductionYear.HasValue)
  1180. {
  1181. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1182. }
  1183. recordPath = Path.Combine(recordPath, folderName);
  1184. }
  1185. else if (timer.IsSports)
  1186. {
  1187. if (config.EnableRecordingSubfolders)
  1188. {
  1189. recordPath = Path.Combine(recordPath, "Sports");
  1190. }
  1191. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1192. }
  1193. else
  1194. {
  1195. if (config.EnableRecordingSubfolders)
  1196. {
  1197. recordPath = Path.Combine(recordPath, "Other");
  1198. }
  1199. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1200. }
  1201. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1202. return Path.Combine(recordPath, recordingFileName);
  1203. }
  1204. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  1205. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  1206. {
  1207. if (timer == null)
  1208. {
  1209. throw new ArgumentNullException("timer");
  1210. }
  1211. ProgramInfo programInfo = null;
  1212. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1213. {
  1214. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  1215. }
  1216. if (programInfo == null)
  1217. {
  1218. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1219. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1220. }
  1221. if (programInfo != null)
  1222. {
  1223. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  1224. activeRecordingInfo.Program = programInfo;
  1225. }
  1226. string seriesPath = null;
  1227. var recordPath = GetRecordingPath(timer, out seriesPath);
  1228. var recordingStatus = RecordingStatus.New;
  1229. string liveStreamId = null;
  1230. OnRecordingStatusChanged();
  1231. try
  1232. {
  1233. var recorder = await GetRecorder().ConfigureAwait(false);
  1234. var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  1235. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  1236. .ConfigureAwait(false);
  1237. var mediaStreamInfo = liveStreamInfo.Item2;
  1238. liveStreamId = mediaStreamInfo.Id;
  1239. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  1240. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  1241. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1242. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1243. _libraryManager.RegisterIgnoredPath(recordPath);
  1244. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1245. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  1246. activeRecordingInfo.Path = recordPath;
  1247. var duration = recordingEndDate - DateTime.UtcNow;
  1248. _logger.Info("Beginning recording. Will record for {0} minutes.",
  1249. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1250. _logger.Info("Writing file to path: " + recordPath);
  1251. _logger.Info("Opening recording stream from tuner provider");
  1252. Action onStarted = () =>
  1253. {
  1254. timer.Status = RecordingStatus.InProgress;
  1255. _timerProvider.AddOrUpdate(timer, false);
  1256. SaveRecordingMetadata(timer, recordPath, seriesPath);
  1257. EnforceKeepUpTo(timer);
  1258. };
  1259. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  1260. .ConfigureAwait(false);
  1261. recordingStatus = RecordingStatus.Completed;
  1262. _logger.Info("Recording completed: {0}", recordPath);
  1263. }
  1264. catch (OperationCanceledException)
  1265. {
  1266. _logger.Info("Recording stopped: {0}", recordPath);
  1267. recordingStatus = RecordingStatus.Completed;
  1268. }
  1269. catch (Exception ex)
  1270. {
  1271. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  1272. recordingStatus = RecordingStatus.Error;
  1273. }
  1274. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1275. {
  1276. try
  1277. {
  1278. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1279. }
  1280. catch (Exception ex)
  1281. {
  1282. _logger.ErrorException("Error closing live stream", ex);
  1283. }
  1284. }
  1285. _libraryManager.UnRegisterIgnoredPath(recordPath);
  1286. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  1287. ActiveRecordingInfo removed;
  1288. _activeRecordings.TryRemove(timer.Id, out removed);
  1289. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1290. {
  1291. const int retryIntervalSeconds = 60;
  1292. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1293. timer.Status = RecordingStatus.New;
  1294. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1295. timer.RetryCount++;
  1296. _timerProvider.AddOrUpdate(timer);
  1297. }
  1298. else if (_fileSystem.FileExists(recordPath))
  1299. {
  1300. timer.RecordingPath = recordPath;
  1301. timer.Status = RecordingStatus.Completed;
  1302. _timerProvider.AddOrUpdate(timer, false);
  1303. OnSuccessfulRecording(timer, recordPath);
  1304. }
  1305. else
  1306. {
  1307. _timerProvider.Delete(timer);
  1308. }
  1309. OnRecordingStatusChanged();
  1310. }
  1311. private void OnRecordingStatusChanged()
  1312. {
  1313. EventHelper.FireEventIfNotNull(RecordingStatusChanged, this, new RecordingStatusChangedEventArgs
  1314. {
  1315. }, _logger);
  1316. }
  1317. private async void EnforceKeepUpTo(TimerInfo timer)
  1318. {
  1319. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1320. {
  1321. return;
  1322. }
  1323. var seriesTimerId = timer.SeriesTimerId;
  1324. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1325. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1326. {
  1327. return;
  1328. }
  1329. if (_disposed)
  1330. {
  1331. return;
  1332. }
  1333. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1334. try
  1335. {
  1336. if (_disposed)
  1337. {
  1338. return;
  1339. }
  1340. var timersToDelete = _timerProvider.GetAll()
  1341. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1342. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1343. .OrderByDescending(i => i.EndDate)
  1344. .Where(i => _fileSystem.FileExists(i.RecordingPath))
  1345. .Skip(seriesTimer.KeepUpTo - 1)
  1346. .ToList();
  1347. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1348. }
  1349. finally
  1350. {
  1351. _recordingDeleteSemaphore.Release();
  1352. }
  1353. }
  1354. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1355. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1356. {
  1357. foreach (var timer in timers)
  1358. {
  1359. if (_disposed)
  1360. {
  1361. return;
  1362. }
  1363. try
  1364. {
  1365. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1366. }
  1367. catch (Exception ex)
  1368. {
  1369. _logger.ErrorException("Error deleting recording", ex);
  1370. }
  1371. }
  1372. }
  1373. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1374. {
  1375. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1376. if (libraryItem != null)
  1377. {
  1378. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1379. {
  1380. DeleteFileLocation = true
  1381. });
  1382. }
  1383. else
  1384. {
  1385. try
  1386. {
  1387. _fileSystem.DeleteFile(timer.RecordingPath);
  1388. }
  1389. catch (IOException)
  1390. {
  1391. }
  1392. }
  1393. _timerProvider.Delete(timer);
  1394. }
  1395. private string EnsureFileUnique(string path, string timerId)
  1396. {
  1397. var originalPath = path;
  1398. var index = 1;
  1399. while (FileExists(path, timerId))
  1400. {
  1401. var parent = Path.GetDirectoryName(originalPath);
  1402. var name = Path.GetFileNameWithoutExtension(originalPath);
  1403. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1404. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1405. index++;
  1406. }
  1407. return path;
  1408. }
  1409. private bool FileExists(string path, string timerId)
  1410. {
  1411. if (_fileSystem.FileExists(path))
  1412. {
  1413. return true;
  1414. }
  1415. var hasRecordingAtPath = _activeRecordings
  1416. .Values
  1417. .ToList()
  1418. .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1419. if (hasRecordingAtPath)
  1420. {
  1421. return true;
  1422. }
  1423. return false;
  1424. }
  1425. private async Task<IRecorder> GetRecorder()
  1426. {
  1427. var config = GetConfiguration();
  1428. if (config.EnableRecordingEncoding)
  1429. {
  1430. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1431. if (regInfo.IsValid)
  1432. {
  1433. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient, _processFactory);
  1434. }
  1435. }
  1436. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1437. }
  1438. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1439. {
  1440. //if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1441. //{
  1442. // try
  1443. // {
  1444. // // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1445. // // ideally this shouldn't be hard-coded
  1446. // await Task.Delay(30000).ConfigureAwait(false);
  1447. // var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1448. // var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1449. // if (result.Status == FileSortingStatus.Success)
  1450. // {
  1451. // return;
  1452. // }
  1453. // }
  1454. // catch (Exception ex)
  1455. // {
  1456. // _logger.ErrorException("Error processing new recording", ex);
  1457. // }
  1458. //}
  1459. PostProcessRecording(timer, path);
  1460. }
  1461. private void PostProcessRecording(TimerInfo timer, string path)
  1462. {
  1463. var options = GetConfiguration();
  1464. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1465. {
  1466. return;
  1467. }
  1468. try
  1469. {
  1470. var process = _processFactory.Create(new ProcessOptions
  1471. {
  1472. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1473. CreateNoWindow = true,
  1474. EnableRaisingEvents = true,
  1475. ErrorDialog = false,
  1476. FileName = options.RecordingPostProcessor,
  1477. IsHidden = true,
  1478. UseShellExecute = false
  1479. });
  1480. _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1481. process.Exited += Process_Exited;
  1482. process.Start();
  1483. }
  1484. catch (Exception ex)
  1485. {
  1486. _logger.ErrorException("Error running recording post processor", ex);
  1487. }
  1488. }
  1489. private string GetPostProcessArguments(string path, string arguments)
  1490. {
  1491. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1492. }
  1493. private void Process_Exited(object sender, EventArgs e)
  1494. {
  1495. var process = (IProcess)sender;
  1496. try
  1497. {
  1498. _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
  1499. }
  1500. catch
  1501. {
  1502. }
  1503. process.Dispose();
  1504. }
  1505. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1506. {
  1507. if (!image.IsLocalFile)
  1508. {
  1509. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1510. }
  1511. string imageSaveFilenameWithoutExtension = null;
  1512. switch (image.Type)
  1513. {
  1514. case ImageType.Primary:
  1515. if (program.IsSeries)
  1516. {
  1517. imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
  1518. }
  1519. else
  1520. {
  1521. imageSaveFilenameWithoutExtension = "poster";
  1522. }
  1523. break;
  1524. case ImageType.Logo:
  1525. imageSaveFilenameWithoutExtension = "logo";
  1526. break;
  1527. case ImageType.Thumb:
  1528. imageSaveFilenameWithoutExtension = "landscape";
  1529. break;
  1530. case ImageType.Backdrop:
  1531. imageSaveFilenameWithoutExtension = "fanart";
  1532. break;
  1533. default:
  1534. break;
  1535. }
  1536. if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
  1537. {
  1538. return;
  1539. }
  1540. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1541. // preserve original image extension
  1542. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1543. _fileSystem.CopyFile(image.Path, imageSavePath, true);
  1544. }
  1545. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1546. {
  1547. var image = program.GetImageInfo(ImageType.Primary, 0);
  1548. if (image != null && program.IsMovie)
  1549. {
  1550. try
  1551. {
  1552. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1553. }
  1554. catch (Exception ex)
  1555. {
  1556. _logger.ErrorException("Error saving recording image", ex);
  1557. }
  1558. }
  1559. if (!program.IsSeries)
  1560. {
  1561. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1562. if (image != null)
  1563. {
  1564. try
  1565. {
  1566. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1567. }
  1568. catch (Exception ex)
  1569. {
  1570. _logger.ErrorException("Error saving recording image", ex);
  1571. }
  1572. }
  1573. image = program.GetImageInfo(ImageType.Thumb, 0);
  1574. if (image != null)
  1575. {
  1576. try
  1577. {
  1578. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1579. }
  1580. catch (Exception ex)
  1581. {
  1582. _logger.ErrorException("Error saving recording image", ex);
  1583. }
  1584. }
  1585. image = program.GetImageInfo(ImageType.Logo, 0);
  1586. if (image != null)
  1587. {
  1588. try
  1589. {
  1590. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1591. }
  1592. catch (Exception ex)
  1593. {
  1594. _logger.ErrorException("Error saving recording image", ex);
  1595. }
  1596. }
  1597. }
  1598. }
  1599. private async void SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1600. {
  1601. try
  1602. {
  1603. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1604. {
  1605. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1606. Limit = 1,
  1607. ExternalId = timer.ProgramId
  1608. }).FirstOrDefault() as LiveTvProgram;
  1609. // dummy this up
  1610. if (program == null)
  1611. {
  1612. program = new LiveTvProgram
  1613. {
  1614. Name = timer.Name,
  1615. HomePageUrl = timer.HomePageUrl,
  1616. Overview = timer.Overview,
  1617. Genres = timer.Genres,
  1618. CommunityRating = timer.CommunityRating,
  1619. OfficialRating = timer.OfficialRating,
  1620. ProductionYear = timer.ProductionYear,
  1621. PremiereDate = timer.OriginalAirDate,
  1622. IndexNumber = timer.EpisodeNumber,
  1623. ParentIndexNumber = timer.SeasonNumber
  1624. };
  1625. }
  1626. if (timer.IsSports)
  1627. {
  1628. AddGenre(program.Genres, "Sports");
  1629. }
  1630. if (timer.IsKids)
  1631. {
  1632. AddGenre(program.Genres, "Kids");
  1633. AddGenre(program.Genres, "Children");
  1634. }
  1635. if (timer.IsNews)
  1636. {
  1637. AddGenre(program.Genres, "News");
  1638. }
  1639. if (timer.IsProgramSeries)
  1640. {
  1641. SaveSeriesNfo(timer, seriesPath);
  1642. SaveVideoNfo(timer, recordingPath, program, false);
  1643. }
  1644. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1645. {
  1646. SaveVideoNfo(timer, recordingPath, program, true);
  1647. }
  1648. else
  1649. {
  1650. SaveVideoNfo(timer, recordingPath, program, false);
  1651. }
  1652. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1653. }
  1654. catch (Exception ex)
  1655. {
  1656. _logger.ErrorException("Error saving nfo", ex);
  1657. }
  1658. }
  1659. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1660. {
  1661. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1662. if (_fileSystem.FileExists(nfoPath))
  1663. {
  1664. return;
  1665. }
  1666. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1667. {
  1668. var settings = new XmlWriterSettings
  1669. {
  1670. Indent = true,
  1671. Encoding = Encoding.UTF8,
  1672. CloseOutput = false
  1673. };
  1674. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1675. {
  1676. writer.WriteStartDocument(true);
  1677. writer.WriteStartElement("tvshow");
  1678. if (!string.IsNullOrWhiteSpace(timer.Name))
  1679. {
  1680. writer.WriteElementString("title", timer.Name);
  1681. }
  1682. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1683. {
  1684. writer.WriteElementString("mpaa", timer.OfficialRating);
  1685. }
  1686. foreach (var genre in timer.Genres)
  1687. {
  1688. writer.WriteElementString("genre", genre);
  1689. }
  1690. writer.WriteEndElement();
  1691. writer.WriteEndDocument();
  1692. }
  1693. }
  1694. }
  1695. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1696. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1697. {
  1698. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1699. if (_fileSystem.FileExists(nfoPath))
  1700. {
  1701. return;
  1702. }
  1703. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1704. {
  1705. var settings = new XmlWriterSettings
  1706. {
  1707. Indent = true,
  1708. Encoding = Encoding.UTF8,
  1709. CloseOutput = false
  1710. };
  1711. var options = _config.GetNfoConfiguration();
  1712. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1713. {
  1714. writer.WriteStartDocument(true);
  1715. if (timer.IsProgramSeries)
  1716. {
  1717. writer.WriteStartElement("episodedetails");
  1718. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1719. {
  1720. writer.WriteElementString("title", timer.EpisodeTitle);
  1721. }
  1722. if (item.PremiereDate.HasValue)
  1723. {
  1724. var formatString = options.ReleaseDateFormat;
  1725. writer.WriteElementString("aired", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1726. }
  1727. if (item.IndexNumber.HasValue)
  1728. {
  1729. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1730. }
  1731. if (item.ParentIndexNumber.HasValue)
  1732. {
  1733. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1734. }
  1735. }
  1736. else
  1737. {
  1738. writer.WriteStartElement("movie");
  1739. if (!string.IsNullOrWhiteSpace(item.Name))
  1740. {
  1741. writer.WriteElementString("title", item.Name);
  1742. }
  1743. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1744. {
  1745. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1746. }
  1747. if (item.PremiereDate.HasValue)
  1748. {
  1749. var formatString = options.ReleaseDateFormat;
  1750. writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1751. writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1752. }
  1753. }
  1754. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1755. if (item.ProductionYear.HasValue)
  1756. {
  1757. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1758. }
  1759. if (!string.IsNullOrEmpty(item.OfficialRating))
  1760. {
  1761. writer.WriteElementString("mpaa", item.OfficialRating);
  1762. }
  1763. if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
  1764. {
  1765. writer.WriteElementString("mpaadescription", item.OfficialRatingDescription);
  1766. }
  1767. var overview = (item.Overview ?? string.Empty)
  1768. .StripHtml()
  1769. .Replace("&quot;", "'");
  1770. writer.WriteElementString("plot", overview);
  1771. if (lockData)
  1772. {
  1773. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1774. }
  1775. if (item.CommunityRating.HasValue)
  1776. {
  1777. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1778. }
  1779. foreach (var genre in item.Genres)
  1780. {
  1781. writer.WriteElementString("genre", genre);
  1782. }
  1783. if (!string.IsNullOrWhiteSpace(item.HomePageUrl))
  1784. {
  1785. writer.WriteElementString("website", item.HomePageUrl);
  1786. }
  1787. var people = item.Id == Guid.Empty ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1788. var directors = people
  1789. .Where(i => IsPersonType(i, PersonType.Director))
  1790. .Select(i => i.Name)
  1791. .ToList();
  1792. foreach (var person in directors)
  1793. {
  1794. writer.WriteElementString("director", person);
  1795. }
  1796. var writers = people
  1797. .Where(i => IsPersonType(i, PersonType.Writer))
  1798. .Select(i => i.Name)
  1799. .Distinct(StringComparer.OrdinalIgnoreCase)
  1800. .ToList();
  1801. foreach (var person in writers)
  1802. {
  1803. writer.WriteElementString("writer", person);
  1804. }
  1805. foreach (var person in writers)
  1806. {
  1807. writer.WriteElementString("credits", person);
  1808. }
  1809. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  1810. if (!string.IsNullOrEmpty(tmdbCollection))
  1811. {
  1812. writer.WriteElementString("collectionnumber", tmdbCollection);
  1813. }
  1814. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  1815. if (!string.IsNullOrEmpty(imdb))
  1816. {
  1817. if (item is Series)
  1818. {
  1819. writer.WriteElementString("imdb_id", imdb);
  1820. }
  1821. else
  1822. {
  1823. writer.WriteElementString("imdbid", imdb);
  1824. }
  1825. }
  1826. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  1827. if (!string.IsNullOrEmpty(tvdb))
  1828. {
  1829. writer.WriteElementString("tvdbid", tvdb);
  1830. }
  1831. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  1832. if (!string.IsNullOrEmpty(tmdb))
  1833. {
  1834. writer.WriteElementString("tmdbid", tmdb);
  1835. }
  1836. if (item.CriticRating.HasValue)
  1837. {
  1838. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1839. }
  1840. if (!string.IsNullOrEmpty(item.CriticRatingSummary))
  1841. {
  1842. writer.WriteElementString("criticratingsummary", item.CriticRatingSummary);
  1843. }
  1844. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1845. {
  1846. writer.WriteElementString("tagline", item.Tagline);
  1847. }
  1848. foreach (var studio in item.Studios)
  1849. {
  1850. writer.WriteElementString("studio", studio);
  1851. }
  1852. if (item.VoteCount.HasValue)
  1853. {
  1854. writer.WriteElementString("votes", item.VoteCount.Value.ToString(CultureInfo.InvariantCulture));
  1855. }
  1856. writer.WriteEndElement();
  1857. writer.WriteEndDocument();
  1858. }
  1859. }
  1860. }
  1861. private static bool IsPersonType(PersonInfo person, string type)
  1862. {
  1863. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1864. }
  1865. private void AddGenre(List<string> genres, string genre)
  1866. {
  1867. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1868. {
  1869. genres.Add(genre);
  1870. }
  1871. }
  1872. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1873. {
  1874. var epgData = GetEpgDataForChannel(channelId);
  1875. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1876. }
  1877. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1878. {
  1879. var epgData = GetEpgDataForChannel(channelId);
  1880. var startDateTicks = startDateUtc.Ticks;
  1881. // Find the first program that starts within 3 minutes
  1882. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1883. }
  1884. private LiveTvOptions GetConfiguration()
  1885. {
  1886. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1887. }
  1888. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1889. {
  1890. if (timer.IsManual)
  1891. {
  1892. return false;
  1893. }
  1894. if (!seriesTimer.RecordAnyTime)
  1895. {
  1896. if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(5).Ticks)
  1897. {
  1898. return true;
  1899. }
  1900. }
  1901. //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
  1902. //{
  1903. // return true;
  1904. //}
  1905. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1906. {
  1907. return true;
  1908. }
  1909. if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1910. {
  1911. return true;
  1912. }
  1913. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1914. }
  1915. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1916. {
  1917. foreach (var timer in timers.Skip(1))
  1918. {
  1919. // TODO: Get smarter, prefer HD, etc
  1920. timer.Status = RecordingStatus.Cancelled;
  1921. _timerProvider.Update(timer);
  1922. }
  1923. }
  1924. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1925. {
  1926. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1927. foreach (var group in groups)
  1928. {
  1929. if (string.IsNullOrWhiteSpace(group.Key))
  1930. {
  1931. continue;
  1932. }
  1933. var groupTimers = group.ToList();
  1934. if (groupTimers.Count < 2)
  1935. {
  1936. continue;
  1937. }
  1938. HandleDuplicateShowIds(groupTimers);
  1939. }
  1940. }
  1941. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1942. {
  1943. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1944. .ToList();
  1945. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1946. var enabledTimersForSeries = new List<TimerInfo>();
  1947. if (registration.IsValid)
  1948. {
  1949. foreach (var timer in allTimers)
  1950. {
  1951. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1952. if (existingTimer == null)
  1953. {
  1954. existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId)
  1955. ? null
  1956. : _timerProvider.GetTimerByProgramId(timer.ProgramId);
  1957. }
  1958. if (existingTimer == null)
  1959. {
  1960. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1961. {
  1962. timer.Status = RecordingStatus.Cancelled;
  1963. }
  1964. else
  1965. {
  1966. enabledTimersForSeries.Add(timer);
  1967. }
  1968. _timerProvider.Add(timer);
  1969. }
  1970. else
  1971. {
  1972. // Only update if not currently active - test both new timer and existing in case Id's are different
  1973. // Id's could be different if the timer was created manually prior to series timer creation
  1974. ActiveRecordingInfo activeRecordingInfo;
  1975. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo))
  1976. {
  1977. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1978. // Needed by ShouldCancelTimerForSeriesTimer
  1979. timer.IsManual = existingTimer.IsManual;
  1980. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1981. {
  1982. existingTimer.Status = RecordingStatus.Cancelled;
  1983. }
  1984. if (existingTimer.Status != RecordingStatus.Cancelled)
  1985. {
  1986. enabledTimersForSeries.Add(existingTimer);
  1987. }
  1988. if (updateTimerSettings)
  1989. {
  1990. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1991. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1992. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1993. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1994. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1995. existingTimer.Priority = seriesTimer.Priority;
  1996. }
  1997. existingTimer.SeriesTimerId = seriesTimer.Id;
  1998. _timerProvider.Update(existingTimer);
  1999. }
  2000. }
  2001. }
  2002. }
  2003. SearchForDuplicateShowIds(enabledTimersForSeries);
  2004. if (deleteInvalidTimers)
  2005. {
  2006. var allTimerIds = allTimers
  2007. .Select(i => i.Id)
  2008. .ToList();
  2009. var deleteStatuses = new List<RecordingStatus>
  2010. {
  2011. RecordingStatus.New
  2012. };
  2013. var deletes = _timerProvider.GetAll()
  2014. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  2015. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  2016. .Where(i => deleteStatuses.Contains(i.Status))
  2017. .ToList();
  2018. foreach (var timer in deletes)
  2019. {
  2020. CancelTimerInternal(timer.Id, false);
  2021. }
  2022. }
  2023. }
  2024. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  2025. {
  2026. if (seriesTimer == null)
  2027. {
  2028. throw new ArgumentNullException("seriesTimer");
  2029. }
  2030. if (allPrograms == null)
  2031. {
  2032. throw new ArgumentNullException("allPrograms");
  2033. }
  2034. // Exclude programs that have already ended
  2035. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  2036. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  2037. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  2038. }
  2039. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2040. {
  2041. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2042. {
  2043. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  2044. {
  2045. IncludeItemTypes = new[] { typeof(Series).Name },
  2046. Name = program.Name
  2047. }).Select(i => i.ToString("N")).ToArray();
  2048. if (seriesIds.Length == 0)
  2049. {
  2050. return false;
  2051. }
  2052. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2053. {
  2054. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  2055. {
  2056. IncludeItemTypes = new[] { typeof(Episode).Name },
  2057. ParentIndexNumber = program.SeasonNumber.Value,
  2058. IndexNumber = program.EpisodeNumber.Value,
  2059. AncestorIds = seriesIds,
  2060. IsVirtualItem = false
  2061. });
  2062. if (result.TotalRecordCount > 0)
  2063. {
  2064. return true;
  2065. }
  2066. }
  2067. }
  2068. return false;
  2069. }
  2070. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  2071. {
  2072. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  2073. {
  2074. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  2075. return new List<ProgramInfo>();
  2076. }
  2077. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  2078. }
  2079. private string GetChannelEpgCachePath(string channelId)
  2080. {
  2081. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  2082. }
  2083. private readonly object _epgLock = new object();
  2084. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  2085. {
  2086. var path = GetChannelEpgCachePath(channelId);
  2087. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  2088. lock (_epgLock)
  2089. {
  2090. _jsonSerializer.SerializeToFile(epgData, path);
  2091. }
  2092. }
  2093. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  2094. {
  2095. try
  2096. {
  2097. lock (_epgLock)
  2098. {
  2099. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  2100. }
  2101. }
  2102. catch
  2103. {
  2104. return new List<ProgramInfo>();
  2105. }
  2106. }
  2107. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  2108. {
  2109. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  2110. }
  2111. private bool _disposed;
  2112. public void Dispose()
  2113. {
  2114. _disposed = true;
  2115. foreach (var pair in _activeRecordings.ToList())
  2116. {
  2117. pair.Value.CancellationTokenSource.Cancel();
  2118. }
  2119. }
  2120. public List<VirtualFolderInfo> GetRecordingFolders()
  2121. {
  2122. var list = new List<VirtualFolderInfo>();
  2123. var defaultFolder = RecordingPath;
  2124. var defaultName = "Recordings";
  2125. if (_fileSystem.DirectoryExists(defaultFolder))
  2126. {
  2127. list.Add(new VirtualFolderInfo
  2128. {
  2129. Locations = new List<string> { defaultFolder },
  2130. Name = defaultName
  2131. });
  2132. }
  2133. var customPath = GetConfiguration().MovieRecordingPath;
  2134. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2135. {
  2136. list.Add(new VirtualFolderInfo
  2137. {
  2138. Locations = new List<string> { customPath },
  2139. Name = "Recorded Movies",
  2140. CollectionType = CollectionType.Movies
  2141. });
  2142. }
  2143. customPath = GetConfiguration().SeriesRecordingPath;
  2144. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2145. {
  2146. list.Add(new VirtualFolderInfo
  2147. {
  2148. Locations = new List<string> { customPath },
  2149. Name = "Recorded Series",
  2150. CollectionType = CollectionType.TvShows
  2151. });
  2152. }
  2153. return list;
  2154. }
  2155. class ActiveRecordingInfo
  2156. {
  2157. public string Path { get; set; }
  2158. public TimerInfo Timer { get; set; }
  2159. public ProgramInfo Program { get; set; }
  2160. public CancellationTokenSource CancellationTokenSource { get; set; }
  2161. }
  2162. private const int TunerDiscoveryDurationMs = 3000;
  2163. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2164. {
  2165. var list = new List<TunerHostInfo>();
  2166. var configuredDeviceIds = GetConfiguration().TunerHosts
  2167. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2168. .Select(i => i.DeviceId)
  2169. .ToList();
  2170. foreach (var host in _liveTvManager.TunerHosts)
  2171. {
  2172. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2173. if (newDevicesOnly)
  2174. {
  2175. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparer.OrdinalIgnoreCase))
  2176. .ToList();
  2177. }
  2178. list.AddRange(discoveredDevices);
  2179. }
  2180. return list;
  2181. }
  2182. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2183. {
  2184. foreach (var host in _liveTvManager.TunerHosts)
  2185. {
  2186. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2187. }
  2188. }
  2189. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2190. {
  2191. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2192. var configuredDevices = GetConfiguration().TunerHosts
  2193. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2194. .ToList();
  2195. foreach (var device in discoveredDevices)
  2196. {
  2197. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2198. if (configuredDevice != null)
  2199. {
  2200. if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2201. {
  2202. _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url);
  2203. configuredDevice.Url = device.Url;
  2204. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2205. }
  2206. }
  2207. }
  2208. }
  2209. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDuationMs, CancellationToken cancellationToken)
  2210. {
  2211. try
  2212. {
  2213. var discoveredDevices = await host.DiscoverDevices(discoveryDuationMs, cancellationToken).ConfigureAwait(false);
  2214. foreach (var device in discoveredDevices)
  2215. {
  2216. _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2217. }
  2218. return discoveredDevices;
  2219. }
  2220. catch (Exception ex)
  2221. {
  2222. _logger.ErrorException("Error discovering tuner devices", ex);
  2223. return new List<TunerHostInfo>();
  2224. }
  2225. }
  2226. }
  2227. public static class ConfigurationExtension
  2228. {
  2229. public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
  2230. {
  2231. return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  2232. }
  2233. }
  2234. }