EmbyTV.cs 103 KB

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