EmbyTV.cs 89 KB

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