EmbyTV.cs 101 KB

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