EmbyTV.cs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  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.StartDate = updatedTimer.StartDate;
  568. existingTimer.ShowId = updatedTimer.ShowId;
  569. }
  570. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  571. {
  572. throw new NotImplementedException();
  573. }
  574. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  575. {
  576. throw new NotImplementedException();
  577. }
  578. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  579. {
  580. throw new NotImplementedException();
  581. }
  582. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  583. {
  584. return _activeRecordings.Values.ToList().Select(GetRecordingInfo).ToList();
  585. }
  586. public string GetActiveRecordingPath(string id)
  587. {
  588. ActiveRecordingInfo info;
  589. if (_activeRecordings.TryGetValue(id, out info))
  590. {
  591. return info.Path;
  592. }
  593. return null;
  594. }
  595. private RecordingInfo GetRecordingInfo(ActiveRecordingInfo info)
  596. {
  597. var timer = info.Timer;
  598. var program = info.Program;
  599. var result = new RecordingInfo
  600. {
  601. ChannelId = timer.ChannelId,
  602. CommunityRating = timer.CommunityRating,
  603. DateLastUpdated = DateTime.UtcNow,
  604. EndDate = timer.EndDate,
  605. EpisodeTitle = timer.EpisodeTitle,
  606. Genres = timer.Genres,
  607. Id = "recording" + timer.Id,
  608. IsKids = timer.IsKids,
  609. IsMovie = timer.IsMovie,
  610. IsNews = timer.IsNews,
  611. IsRepeat = timer.IsRepeat,
  612. IsSeries = timer.IsProgramSeries,
  613. IsSports = timer.IsSports,
  614. Name = timer.Name,
  615. OfficialRating = timer.OfficialRating,
  616. OriginalAirDate = timer.OriginalAirDate,
  617. Overview = timer.Overview,
  618. ProgramId = timer.ProgramId,
  619. SeriesTimerId = timer.SeriesTimerId,
  620. StartDate = timer.StartDate,
  621. Status = RecordingStatus.InProgress,
  622. TimerId = timer.Id
  623. };
  624. if (program != null)
  625. {
  626. result.Audio = program.Audio;
  627. result.ImagePath = program.ImagePath;
  628. result.ImageUrl = program.ImageUrl;
  629. result.IsHD = program.IsHD;
  630. result.IsLive = program.IsLive;
  631. result.IsPremiere = program.IsPremiere;
  632. result.ShowId = program.ShowId;
  633. }
  634. return result;
  635. }
  636. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  637. {
  638. var excludeStatues = new List<RecordingStatus>
  639. {
  640. RecordingStatus.Completed
  641. };
  642. var timers = _timerProvider.GetAll()
  643. .Where(i => !excludeStatues.Contains(i.Status));
  644. return Task.FromResult(timers);
  645. }
  646. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  647. {
  648. var config = GetConfiguration();
  649. var defaults = new SeriesTimerInfo()
  650. {
  651. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  652. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  653. RecordAnyChannel = false,
  654. RecordAnyTime = true,
  655. RecordNewOnly = true,
  656. Days = new List<DayOfWeek>
  657. {
  658. DayOfWeek.Sunday,
  659. DayOfWeek.Monday,
  660. DayOfWeek.Tuesday,
  661. DayOfWeek.Wednesday,
  662. DayOfWeek.Thursday,
  663. DayOfWeek.Friday,
  664. DayOfWeek.Saturday
  665. }
  666. };
  667. if (program != null)
  668. {
  669. defaults.SeriesId = program.SeriesId;
  670. defaults.ProgramId = program.Id;
  671. defaults.RecordNewOnly = !program.IsRepeat;
  672. }
  673. defaults.SkipEpisodesInLibrary = defaults.RecordNewOnly;
  674. defaults.KeepUntil = KeepUntil.UntilDeleted;
  675. return Task.FromResult(defaults);
  676. }
  677. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  678. {
  679. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  680. }
  681. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  682. {
  683. try
  684. {
  685. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  686. }
  687. catch (OperationCanceledException)
  688. {
  689. throw;
  690. }
  691. catch (Exception ex)
  692. {
  693. _logger.ErrorException("Error getting programs", ex);
  694. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  695. }
  696. }
  697. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  698. {
  699. if (info.EnableAllTuners)
  700. {
  701. return true;
  702. }
  703. if (string.IsNullOrWhiteSpace(tunerHostId))
  704. {
  705. throw new ArgumentNullException("tunerHostId");
  706. }
  707. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  708. }
  709. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  710. {
  711. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  712. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  713. foreach (var provider in GetListingProviders())
  714. {
  715. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  716. {
  717. _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);
  718. continue;
  719. }
  720. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  721. var channelMappings = GetChannelMappings(provider.Item2);
  722. var channelNumber = channel.Number;
  723. if (!string.IsNullOrWhiteSpace(channelNumber))
  724. {
  725. string mappedChannelNumber;
  726. if (channelMappings.TryGetValue(channelNumber, out mappedChannelNumber))
  727. {
  728. _logger.Debug("Found mapped channel on provider {0}. Tuner channel number: {1}, Mapped channel number: {2}", provider.Item1.Name, channelNumber, mappedChannelNumber);
  729. channelNumber = mappedChannelNumber;
  730. }
  731. }
  732. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channelNumber, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  733. .ConfigureAwait(false);
  734. var list = programs.ToList();
  735. // Replace the value that came from the provider with a normalized value
  736. foreach (var program in list)
  737. {
  738. program.ChannelId = channelId;
  739. }
  740. if (list.Count > 0)
  741. {
  742. SaveEpgDataForChannel(channelId, list);
  743. return list;
  744. }
  745. }
  746. return new List<ProgramInfo>();
  747. }
  748. private Dictionary<string, string> GetChannelMappings(ListingsProviderInfo info)
  749. {
  750. var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  751. foreach (var mapping in info.ChannelMappings)
  752. {
  753. dict[mapping.Name] = mapping.Value;
  754. }
  755. return dict;
  756. }
  757. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  758. {
  759. return GetConfiguration().ListingProviders
  760. .Select(i =>
  761. {
  762. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  763. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  764. })
  765. .Where(i => i != null)
  766. .ToList();
  767. }
  768. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  769. {
  770. throw new NotImplementedException();
  771. }
  772. private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
  773. private readonly List<LiveStream> _liveStreams = new List<LiveStream>();
  774. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  775. {
  776. var result = await GetChannelStreamWithDirectStreamProvider(channelId, streamId, cancellationToken).ConfigureAwait(false);
  777. return result.Item1;
  778. }
  779. public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, CancellationToken cancellationToken)
  780. {
  781. var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
  782. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(result.Item2, result.Item1 as IDirectStreamProvider);
  783. }
  784. private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, bool enableStreamSharing)
  785. {
  786. var json = _jsonSerializer.SerializeToString(mediaSource);
  787. mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  788. mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
  789. //if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
  790. //{
  791. // var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks;
  792. // ticks = Math.Max(0, ticks);
  793. // mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture);
  794. //}
  795. return mediaSource;
  796. }
  797. public async Task<LiveStream> GetLiveStream(string uniqueId)
  798. {
  799. await _liveStreamsSemaphore.WaitAsync().ConfigureAwait(false);
  800. try
  801. {
  802. return _liveStreams
  803. .FirstOrDefault(i => string.Equals(i.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase));
  804. }
  805. finally
  806. {
  807. _liveStreamsSemaphore.Release();
  808. }
  809. }
  810. private async Task<Tuple<LiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  811. {
  812. _logger.Info("Streaming Channel " + channelId);
  813. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  814. try
  815. {
  816. var result = _liveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  817. if (result != null && result.EnableStreamSharing)
  818. {
  819. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  820. result.SharedStreamIds.Add(openedMediaSource.Id);
  821. _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  822. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, result.TunerHost);
  823. }
  824. foreach (var hostInstance in _liveTvManager.TunerHosts)
  825. {
  826. try
  827. {
  828. result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  829. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  830. result.SharedStreamIds.Add(openedMediaSource.Id);
  831. _liveStreams.Add(result);
  832. result.TunerHost = hostInstance;
  833. result.OriginalStreamId = streamId;
  834. _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
  835. streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  836. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, hostInstance);
  837. }
  838. catch (FileNotFoundException)
  839. {
  840. }
  841. catch (OperationCanceledException)
  842. {
  843. }
  844. }
  845. }
  846. finally
  847. {
  848. _liveStreamsSemaphore.Release();
  849. }
  850. throw new Exception("Tuner not found.");
  851. }
  852. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  853. {
  854. if (string.IsNullOrWhiteSpace(channelId))
  855. {
  856. throw new ArgumentNullException("channelId");
  857. }
  858. foreach (var hostInstance in _liveTvManager.TunerHosts)
  859. {
  860. try
  861. {
  862. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  863. if (sources.Count > 0)
  864. {
  865. return sources;
  866. }
  867. }
  868. catch (NotImplementedException)
  869. {
  870. }
  871. }
  872. throw new NotImplementedException();
  873. }
  874. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  875. {
  876. ActiveRecordingInfo info;
  877. recordingId = recordingId.Replace("recording", string.Empty);
  878. if (_activeRecordings.TryGetValue(recordingId, out info))
  879. {
  880. var stream = new MediaSourceInfo
  881. {
  882. Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + recordingId + "/stream",
  883. Id = recordingId,
  884. SupportsDirectPlay = false,
  885. SupportsDirectStream = true,
  886. SupportsTranscoding = true,
  887. IsInfiniteStream = true,
  888. RequiresOpening = false,
  889. RequiresClosing = false,
  890. Protocol = MediaBrowser.Model.MediaInfo.MediaProtocol.Http,
  891. BufferMs = 0
  892. };
  893. var isAudio = false;
  894. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  895. return new List<MediaSourceInfo>
  896. {
  897. stream
  898. };
  899. }
  900. throw new FileNotFoundException();
  901. }
  902. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  903. {
  904. // Ignore the consumer id
  905. //id = id.Substring(id.IndexOf('_') + 1);
  906. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  907. try
  908. {
  909. var stream = _liveStreams.FirstOrDefault(i => i.SharedStreamIds.Contains(id));
  910. if (stream != null)
  911. {
  912. stream.SharedStreamIds.Remove(id);
  913. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  914. if (stream.ConsumerCount <= 0)
  915. {
  916. _liveStreams.Remove(stream);
  917. _logger.Info("Closing live stream {0}", id);
  918. await stream.Close().ConfigureAwait(false);
  919. _logger.Info("Live stream {0} closed successfully", id);
  920. }
  921. }
  922. else
  923. {
  924. _logger.Warn("Live stream not found: {0}, unable to close", id);
  925. }
  926. }
  927. catch (OperationCanceledException)
  928. {
  929. }
  930. catch (Exception ex)
  931. {
  932. _logger.ErrorException("Error closing live stream", ex);
  933. }
  934. finally
  935. {
  936. _liveStreamsSemaphore.Release();
  937. }
  938. }
  939. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  940. {
  941. return Task.FromResult(0);
  942. }
  943. public Task ResetTuner(string id, CancellationToken cancellationToken)
  944. {
  945. return Task.FromResult(0);
  946. }
  947. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  948. {
  949. var timer = e.Argument;
  950. _logger.Info("Recording timer fired.");
  951. try
  952. {
  953. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  954. if (recordingEndDate <= DateTime.UtcNow)
  955. {
  956. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  957. OnTimerOutOfDate(timer);
  958. return;
  959. }
  960. var activeRecordingInfo = new ActiveRecordingInfo
  961. {
  962. CancellationTokenSource = new CancellationTokenSource(),
  963. Timer = timer
  964. };
  965. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  966. {
  967. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  968. }
  969. else
  970. {
  971. _logger.Info("Skipping RecordStream because it's already in progress.");
  972. }
  973. }
  974. catch (OperationCanceledException)
  975. {
  976. }
  977. catch (Exception ex)
  978. {
  979. _logger.ErrorException("Error recording stream", ex);
  980. }
  981. }
  982. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  983. {
  984. var recordPath = RecordingPath;
  985. var config = GetConfiguration();
  986. seriesPath = null;
  987. if (timer.IsProgramSeries)
  988. {
  989. var customRecordingPath = config.SeriesRecordingPath;
  990. var allowSubfolder = true;
  991. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  992. {
  993. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  994. recordPath = customRecordingPath;
  995. }
  996. if (allowSubfolder && config.EnableRecordingSubfolders)
  997. {
  998. recordPath = Path.Combine(recordPath, "Series");
  999. }
  1000. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1001. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  1002. recordPath = Path.Combine(recordPath, folderName);
  1003. seriesPath = recordPath;
  1004. if (timer.SeasonNumber.HasValue)
  1005. {
  1006. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  1007. recordPath = Path.Combine(recordPath, folderName);
  1008. }
  1009. }
  1010. else if (timer.IsMovie)
  1011. {
  1012. var customRecordingPath = config.MovieRecordingPath;
  1013. var allowSubfolder = true;
  1014. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1015. {
  1016. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1017. recordPath = customRecordingPath;
  1018. }
  1019. if (allowSubfolder && config.EnableRecordingSubfolders)
  1020. {
  1021. recordPath = Path.Combine(recordPath, "Movies");
  1022. }
  1023. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1024. if (timer.ProductionYear.HasValue)
  1025. {
  1026. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1027. }
  1028. recordPath = Path.Combine(recordPath, folderName);
  1029. }
  1030. else if (timer.IsKids)
  1031. {
  1032. if (config.EnableRecordingSubfolders)
  1033. {
  1034. recordPath = Path.Combine(recordPath, "Kids");
  1035. }
  1036. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1037. if (timer.ProductionYear.HasValue)
  1038. {
  1039. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1040. }
  1041. recordPath = Path.Combine(recordPath, folderName);
  1042. }
  1043. else if (timer.IsSports)
  1044. {
  1045. if (config.EnableRecordingSubfolders)
  1046. {
  1047. recordPath = Path.Combine(recordPath, "Sports");
  1048. }
  1049. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1050. }
  1051. else
  1052. {
  1053. if (config.EnableRecordingSubfolders)
  1054. {
  1055. recordPath = Path.Combine(recordPath, "Other");
  1056. }
  1057. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1058. }
  1059. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1060. return Path.Combine(recordPath, recordingFileName);
  1061. }
  1062. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  1063. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  1064. {
  1065. if (timer == null)
  1066. {
  1067. throw new ArgumentNullException("timer");
  1068. }
  1069. ProgramInfo programInfo = null;
  1070. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1071. {
  1072. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  1073. }
  1074. if (programInfo == null)
  1075. {
  1076. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1077. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1078. }
  1079. if (programInfo != null)
  1080. {
  1081. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  1082. activeRecordingInfo.Program = programInfo;
  1083. }
  1084. string seriesPath = null;
  1085. var recordPath = GetRecordingPath(timer, out seriesPath);
  1086. var recordingStatus = RecordingStatus.New;
  1087. string liveStreamId = null;
  1088. OnRecordingStatusChanged();
  1089. try
  1090. {
  1091. var recorder = await GetRecorder().ConfigureAwait(false);
  1092. var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  1093. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  1094. .ConfigureAwait(false);
  1095. var mediaStreamInfo = liveStreamInfo.Item2;
  1096. liveStreamId = mediaStreamInfo.Id;
  1097. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  1098. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  1099. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1100. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1101. _libraryManager.RegisterIgnoredPath(recordPath);
  1102. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1103. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  1104. activeRecordingInfo.Path = recordPath;
  1105. var duration = recordingEndDate - DateTime.UtcNow;
  1106. _logger.Info("Beginning recording. Will record for {0} minutes.",
  1107. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1108. _logger.Info("Writing file to path: " + recordPath);
  1109. _logger.Info("Opening recording stream from tuner provider");
  1110. Action onStarted = () =>
  1111. {
  1112. timer.Status = RecordingStatus.InProgress;
  1113. _timerProvider.AddOrUpdate(timer, false);
  1114. SaveRecordingMetadata(timer, recordPath, seriesPath);
  1115. EnforceKeepUpTo(timer);
  1116. };
  1117. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  1118. .ConfigureAwait(false);
  1119. recordingStatus = RecordingStatus.Completed;
  1120. _logger.Info("Recording completed: {0}", recordPath);
  1121. }
  1122. catch (OperationCanceledException)
  1123. {
  1124. _logger.Info("Recording stopped: {0}", recordPath);
  1125. recordingStatus = RecordingStatus.Completed;
  1126. }
  1127. catch (Exception ex)
  1128. {
  1129. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  1130. recordingStatus = RecordingStatus.Error;
  1131. }
  1132. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1133. {
  1134. try
  1135. {
  1136. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1137. }
  1138. catch (Exception ex)
  1139. {
  1140. _logger.ErrorException("Error closing live stream", ex);
  1141. }
  1142. }
  1143. _libraryManager.UnRegisterIgnoredPath(recordPath);
  1144. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  1145. ActiveRecordingInfo removed;
  1146. _activeRecordings.TryRemove(timer.Id, out removed);
  1147. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1148. {
  1149. const int retryIntervalSeconds = 60;
  1150. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1151. timer.Status = RecordingStatus.New;
  1152. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1153. timer.RetryCount++;
  1154. _timerProvider.AddOrUpdate(timer);
  1155. }
  1156. else if (_fileSystem.FileExists(recordPath))
  1157. {
  1158. timer.RecordingPath = recordPath;
  1159. timer.Status = RecordingStatus.Completed;
  1160. _timerProvider.AddOrUpdate(timer, false);
  1161. OnSuccessfulRecording(timer, recordPath);
  1162. }
  1163. else
  1164. {
  1165. _timerProvider.Delete(timer);
  1166. }
  1167. OnRecordingStatusChanged();
  1168. }
  1169. private void OnRecordingStatusChanged()
  1170. {
  1171. EventHelper.FireEventIfNotNull(RecordingStatusChanged, this, new RecordingStatusChangedEventArgs
  1172. {
  1173. }, _logger);
  1174. }
  1175. private async void EnforceKeepUpTo(TimerInfo timer)
  1176. {
  1177. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1178. {
  1179. return;
  1180. }
  1181. var seriesTimerId = timer.SeriesTimerId;
  1182. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1183. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1184. {
  1185. return;
  1186. }
  1187. if (_disposed)
  1188. {
  1189. return;
  1190. }
  1191. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1192. try
  1193. {
  1194. if (_disposed)
  1195. {
  1196. return;
  1197. }
  1198. var timersToDelete = _timerProvider.GetAll()
  1199. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1200. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1201. .OrderByDescending(i => i.EndDate)
  1202. .Where(i => _fileSystem.FileExists(i.RecordingPath))
  1203. .Skip(seriesTimer.KeepUpTo - 1)
  1204. .ToList();
  1205. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1206. }
  1207. finally
  1208. {
  1209. _recordingDeleteSemaphore.Release();
  1210. }
  1211. }
  1212. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1213. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1214. {
  1215. foreach (var timer in timers)
  1216. {
  1217. if (_disposed)
  1218. {
  1219. return;
  1220. }
  1221. try
  1222. {
  1223. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1224. }
  1225. catch (Exception ex)
  1226. {
  1227. _logger.ErrorException("Error deleting recording", ex);
  1228. }
  1229. }
  1230. }
  1231. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1232. {
  1233. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1234. if (libraryItem != null)
  1235. {
  1236. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1237. {
  1238. DeleteFileLocation = true
  1239. });
  1240. }
  1241. else
  1242. {
  1243. try
  1244. {
  1245. _fileSystem.DeleteFile(timer.RecordingPath);
  1246. }
  1247. catch (IOException)
  1248. {
  1249. }
  1250. }
  1251. _timerProvider.Delete(timer);
  1252. }
  1253. private string EnsureFileUnique(string path, string timerId)
  1254. {
  1255. var originalPath = path;
  1256. var index = 1;
  1257. while (FileExists(path, timerId))
  1258. {
  1259. var parent = Path.GetDirectoryName(originalPath);
  1260. var name = Path.GetFileNameWithoutExtension(originalPath);
  1261. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1262. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1263. index++;
  1264. }
  1265. return path;
  1266. }
  1267. private bool FileExists(string path, string timerId)
  1268. {
  1269. if (_fileSystem.FileExists(path))
  1270. {
  1271. return true;
  1272. }
  1273. var hasRecordingAtPath = _activeRecordings
  1274. .Values
  1275. .ToList()
  1276. .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1277. if (hasRecordingAtPath)
  1278. {
  1279. return true;
  1280. }
  1281. return false;
  1282. }
  1283. private async Task<IRecorder> GetRecorder()
  1284. {
  1285. var config = GetConfiguration();
  1286. if (config.EnableRecordingEncoding)
  1287. {
  1288. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1289. if (regInfo.IsValid)
  1290. {
  1291. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient, _processFactory);
  1292. }
  1293. }
  1294. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1295. }
  1296. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1297. {
  1298. //if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1299. //{
  1300. // try
  1301. // {
  1302. // // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1303. // // ideally this shouldn't be hard-coded
  1304. // await Task.Delay(30000).ConfigureAwait(false);
  1305. // var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1306. // var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1307. // if (result.Status == FileSortingStatus.Success)
  1308. // {
  1309. // return;
  1310. // }
  1311. // }
  1312. // catch (Exception ex)
  1313. // {
  1314. // _logger.ErrorException("Error processing new recording", ex);
  1315. // }
  1316. //}
  1317. PostProcessRecording(timer, path);
  1318. }
  1319. private void PostProcessRecording(TimerInfo timer, string path)
  1320. {
  1321. var options = GetConfiguration();
  1322. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1323. {
  1324. return;
  1325. }
  1326. try
  1327. {
  1328. var process = _processFactory.Create(new ProcessOptions
  1329. {
  1330. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1331. CreateNoWindow = true,
  1332. EnableRaisingEvents = true,
  1333. ErrorDialog = false,
  1334. FileName = options.RecordingPostProcessor,
  1335. IsHidden = true,
  1336. UseShellExecute = false
  1337. });
  1338. _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1339. process.Exited += Process_Exited;
  1340. process.Start();
  1341. }
  1342. catch (Exception ex)
  1343. {
  1344. _logger.ErrorException("Error running recording post processor", ex);
  1345. }
  1346. }
  1347. private string GetPostProcessArguments(string path, string arguments)
  1348. {
  1349. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1350. }
  1351. private void Process_Exited(object sender, EventArgs e)
  1352. {
  1353. var process = (IProcess)sender;
  1354. try
  1355. {
  1356. _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
  1357. }
  1358. catch
  1359. {
  1360. }
  1361. process.Dispose();
  1362. }
  1363. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1364. {
  1365. if (!image.IsLocalFile)
  1366. {
  1367. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1368. }
  1369. string imageSaveFilenameWithoutExtension = null;
  1370. switch (image.Type)
  1371. {
  1372. case ImageType.Primary:
  1373. if (program.IsSeries)
  1374. {
  1375. imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
  1376. }
  1377. else
  1378. {
  1379. imageSaveFilenameWithoutExtension = "poster";
  1380. }
  1381. break;
  1382. case ImageType.Logo:
  1383. imageSaveFilenameWithoutExtension = "logo";
  1384. break;
  1385. case ImageType.Thumb:
  1386. imageSaveFilenameWithoutExtension = "landscape";
  1387. break;
  1388. case ImageType.Backdrop:
  1389. imageSaveFilenameWithoutExtension = "fanart";
  1390. break;
  1391. default:
  1392. break;
  1393. }
  1394. if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
  1395. {
  1396. return;
  1397. }
  1398. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1399. // preserve original image extension
  1400. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1401. _fileSystem.CopyFile(image.Path, imageSavePath, true);
  1402. }
  1403. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1404. {
  1405. var image = program.GetImageInfo(ImageType.Primary, 0);
  1406. if (image != null && program.IsMovie)
  1407. {
  1408. try
  1409. {
  1410. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1411. }
  1412. catch (Exception ex)
  1413. {
  1414. _logger.ErrorException("Error saving recording image", ex);
  1415. }
  1416. }
  1417. if (!program.IsSeries)
  1418. {
  1419. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1420. if (image != null)
  1421. {
  1422. try
  1423. {
  1424. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1425. }
  1426. catch (Exception ex)
  1427. {
  1428. _logger.ErrorException("Error saving recording image", ex);
  1429. }
  1430. }
  1431. image = program.GetImageInfo(ImageType.Thumb, 0);
  1432. if (image != null)
  1433. {
  1434. try
  1435. {
  1436. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1437. }
  1438. catch (Exception ex)
  1439. {
  1440. _logger.ErrorException("Error saving recording image", ex);
  1441. }
  1442. }
  1443. image = program.GetImageInfo(ImageType.Logo, 0);
  1444. if (image != null)
  1445. {
  1446. try
  1447. {
  1448. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1449. }
  1450. catch (Exception ex)
  1451. {
  1452. _logger.ErrorException("Error saving recording image", ex);
  1453. }
  1454. }
  1455. }
  1456. }
  1457. private async void SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1458. {
  1459. try
  1460. {
  1461. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1462. {
  1463. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1464. Limit = 1,
  1465. ExternalId = timer.ProgramId
  1466. }).FirstOrDefault() as LiveTvProgram;
  1467. // dummy this up
  1468. if (program == null)
  1469. {
  1470. program = new LiveTvProgram
  1471. {
  1472. Name = timer.Name,
  1473. HomePageUrl = timer.HomePageUrl,
  1474. Overview = timer.Overview,
  1475. Genres = timer.Genres,
  1476. CommunityRating = timer.CommunityRating,
  1477. OfficialRating = timer.OfficialRating,
  1478. ProductionYear = timer.ProductionYear,
  1479. PremiereDate = timer.OriginalAirDate,
  1480. IndexNumber = timer.EpisodeNumber,
  1481. ParentIndexNumber = timer.SeasonNumber
  1482. };
  1483. }
  1484. if (timer.IsSports)
  1485. {
  1486. AddGenre(program.Genres, "Sports");
  1487. }
  1488. if (timer.IsKids)
  1489. {
  1490. AddGenre(program.Genres, "Kids");
  1491. AddGenre(program.Genres, "Children");
  1492. }
  1493. if (timer.IsNews)
  1494. {
  1495. AddGenre(program.Genres, "News");
  1496. }
  1497. if (timer.IsProgramSeries)
  1498. {
  1499. SaveSeriesNfo(timer, seriesPath);
  1500. SaveVideoNfo(timer, recordingPath, program, false);
  1501. }
  1502. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1503. {
  1504. SaveVideoNfo(timer, recordingPath, program, true);
  1505. }
  1506. else
  1507. {
  1508. SaveVideoNfo(timer, recordingPath, program, false);
  1509. }
  1510. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1511. }
  1512. catch (Exception ex)
  1513. {
  1514. _logger.ErrorException("Error saving nfo", ex);
  1515. }
  1516. }
  1517. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1518. {
  1519. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1520. if (_fileSystem.FileExists(nfoPath))
  1521. {
  1522. return;
  1523. }
  1524. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1525. {
  1526. var settings = new XmlWriterSettings
  1527. {
  1528. Indent = true,
  1529. Encoding = Encoding.UTF8,
  1530. CloseOutput = false
  1531. };
  1532. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1533. {
  1534. writer.WriteStartDocument(true);
  1535. writer.WriteStartElement("tvshow");
  1536. if (!string.IsNullOrWhiteSpace(timer.Name))
  1537. {
  1538. writer.WriteElementString("title", timer.Name);
  1539. }
  1540. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1541. {
  1542. writer.WriteElementString("mpaa", timer.OfficialRating);
  1543. }
  1544. foreach (var genre in timer.Genres)
  1545. {
  1546. writer.WriteElementString("genre", genre);
  1547. }
  1548. writer.WriteEndElement();
  1549. writer.WriteEndDocument();
  1550. }
  1551. }
  1552. }
  1553. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1554. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1555. {
  1556. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1557. if (_fileSystem.FileExists(nfoPath))
  1558. {
  1559. return;
  1560. }
  1561. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1562. {
  1563. var settings = new XmlWriterSettings
  1564. {
  1565. Indent = true,
  1566. Encoding = Encoding.UTF8,
  1567. CloseOutput = false
  1568. };
  1569. var options = _config.GetNfoConfiguration();
  1570. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1571. {
  1572. writer.WriteStartDocument(true);
  1573. if (timer.IsProgramSeries)
  1574. {
  1575. writer.WriteStartElement("episodedetails");
  1576. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1577. {
  1578. writer.WriteElementString("title", timer.EpisodeTitle);
  1579. }
  1580. if (item.PremiereDate.HasValue)
  1581. {
  1582. var formatString = options.ReleaseDateFormat;
  1583. writer.WriteElementString("aired", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1584. }
  1585. if (item.IndexNumber.HasValue)
  1586. {
  1587. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1588. }
  1589. if (item.ParentIndexNumber.HasValue)
  1590. {
  1591. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1592. }
  1593. }
  1594. else
  1595. {
  1596. writer.WriteStartElement("movie");
  1597. if (!string.IsNullOrWhiteSpace(item.Name))
  1598. {
  1599. writer.WriteElementString("title", item.Name);
  1600. }
  1601. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1602. {
  1603. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1604. }
  1605. if (item.PremiereDate.HasValue)
  1606. {
  1607. var formatString = options.ReleaseDateFormat;
  1608. writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1609. writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1610. }
  1611. }
  1612. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1613. if (item.ProductionYear.HasValue)
  1614. {
  1615. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1616. }
  1617. if (!string.IsNullOrEmpty(item.OfficialRating))
  1618. {
  1619. writer.WriteElementString("mpaa", item.OfficialRating);
  1620. }
  1621. if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
  1622. {
  1623. writer.WriteElementString("mpaadescription", item.OfficialRatingDescription);
  1624. }
  1625. var overview = (item.Overview ?? string.Empty)
  1626. .StripHtml()
  1627. .Replace("&quot;", "'");
  1628. writer.WriteElementString("plot", overview);
  1629. if (lockData)
  1630. {
  1631. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1632. }
  1633. if (item.CommunityRating.HasValue)
  1634. {
  1635. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1636. }
  1637. foreach (var genre in item.Genres)
  1638. {
  1639. writer.WriteElementString("genre", genre);
  1640. }
  1641. if (!string.IsNullOrWhiteSpace(item.HomePageUrl))
  1642. {
  1643. writer.WriteElementString("website", item.HomePageUrl);
  1644. }
  1645. var people = item.Id == Guid.Empty ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1646. var directors = people
  1647. .Where(i => IsPersonType(i, PersonType.Director))
  1648. .Select(i => i.Name)
  1649. .ToList();
  1650. foreach (var person in directors)
  1651. {
  1652. writer.WriteElementString("director", person);
  1653. }
  1654. var writers = people
  1655. .Where(i => IsPersonType(i, PersonType.Writer))
  1656. .Select(i => i.Name)
  1657. .Distinct(StringComparer.OrdinalIgnoreCase)
  1658. .ToList();
  1659. foreach (var person in writers)
  1660. {
  1661. writer.WriteElementString("writer", person);
  1662. }
  1663. foreach (var person in writers)
  1664. {
  1665. writer.WriteElementString("credits", person);
  1666. }
  1667. var rt = item.GetProviderId(MetadataProviders.RottenTomatoes);
  1668. if (!string.IsNullOrEmpty(rt))
  1669. {
  1670. writer.WriteElementString("rottentomatoesid", rt);
  1671. }
  1672. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  1673. if (!string.IsNullOrEmpty(tmdbCollection))
  1674. {
  1675. writer.WriteElementString("collectionnumber", tmdbCollection);
  1676. }
  1677. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  1678. if (!string.IsNullOrEmpty(imdb))
  1679. {
  1680. if (item is Series)
  1681. {
  1682. writer.WriteElementString("imdb_id", imdb);
  1683. }
  1684. else
  1685. {
  1686. writer.WriteElementString("imdbid", imdb);
  1687. }
  1688. }
  1689. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  1690. if (!string.IsNullOrEmpty(tvdb))
  1691. {
  1692. writer.WriteElementString("tvdbid", tvdb);
  1693. }
  1694. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  1695. if (!string.IsNullOrEmpty(tmdb))
  1696. {
  1697. writer.WriteElementString("tmdbid", tmdb);
  1698. }
  1699. if (item.CriticRating.HasValue)
  1700. {
  1701. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1702. }
  1703. if (!string.IsNullOrEmpty(item.CriticRatingSummary))
  1704. {
  1705. writer.WriteElementString("criticratingsummary", item.CriticRatingSummary);
  1706. }
  1707. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1708. {
  1709. writer.WriteElementString("tagline", item.Tagline);
  1710. }
  1711. foreach (var studio in item.Studios)
  1712. {
  1713. writer.WriteElementString("studio", studio);
  1714. }
  1715. if (item.VoteCount.HasValue)
  1716. {
  1717. writer.WriteElementString("votes", item.VoteCount.Value.ToString(CultureInfo.InvariantCulture));
  1718. }
  1719. writer.WriteEndElement();
  1720. writer.WriteEndDocument();
  1721. }
  1722. }
  1723. }
  1724. private static bool IsPersonType(PersonInfo person, string type)
  1725. {
  1726. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1727. }
  1728. private void AddGenre(List<string> genres, string genre)
  1729. {
  1730. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1731. {
  1732. genres.Add(genre);
  1733. }
  1734. }
  1735. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1736. {
  1737. var epgData = GetEpgDataForChannel(channelId);
  1738. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1739. }
  1740. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1741. {
  1742. var epgData = GetEpgDataForChannel(channelId);
  1743. var startDateTicks = startDateUtc.Ticks;
  1744. // Find the first program that starts within 3 minutes
  1745. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1746. }
  1747. private LiveTvOptions GetConfiguration()
  1748. {
  1749. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1750. }
  1751. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1752. {
  1753. if (!seriesTimer.RecordAnyTime)
  1754. {
  1755. if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(5).Ticks)
  1756. {
  1757. return true;
  1758. }
  1759. }
  1760. //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
  1761. //{
  1762. // return true;
  1763. //}
  1764. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1765. {
  1766. return true;
  1767. }
  1768. if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1769. {
  1770. return true;
  1771. }
  1772. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1773. }
  1774. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1775. {
  1776. foreach (var timer in timers.Skip(1))
  1777. {
  1778. // TODO: Get smarter, prefer HD, etc
  1779. timer.Status = RecordingStatus.Cancelled;
  1780. _timerProvider.Update(timer);
  1781. }
  1782. }
  1783. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1784. {
  1785. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1786. foreach (var group in groups)
  1787. {
  1788. if (string.IsNullOrWhiteSpace(group.Key))
  1789. {
  1790. continue;
  1791. }
  1792. var groupTimers = group.ToList();
  1793. if (groupTimers.Count < 2)
  1794. {
  1795. continue;
  1796. }
  1797. HandleDuplicateShowIds(groupTimers);
  1798. }
  1799. }
  1800. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1801. {
  1802. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1803. .ToList();
  1804. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1805. var enabledTimersForSeries = new List<TimerInfo>();
  1806. if (registration.IsValid)
  1807. {
  1808. foreach (var timer in allTimers)
  1809. {
  1810. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1811. if (existingTimer == null)
  1812. {
  1813. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1814. {
  1815. timer.Status = RecordingStatus.Cancelled;
  1816. }
  1817. else
  1818. {
  1819. enabledTimersForSeries.Add(timer);
  1820. }
  1821. _timerProvider.Add(timer);
  1822. }
  1823. else
  1824. {
  1825. // Only update if not currently active
  1826. ActiveRecordingInfo activeRecordingInfo;
  1827. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
  1828. {
  1829. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1830. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1831. {
  1832. existingTimer.Status = RecordingStatus.Cancelled;
  1833. }
  1834. if (existingTimer.Status != RecordingStatus.Cancelled)
  1835. {
  1836. enabledTimersForSeries.Add(existingTimer);
  1837. }
  1838. if (updateTimerSettings)
  1839. {
  1840. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1841. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1842. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1843. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1844. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1845. existingTimer.Priority = seriesTimer.Priority;
  1846. }
  1847. existingTimer.SeriesTimerId = seriesTimer.Id;
  1848. _timerProvider.Update(existingTimer);
  1849. }
  1850. }
  1851. }
  1852. }
  1853. SearchForDuplicateShowIds(enabledTimersForSeries);
  1854. if (deleteInvalidTimers)
  1855. {
  1856. var allTimerIds = allTimers
  1857. .Select(i => i.Id)
  1858. .ToList();
  1859. var deleteStatuses = new List<RecordingStatus>
  1860. {
  1861. RecordingStatus.New
  1862. };
  1863. var deletes = _timerProvider.GetAll()
  1864. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1865. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1866. .Where(i => deleteStatuses.Contains(i.Status))
  1867. .ToList();
  1868. foreach (var timer in deletes)
  1869. {
  1870. CancelTimerInternal(timer.Id, false);
  1871. }
  1872. }
  1873. }
  1874. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1875. {
  1876. if (seriesTimer == null)
  1877. {
  1878. throw new ArgumentNullException("seriesTimer");
  1879. }
  1880. if (allPrograms == null)
  1881. {
  1882. throw new ArgumentNullException("allPrograms");
  1883. }
  1884. // Exclude programs that have already ended
  1885. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  1886. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  1887. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  1888. }
  1889. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  1890. {
  1891. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1892. {
  1893. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  1894. {
  1895. IncludeItemTypes = new[] { typeof(Series).Name },
  1896. Name = program.Name
  1897. }).Select(i => i.ToString("N")).ToArray();
  1898. if (seriesIds.Length == 0)
  1899. {
  1900. return false;
  1901. }
  1902. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  1903. {
  1904. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1905. {
  1906. IncludeItemTypes = new[] { typeof(Episode).Name },
  1907. ParentIndexNumber = program.SeasonNumber.Value,
  1908. IndexNumber = program.EpisodeNumber.Value,
  1909. AncestorIds = seriesIds,
  1910. IsVirtualItem = false
  1911. });
  1912. if (result.TotalRecordCount > 0)
  1913. {
  1914. return true;
  1915. }
  1916. }
  1917. }
  1918. return false;
  1919. }
  1920. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1921. {
  1922. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  1923. {
  1924. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  1925. return new List<ProgramInfo>();
  1926. }
  1927. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1928. }
  1929. private string GetChannelEpgCachePath(string channelId)
  1930. {
  1931. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1932. }
  1933. private readonly object _epgLock = new object();
  1934. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1935. {
  1936. var path = GetChannelEpgCachePath(channelId);
  1937. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1938. lock (_epgLock)
  1939. {
  1940. _jsonSerializer.SerializeToFile(epgData, path);
  1941. }
  1942. }
  1943. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1944. {
  1945. try
  1946. {
  1947. lock (_epgLock)
  1948. {
  1949. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1950. }
  1951. }
  1952. catch
  1953. {
  1954. return new List<ProgramInfo>();
  1955. }
  1956. }
  1957. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1958. {
  1959. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1960. }
  1961. private bool _disposed;
  1962. public void Dispose()
  1963. {
  1964. _disposed = true;
  1965. foreach (var pair in _activeRecordings.ToList())
  1966. {
  1967. pair.Value.CancellationTokenSource.Cancel();
  1968. }
  1969. }
  1970. public List<VirtualFolderInfo> GetRecordingFolders()
  1971. {
  1972. var list = new List<VirtualFolderInfo>();
  1973. var defaultFolder = RecordingPath;
  1974. var defaultName = "Recordings";
  1975. if (_fileSystem.DirectoryExists(defaultFolder))
  1976. {
  1977. list.Add(new VirtualFolderInfo
  1978. {
  1979. Locations = new List<string> { defaultFolder },
  1980. Name = defaultName
  1981. });
  1982. }
  1983. var customPath = GetConfiguration().MovieRecordingPath;
  1984. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  1985. {
  1986. list.Add(new VirtualFolderInfo
  1987. {
  1988. Locations = new List<string> { customPath },
  1989. Name = "Recorded Movies",
  1990. CollectionType = CollectionType.Movies
  1991. });
  1992. }
  1993. customPath = GetConfiguration().SeriesRecordingPath;
  1994. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  1995. {
  1996. list.Add(new VirtualFolderInfo
  1997. {
  1998. Locations = new List<string> { customPath },
  1999. Name = "Recorded Series",
  2000. CollectionType = CollectionType.TvShows
  2001. });
  2002. }
  2003. return list;
  2004. }
  2005. class ActiveRecordingInfo
  2006. {
  2007. public string Path { get; set; }
  2008. public TimerInfo Timer { get; set; }
  2009. public ProgramInfo Program { get; set; }
  2010. public CancellationTokenSource CancellationTokenSource { get; set; }
  2011. }
  2012. }
  2013. public static class ConfigurationExtension
  2014. {
  2015. public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
  2016. {
  2017. return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  2018. }
  2019. }
  2020. }