EmbyTV.cs 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419
  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. stream.InferTotalBitrate();
  894. return new List<MediaSourceInfo>
  895. {
  896. stream
  897. };
  898. }
  899. throw new FileNotFoundException();
  900. }
  901. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  902. {
  903. // Ignore the consumer id
  904. //id = id.Substring(id.IndexOf('_') + 1);
  905. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  906. try
  907. {
  908. var stream = _liveStreams.FirstOrDefault(i => i.SharedStreamIds.Contains(id));
  909. if (stream != null)
  910. {
  911. stream.SharedStreamIds.Remove(id);
  912. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  913. if (stream.ConsumerCount <= 0)
  914. {
  915. _liveStreams.Remove(stream);
  916. _logger.Info("Closing live stream {0}", id);
  917. await stream.Close().ConfigureAwait(false);
  918. _logger.Info("Live stream {0} closed successfully", id);
  919. }
  920. }
  921. else
  922. {
  923. _logger.Warn("Live stream not found: {0}, unable to close", id);
  924. }
  925. }
  926. catch (OperationCanceledException)
  927. {
  928. }
  929. catch (Exception ex)
  930. {
  931. _logger.ErrorException("Error closing live stream", ex);
  932. }
  933. finally
  934. {
  935. _liveStreamsSemaphore.Release();
  936. }
  937. }
  938. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  939. {
  940. return Task.FromResult(0);
  941. }
  942. public Task ResetTuner(string id, CancellationToken cancellationToken)
  943. {
  944. return Task.FromResult(0);
  945. }
  946. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  947. {
  948. var timer = e.Argument;
  949. _logger.Info("Recording timer fired.");
  950. try
  951. {
  952. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  953. if (recordingEndDate <= DateTime.UtcNow)
  954. {
  955. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  956. OnTimerOutOfDate(timer);
  957. return;
  958. }
  959. var activeRecordingInfo = new ActiveRecordingInfo
  960. {
  961. CancellationTokenSource = new CancellationTokenSource(),
  962. Timer = timer
  963. };
  964. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  965. {
  966. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  967. }
  968. else
  969. {
  970. _logger.Info("Skipping RecordStream because it's already in progress.");
  971. }
  972. }
  973. catch (OperationCanceledException)
  974. {
  975. }
  976. catch (Exception ex)
  977. {
  978. _logger.ErrorException("Error recording stream", ex);
  979. }
  980. }
  981. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  982. {
  983. var recordPath = RecordingPath;
  984. var config = GetConfiguration();
  985. seriesPath = null;
  986. if (timer.IsProgramSeries)
  987. {
  988. var customRecordingPath = config.SeriesRecordingPath;
  989. var allowSubfolder = true;
  990. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  991. {
  992. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  993. recordPath = customRecordingPath;
  994. }
  995. if (allowSubfolder && config.EnableRecordingSubfolders)
  996. {
  997. recordPath = Path.Combine(recordPath, "Series");
  998. }
  999. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1000. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  1001. recordPath = Path.Combine(recordPath, folderName);
  1002. seriesPath = recordPath;
  1003. if (timer.SeasonNumber.HasValue)
  1004. {
  1005. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  1006. recordPath = Path.Combine(recordPath, folderName);
  1007. }
  1008. }
  1009. else if (timer.IsMovie)
  1010. {
  1011. var customRecordingPath = config.MovieRecordingPath;
  1012. var allowSubfolder = true;
  1013. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1014. {
  1015. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1016. recordPath = customRecordingPath;
  1017. }
  1018. if (allowSubfolder && config.EnableRecordingSubfolders)
  1019. {
  1020. recordPath = Path.Combine(recordPath, "Movies");
  1021. }
  1022. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1023. if (timer.ProductionYear.HasValue)
  1024. {
  1025. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1026. }
  1027. recordPath = Path.Combine(recordPath, folderName);
  1028. }
  1029. else if (timer.IsKids)
  1030. {
  1031. if (config.EnableRecordingSubfolders)
  1032. {
  1033. recordPath = Path.Combine(recordPath, "Kids");
  1034. }
  1035. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1036. if (timer.ProductionYear.HasValue)
  1037. {
  1038. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1039. }
  1040. recordPath = Path.Combine(recordPath, folderName);
  1041. }
  1042. else if (timer.IsSports)
  1043. {
  1044. if (config.EnableRecordingSubfolders)
  1045. {
  1046. recordPath = Path.Combine(recordPath, "Sports");
  1047. }
  1048. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1049. }
  1050. else
  1051. {
  1052. if (config.EnableRecordingSubfolders)
  1053. {
  1054. recordPath = Path.Combine(recordPath, "Other");
  1055. }
  1056. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1057. }
  1058. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1059. return Path.Combine(recordPath, recordingFileName);
  1060. }
  1061. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  1062. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  1063. {
  1064. if (timer == null)
  1065. {
  1066. throw new ArgumentNullException("timer");
  1067. }
  1068. ProgramInfo programInfo = null;
  1069. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1070. {
  1071. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  1072. }
  1073. if (programInfo == null)
  1074. {
  1075. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1076. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1077. }
  1078. if (programInfo != null)
  1079. {
  1080. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  1081. activeRecordingInfo.Program = programInfo;
  1082. }
  1083. string seriesPath = null;
  1084. var recordPath = GetRecordingPath(timer, out seriesPath);
  1085. var recordingStatus = RecordingStatus.New;
  1086. string liveStreamId = null;
  1087. OnRecordingStatusChanged();
  1088. try
  1089. {
  1090. var recorder = await GetRecorder().ConfigureAwait(false);
  1091. var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  1092. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  1093. .ConfigureAwait(false);
  1094. var mediaStreamInfo = liveStreamInfo.Item2;
  1095. liveStreamId = mediaStreamInfo.Id;
  1096. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  1097. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  1098. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1099. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1100. _libraryManager.RegisterIgnoredPath(recordPath);
  1101. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1102. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  1103. activeRecordingInfo.Path = recordPath;
  1104. var duration = recordingEndDate - DateTime.UtcNow;
  1105. _logger.Info("Beginning recording. Will record for {0} minutes.",
  1106. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1107. _logger.Info("Writing file to path: " + recordPath);
  1108. _logger.Info("Opening recording stream from tuner provider");
  1109. Action onStarted = () =>
  1110. {
  1111. timer.Status = RecordingStatus.InProgress;
  1112. _timerProvider.AddOrUpdate(timer, false);
  1113. SaveRecordingMetadata(timer, recordPath, seriesPath);
  1114. EnforceKeepUpTo(timer);
  1115. };
  1116. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  1117. .ConfigureAwait(false);
  1118. recordingStatus = RecordingStatus.Completed;
  1119. _logger.Info("Recording completed: {0}", recordPath);
  1120. }
  1121. catch (OperationCanceledException)
  1122. {
  1123. _logger.Info("Recording stopped: {0}", recordPath);
  1124. recordingStatus = RecordingStatus.Completed;
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  1129. recordingStatus = RecordingStatus.Error;
  1130. }
  1131. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1132. {
  1133. try
  1134. {
  1135. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1136. }
  1137. catch (Exception ex)
  1138. {
  1139. _logger.ErrorException("Error closing live stream", ex);
  1140. }
  1141. }
  1142. _libraryManager.UnRegisterIgnoredPath(recordPath);
  1143. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  1144. ActiveRecordingInfo removed;
  1145. _activeRecordings.TryRemove(timer.Id, out removed);
  1146. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate)
  1147. {
  1148. const int retryIntervalSeconds = 60;
  1149. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1150. timer.Status = RecordingStatus.New;
  1151. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1152. _timerProvider.AddOrUpdate(timer);
  1153. }
  1154. else if (_fileSystem.FileExists(recordPath))
  1155. {
  1156. timer.RecordingPath = recordPath;
  1157. timer.Status = RecordingStatus.Completed;
  1158. _timerProvider.AddOrUpdate(timer, false);
  1159. OnSuccessfulRecording(timer, recordPath);
  1160. }
  1161. else
  1162. {
  1163. _timerProvider.Delete(timer);
  1164. }
  1165. OnRecordingStatusChanged();
  1166. }
  1167. private void OnRecordingStatusChanged()
  1168. {
  1169. EventHelper.FireEventIfNotNull(RecordingStatusChanged, this, new RecordingStatusChangedEventArgs
  1170. {
  1171. }, _logger);
  1172. }
  1173. private async void EnforceKeepUpTo(TimerInfo timer)
  1174. {
  1175. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1176. {
  1177. return;
  1178. }
  1179. var seriesTimerId = timer.SeriesTimerId;
  1180. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1181. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1182. {
  1183. return;
  1184. }
  1185. if (_disposed)
  1186. {
  1187. return;
  1188. }
  1189. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1190. try
  1191. {
  1192. if (_disposed)
  1193. {
  1194. return;
  1195. }
  1196. var timersToDelete = _timerProvider.GetAll()
  1197. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1198. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1199. .OrderByDescending(i => i.EndDate)
  1200. .Where(i => _fileSystem.FileExists(i.RecordingPath))
  1201. .Skip(seriesTimer.KeepUpTo - 1)
  1202. .ToList();
  1203. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1204. }
  1205. finally
  1206. {
  1207. _recordingDeleteSemaphore.Release();
  1208. }
  1209. }
  1210. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1211. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1212. {
  1213. foreach (var timer in timers)
  1214. {
  1215. if (_disposed)
  1216. {
  1217. return;
  1218. }
  1219. try
  1220. {
  1221. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1222. }
  1223. catch (Exception ex)
  1224. {
  1225. _logger.ErrorException("Error deleting recording", ex);
  1226. }
  1227. }
  1228. }
  1229. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1230. {
  1231. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1232. if (libraryItem != null)
  1233. {
  1234. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1235. {
  1236. DeleteFileLocation = true
  1237. });
  1238. }
  1239. else
  1240. {
  1241. try
  1242. {
  1243. _fileSystem.DeleteFile(timer.RecordingPath);
  1244. }
  1245. catch (IOException)
  1246. {
  1247. }
  1248. }
  1249. _timerProvider.Delete(timer);
  1250. }
  1251. private string EnsureFileUnique(string path, string timerId)
  1252. {
  1253. var originalPath = path;
  1254. var index = 1;
  1255. while (FileExists(path, timerId))
  1256. {
  1257. var parent = Path.GetDirectoryName(originalPath);
  1258. var name = Path.GetFileNameWithoutExtension(originalPath);
  1259. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1260. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1261. index++;
  1262. }
  1263. return path;
  1264. }
  1265. private bool FileExists(string path, string timerId)
  1266. {
  1267. if (_fileSystem.FileExists(path))
  1268. {
  1269. return true;
  1270. }
  1271. var hasRecordingAtPath = _activeRecordings
  1272. .Values
  1273. .ToList()
  1274. .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1275. if (hasRecordingAtPath)
  1276. {
  1277. return true;
  1278. }
  1279. return false;
  1280. }
  1281. private async Task<IRecorder> GetRecorder()
  1282. {
  1283. var config = GetConfiguration();
  1284. if (config.EnableRecordingEncoding)
  1285. {
  1286. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1287. if (regInfo.IsValid)
  1288. {
  1289. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient, _processFactory);
  1290. }
  1291. }
  1292. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1293. }
  1294. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1295. {
  1296. //if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1297. //{
  1298. // try
  1299. // {
  1300. // // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1301. // // ideally this shouldn't be hard-coded
  1302. // await Task.Delay(30000).ConfigureAwait(false);
  1303. // var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1304. // var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1305. // if (result.Status == FileSortingStatus.Success)
  1306. // {
  1307. // return;
  1308. // }
  1309. // }
  1310. // catch (Exception ex)
  1311. // {
  1312. // _logger.ErrorException("Error processing new recording", ex);
  1313. // }
  1314. //}
  1315. PostProcessRecording(timer, path);
  1316. }
  1317. private void PostProcessRecording(TimerInfo timer, string path)
  1318. {
  1319. var options = GetConfiguration();
  1320. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1321. {
  1322. return;
  1323. }
  1324. try
  1325. {
  1326. var process = _processFactory.Create(new ProcessOptions
  1327. {
  1328. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1329. CreateNoWindow = true,
  1330. EnableRaisingEvents = true,
  1331. ErrorDialog = false,
  1332. FileName = options.RecordingPostProcessor,
  1333. IsHidden = true,
  1334. UseShellExecute = false
  1335. });
  1336. _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1337. process.Exited += Process_Exited;
  1338. process.Start();
  1339. }
  1340. catch (Exception ex)
  1341. {
  1342. _logger.ErrorException("Error running recording post processor", ex);
  1343. }
  1344. }
  1345. private string GetPostProcessArguments(string path, string arguments)
  1346. {
  1347. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1348. }
  1349. private void Process_Exited(object sender, EventArgs e)
  1350. {
  1351. var process = (IProcess)sender;
  1352. try
  1353. {
  1354. _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
  1355. }
  1356. catch
  1357. {
  1358. }
  1359. process.Dispose();
  1360. }
  1361. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1362. {
  1363. if (!image.IsLocalFile)
  1364. {
  1365. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1366. }
  1367. string imageSaveFilenameWithoutExtension = null;
  1368. switch (image.Type)
  1369. {
  1370. case ImageType.Primary:
  1371. if (program.IsSeries)
  1372. {
  1373. imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
  1374. }
  1375. else
  1376. {
  1377. imageSaveFilenameWithoutExtension = "poster";
  1378. }
  1379. break;
  1380. case ImageType.Logo:
  1381. imageSaveFilenameWithoutExtension = "logo";
  1382. break;
  1383. case ImageType.Thumb:
  1384. imageSaveFilenameWithoutExtension = "landscape";
  1385. break;
  1386. case ImageType.Backdrop:
  1387. imageSaveFilenameWithoutExtension = "fanart";
  1388. break;
  1389. default:
  1390. break;
  1391. }
  1392. if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
  1393. {
  1394. return;
  1395. }
  1396. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1397. // preserve original image extension
  1398. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1399. _fileSystem.CopyFile(image.Path, imageSavePath, true);
  1400. }
  1401. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1402. {
  1403. var image = program.GetImageInfo(ImageType.Primary, 0);
  1404. if (image != null && program.IsMovie)
  1405. {
  1406. try
  1407. {
  1408. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1409. }
  1410. catch (Exception ex)
  1411. {
  1412. _logger.ErrorException("Error saving recording image", ex);
  1413. }
  1414. }
  1415. if (!program.IsSeries)
  1416. {
  1417. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1418. if (image != null)
  1419. {
  1420. try
  1421. {
  1422. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1423. }
  1424. catch (Exception ex)
  1425. {
  1426. _logger.ErrorException("Error saving recording image", ex);
  1427. }
  1428. }
  1429. image = program.GetImageInfo(ImageType.Thumb, 0);
  1430. if (image != null)
  1431. {
  1432. try
  1433. {
  1434. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1435. }
  1436. catch (Exception ex)
  1437. {
  1438. _logger.ErrorException("Error saving recording image", ex);
  1439. }
  1440. }
  1441. image = program.GetImageInfo(ImageType.Logo, 0);
  1442. if (image != null)
  1443. {
  1444. try
  1445. {
  1446. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1447. }
  1448. catch (Exception ex)
  1449. {
  1450. _logger.ErrorException("Error saving recording image", ex);
  1451. }
  1452. }
  1453. }
  1454. }
  1455. private async void SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1456. {
  1457. try
  1458. {
  1459. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1460. {
  1461. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1462. Limit = 1,
  1463. ExternalId = timer.ProgramId
  1464. }).FirstOrDefault() as LiveTvProgram;
  1465. // dummy this up
  1466. if (program == null)
  1467. {
  1468. program = new LiveTvProgram
  1469. {
  1470. Name = timer.Name,
  1471. HomePageUrl = timer.HomePageUrl,
  1472. ShortOverview = timer.ShortOverview,
  1473. Overview = timer.Overview,
  1474. Genres = timer.Genres,
  1475. CommunityRating = timer.CommunityRating,
  1476. OfficialRating = timer.OfficialRating,
  1477. ProductionYear = timer.ProductionYear,
  1478. PremiereDate = timer.OriginalAirDate,
  1479. IndexNumber = timer.EpisodeNumber,
  1480. ParentIndexNumber = timer.SeasonNumber
  1481. };
  1482. }
  1483. if (timer.IsSports)
  1484. {
  1485. AddGenre(program.Genres, "Sports");
  1486. }
  1487. if (timer.IsKids)
  1488. {
  1489. AddGenre(program.Genres, "Kids");
  1490. AddGenre(program.Genres, "Children");
  1491. }
  1492. if (timer.IsNews)
  1493. {
  1494. AddGenre(program.Genres, "News");
  1495. }
  1496. if (timer.IsProgramSeries)
  1497. {
  1498. SaveSeriesNfo(timer, seriesPath);
  1499. SaveVideoNfo(timer, recordingPath, program, false);
  1500. }
  1501. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1502. {
  1503. SaveVideoNfo(timer, recordingPath, program, true);
  1504. }
  1505. else
  1506. {
  1507. SaveVideoNfo(timer, recordingPath, program, false);
  1508. }
  1509. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1510. }
  1511. catch (Exception ex)
  1512. {
  1513. _logger.ErrorException("Error saving nfo", ex);
  1514. }
  1515. }
  1516. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1517. {
  1518. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1519. if (_fileSystem.FileExists(nfoPath))
  1520. {
  1521. return;
  1522. }
  1523. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1524. {
  1525. var settings = new XmlWriterSettings
  1526. {
  1527. Indent = true,
  1528. Encoding = Encoding.UTF8,
  1529. CloseOutput = false
  1530. };
  1531. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1532. {
  1533. writer.WriteStartDocument(true);
  1534. writer.WriteStartElement("tvshow");
  1535. if (!string.IsNullOrWhiteSpace(timer.Name))
  1536. {
  1537. writer.WriteElementString("title", timer.Name);
  1538. }
  1539. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1540. {
  1541. writer.WriteElementString("mpaa", timer.OfficialRating);
  1542. }
  1543. foreach (var genre in timer.Genres)
  1544. {
  1545. writer.WriteElementString("genre", genre);
  1546. }
  1547. writer.WriteEndElement();
  1548. writer.WriteEndDocument();
  1549. }
  1550. }
  1551. }
  1552. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1553. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1554. {
  1555. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1556. if (_fileSystem.FileExists(nfoPath))
  1557. {
  1558. return;
  1559. }
  1560. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1561. {
  1562. var settings = new XmlWriterSettings
  1563. {
  1564. Indent = true,
  1565. Encoding = Encoding.UTF8,
  1566. CloseOutput = false
  1567. };
  1568. var options = _config.GetNfoConfiguration();
  1569. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1570. {
  1571. writer.WriteStartDocument(true);
  1572. if (timer.IsProgramSeries)
  1573. {
  1574. writer.WriteStartElement("episodedetails");
  1575. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1576. {
  1577. writer.WriteElementString("title", timer.EpisodeTitle);
  1578. }
  1579. if (item.PremiereDate.HasValue)
  1580. {
  1581. var formatString = options.ReleaseDateFormat;
  1582. writer.WriteElementString("aired", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1583. }
  1584. if (item.IndexNumber.HasValue)
  1585. {
  1586. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1587. }
  1588. if (item.ParentIndexNumber.HasValue)
  1589. {
  1590. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1591. }
  1592. }
  1593. else
  1594. {
  1595. writer.WriteStartElement("movie");
  1596. if (!string.IsNullOrWhiteSpace(item.Name))
  1597. {
  1598. writer.WriteElementString("title", item.Name);
  1599. }
  1600. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1601. {
  1602. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1603. }
  1604. if (item.PremiereDate.HasValue)
  1605. {
  1606. var formatString = options.ReleaseDateFormat;
  1607. writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1608. writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1609. }
  1610. }
  1611. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1612. if (item.ProductionYear.HasValue)
  1613. {
  1614. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1615. }
  1616. if (!string.IsNullOrEmpty(item.OfficialRating))
  1617. {
  1618. writer.WriteElementString("mpaa", item.OfficialRating);
  1619. }
  1620. if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
  1621. {
  1622. writer.WriteElementString("mpaadescription", item.OfficialRatingDescription);
  1623. }
  1624. var overview = (item.Overview ?? string.Empty)
  1625. .StripHtml()
  1626. .Replace("&quot;", "'");
  1627. writer.WriteElementString("plot", overview);
  1628. if (lockData)
  1629. {
  1630. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1631. }
  1632. if (item.CommunityRating.HasValue)
  1633. {
  1634. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1635. }
  1636. foreach (var genre in item.Genres)
  1637. {
  1638. writer.WriteElementString("genre", genre);
  1639. }
  1640. if (!string.IsNullOrWhiteSpace(item.ShortOverview))
  1641. {
  1642. writer.WriteElementString("outline", item.ShortOverview);
  1643. }
  1644. if (!string.IsNullOrWhiteSpace(item.HomePageUrl))
  1645. {
  1646. writer.WriteElementString("website", item.HomePageUrl);
  1647. }
  1648. var people = item.Id == Guid.Empty ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1649. var directors = people
  1650. .Where(i => IsPersonType(i, PersonType.Director))
  1651. .Select(i => i.Name)
  1652. .ToList();
  1653. foreach (var person in directors)
  1654. {
  1655. writer.WriteElementString("director", person);
  1656. }
  1657. var writers = people
  1658. .Where(i => IsPersonType(i, PersonType.Writer))
  1659. .Select(i => i.Name)
  1660. .Distinct(StringComparer.OrdinalIgnoreCase)
  1661. .ToList();
  1662. foreach (var person in writers)
  1663. {
  1664. writer.WriteElementString("writer", person);
  1665. }
  1666. foreach (var person in writers)
  1667. {
  1668. writer.WriteElementString("credits", person);
  1669. }
  1670. var rt = item.GetProviderId(MetadataProviders.RottenTomatoes);
  1671. if (!string.IsNullOrEmpty(rt))
  1672. {
  1673. writer.WriteElementString("rottentomatoesid", rt);
  1674. }
  1675. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  1676. if (!string.IsNullOrEmpty(tmdbCollection))
  1677. {
  1678. writer.WriteElementString("collectionnumber", tmdbCollection);
  1679. }
  1680. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  1681. if (!string.IsNullOrEmpty(imdb))
  1682. {
  1683. if (item is Series)
  1684. {
  1685. writer.WriteElementString("imdb_id", imdb);
  1686. }
  1687. else
  1688. {
  1689. writer.WriteElementString("imdbid", imdb);
  1690. }
  1691. }
  1692. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  1693. if (!string.IsNullOrEmpty(tvdb))
  1694. {
  1695. writer.WriteElementString("tvdbid", tvdb);
  1696. }
  1697. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  1698. if (!string.IsNullOrEmpty(tmdb))
  1699. {
  1700. writer.WriteElementString("tmdbid", tmdb);
  1701. }
  1702. if (item.CriticRating.HasValue)
  1703. {
  1704. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1705. }
  1706. if (!string.IsNullOrEmpty(item.CriticRatingSummary))
  1707. {
  1708. writer.WriteElementString("criticratingsummary", item.CriticRatingSummary);
  1709. }
  1710. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1711. {
  1712. writer.WriteElementString("tagline", item.Tagline);
  1713. }
  1714. foreach (var studio in item.Studios)
  1715. {
  1716. writer.WriteElementString("studio", studio);
  1717. }
  1718. if (item.VoteCount.HasValue)
  1719. {
  1720. writer.WriteElementString("votes", item.VoteCount.Value.ToString(CultureInfo.InvariantCulture));
  1721. }
  1722. writer.WriteEndElement();
  1723. writer.WriteEndDocument();
  1724. }
  1725. }
  1726. }
  1727. private static bool IsPersonType(PersonInfo person, string type)
  1728. {
  1729. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1730. }
  1731. private void AddGenre(List<string> genres, string genre)
  1732. {
  1733. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1734. {
  1735. genres.Add(genre);
  1736. }
  1737. }
  1738. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1739. {
  1740. var epgData = GetEpgDataForChannel(channelId);
  1741. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1742. }
  1743. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1744. {
  1745. var epgData = GetEpgDataForChannel(channelId);
  1746. var startDateTicks = startDateUtc.Ticks;
  1747. // Find the first program that starts within 3 minutes
  1748. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1749. }
  1750. private LiveTvOptions GetConfiguration()
  1751. {
  1752. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1753. }
  1754. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1755. {
  1756. if (!seriesTimer.RecordAnyTime)
  1757. {
  1758. if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(5).Ticks)
  1759. {
  1760. return true;
  1761. }
  1762. }
  1763. //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
  1764. //{
  1765. // return true;
  1766. //}
  1767. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1768. {
  1769. return true;
  1770. }
  1771. if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1772. {
  1773. return true;
  1774. }
  1775. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1776. }
  1777. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1778. {
  1779. foreach (var timer in timers.Skip(1))
  1780. {
  1781. // TODO: Get smarter, prefer HD, etc
  1782. timer.Status = RecordingStatus.Cancelled;
  1783. _timerProvider.Update(timer);
  1784. }
  1785. }
  1786. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1787. {
  1788. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1789. foreach (var group in groups)
  1790. {
  1791. if (string.IsNullOrWhiteSpace(group.Key))
  1792. {
  1793. continue;
  1794. }
  1795. var groupTimers = group.ToList();
  1796. if (groupTimers.Count < 2)
  1797. {
  1798. continue;
  1799. }
  1800. HandleDuplicateShowIds(groupTimers);
  1801. }
  1802. }
  1803. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1804. {
  1805. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1806. .ToList();
  1807. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1808. var enabledTimersForSeries = new List<TimerInfo>();
  1809. if (registration.IsValid)
  1810. {
  1811. foreach (var timer in allTimers)
  1812. {
  1813. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1814. if (existingTimer == null)
  1815. {
  1816. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1817. {
  1818. timer.Status = RecordingStatus.Cancelled;
  1819. }
  1820. else
  1821. {
  1822. enabledTimersForSeries.Add(timer);
  1823. }
  1824. _timerProvider.Add(timer);
  1825. }
  1826. else
  1827. {
  1828. // Only update if not currently active
  1829. ActiveRecordingInfo activeRecordingInfo;
  1830. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
  1831. {
  1832. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1833. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1834. {
  1835. existingTimer.Status = RecordingStatus.Cancelled;
  1836. }
  1837. if (existingTimer.Status != RecordingStatus.Cancelled)
  1838. {
  1839. enabledTimersForSeries.Add(existingTimer);
  1840. }
  1841. if (updateTimerSettings)
  1842. {
  1843. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1844. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1845. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1846. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1847. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1848. existingTimer.Priority = seriesTimer.Priority;
  1849. }
  1850. existingTimer.SeriesTimerId = seriesTimer.Id;
  1851. _timerProvider.Update(existingTimer);
  1852. }
  1853. }
  1854. }
  1855. }
  1856. SearchForDuplicateShowIds(enabledTimersForSeries);
  1857. if (deleteInvalidTimers)
  1858. {
  1859. var allTimerIds = allTimers
  1860. .Select(i => i.Id)
  1861. .ToList();
  1862. var deleteStatuses = new List<RecordingStatus>
  1863. {
  1864. RecordingStatus.New
  1865. };
  1866. var deletes = _timerProvider.GetAll()
  1867. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1868. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1869. .Where(i => deleteStatuses.Contains(i.Status))
  1870. .ToList();
  1871. foreach (var timer in deletes)
  1872. {
  1873. CancelTimerInternal(timer.Id, false);
  1874. }
  1875. }
  1876. }
  1877. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1878. {
  1879. if (seriesTimer == null)
  1880. {
  1881. throw new ArgumentNullException("seriesTimer");
  1882. }
  1883. if (allPrograms == null)
  1884. {
  1885. throw new ArgumentNullException("allPrograms");
  1886. }
  1887. // Exclude programs that have already ended
  1888. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  1889. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  1890. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  1891. }
  1892. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  1893. {
  1894. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1895. {
  1896. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  1897. {
  1898. IncludeItemTypes = new[] { typeof(Series).Name },
  1899. Name = program.Name
  1900. }).Select(i => i.ToString("N")).ToArray();
  1901. if (seriesIds.Length == 0)
  1902. {
  1903. return false;
  1904. }
  1905. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  1906. {
  1907. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1908. {
  1909. IncludeItemTypes = new[] { typeof(Episode).Name },
  1910. ParentIndexNumber = program.SeasonNumber.Value,
  1911. IndexNumber = program.EpisodeNumber.Value,
  1912. AncestorIds = seriesIds,
  1913. IsVirtualItem = false
  1914. });
  1915. if (result.TotalRecordCount > 0)
  1916. {
  1917. return true;
  1918. }
  1919. }
  1920. }
  1921. return false;
  1922. }
  1923. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1924. {
  1925. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  1926. {
  1927. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  1928. return new List<ProgramInfo>();
  1929. }
  1930. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1931. }
  1932. private string GetChannelEpgCachePath(string channelId)
  1933. {
  1934. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1935. }
  1936. private readonly object _epgLock = new object();
  1937. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1938. {
  1939. var path = GetChannelEpgCachePath(channelId);
  1940. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1941. lock (_epgLock)
  1942. {
  1943. _jsonSerializer.SerializeToFile(epgData, path);
  1944. }
  1945. }
  1946. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1947. {
  1948. try
  1949. {
  1950. lock (_epgLock)
  1951. {
  1952. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1953. }
  1954. }
  1955. catch
  1956. {
  1957. return new List<ProgramInfo>();
  1958. }
  1959. }
  1960. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1961. {
  1962. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1963. }
  1964. private bool _disposed;
  1965. public void Dispose()
  1966. {
  1967. _disposed = true;
  1968. foreach (var pair in _activeRecordings.ToList())
  1969. {
  1970. pair.Value.CancellationTokenSource.Cancel();
  1971. }
  1972. }
  1973. public List<VirtualFolderInfo> GetRecordingFolders()
  1974. {
  1975. var list = new List<VirtualFolderInfo>();
  1976. var defaultFolder = RecordingPath;
  1977. var defaultName = "Recordings";
  1978. if (_fileSystem.DirectoryExists(defaultFolder))
  1979. {
  1980. list.Add(new VirtualFolderInfo
  1981. {
  1982. Locations = new List<string> { defaultFolder },
  1983. Name = defaultName
  1984. });
  1985. }
  1986. var customPath = GetConfiguration().MovieRecordingPath;
  1987. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  1988. {
  1989. list.Add(new VirtualFolderInfo
  1990. {
  1991. Locations = new List<string> { customPath },
  1992. Name = "Recorded Movies",
  1993. CollectionType = CollectionType.Movies
  1994. });
  1995. }
  1996. customPath = GetConfiguration().SeriesRecordingPath;
  1997. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  1998. {
  1999. list.Add(new VirtualFolderInfo
  2000. {
  2001. Locations = new List<string> { customPath },
  2002. Name = "Recorded Series",
  2003. CollectionType = CollectionType.TvShows
  2004. });
  2005. }
  2006. return list;
  2007. }
  2008. class ActiveRecordingInfo
  2009. {
  2010. public string Path { get; set; }
  2011. public TimerInfo Timer { get; set; }
  2012. public ProgramInfo Program { get; set; }
  2013. public CancellationTokenSource CancellationTokenSource { get; set; }
  2014. }
  2015. }
  2016. public static class ConfigurationExtension
  2017. {
  2018. public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
  2019. {
  2020. return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  2021. }
  2022. }
  2023. }