EmbyTV.cs 106 KB

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