EmbyTV.cs 101 KB

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