EmbyTV.cs 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829
  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. private async Task<Tuple<ILiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  877. {
  878. _logger.Info("Streaming Channel " + channelId);
  879. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  880. try
  881. {
  882. var result = _liveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  883. if (result != null && result.EnableStreamSharing)
  884. {
  885. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  886. result.SharedStreamIds.Add(openedMediaSource.Id);
  887. _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  888. return new Tuple<ILiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, result.TunerHost);
  889. }
  890. foreach (var hostInstance in _liveTvManager.TunerHosts)
  891. {
  892. try
  893. {
  894. result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  895. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  896. result.SharedStreamIds.Add(openedMediaSource.Id);
  897. _liveStreams.Add(result);
  898. result.TunerHost = hostInstance;
  899. result.OriginalStreamId = streamId;
  900. _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
  901. streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  902. return new Tuple<ILiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, hostInstance);
  903. }
  904. catch (FileNotFoundException)
  905. {
  906. }
  907. catch (OperationCanceledException)
  908. {
  909. }
  910. }
  911. }
  912. finally
  913. {
  914. _liveStreamsSemaphore.Release();
  915. }
  916. throw new Exception("Tuner not found.");
  917. }
  918. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  919. {
  920. if (string.IsNullOrWhiteSpace(channelId))
  921. {
  922. throw new ArgumentNullException("channelId");
  923. }
  924. foreach (var hostInstance in _liveTvManager.TunerHosts)
  925. {
  926. try
  927. {
  928. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  929. if (sources.Count > 0)
  930. {
  931. return sources;
  932. }
  933. }
  934. catch (NotImplementedException)
  935. {
  936. }
  937. }
  938. throw new NotImplementedException();
  939. }
  940. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  941. {
  942. ActiveRecordingInfo info;
  943. recordingId = recordingId.Replace("recording", string.Empty);
  944. if (_activeRecordings.TryGetValue(recordingId, out info))
  945. {
  946. var stream = new MediaSourceInfo
  947. {
  948. Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + recordingId + "/stream",
  949. Id = recordingId,
  950. SupportsDirectPlay = false,
  951. SupportsDirectStream = true,
  952. SupportsTranscoding = true,
  953. IsInfiniteStream = true,
  954. RequiresOpening = false,
  955. RequiresClosing = false,
  956. Protocol = MediaBrowser.Model.MediaInfo.MediaProtocol.Http,
  957. BufferMs = 0,
  958. IgnoreDts = true,
  959. IgnoreIndex = true
  960. };
  961. var isAudio = false;
  962. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  963. return new List<MediaSourceInfo>
  964. {
  965. stream
  966. };
  967. }
  968. throw new FileNotFoundException();
  969. }
  970. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, CancellationToken cancellationToken)
  971. {
  972. var stream = new MediaSourceInfo
  973. {
  974. Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
  975. Id = info.Id,
  976. SupportsDirectPlay = false,
  977. SupportsDirectStream = true,
  978. SupportsTranscoding = true,
  979. IsInfiniteStream = true,
  980. RequiresOpening = false,
  981. RequiresClosing = false,
  982. Protocol = MediaBrowser.Model.MediaInfo.MediaProtocol.Http,
  983. BufferMs = 0,
  984. IgnoreDts = true,
  985. IgnoreIndex = true
  986. };
  987. var isAudio = false;
  988. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  989. return new List<MediaSourceInfo>
  990. {
  991. stream
  992. };
  993. }
  994. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  995. {
  996. // Ignore the consumer id
  997. //id = id.Substring(id.IndexOf('_') + 1);
  998. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  999. try
  1000. {
  1001. var stream = _liveStreams.FirstOrDefault(i => i.SharedStreamIds.Contains(id));
  1002. if (stream != null)
  1003. {
  1004. stream.SharedStreamIds.Remove(id);
  1005. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  1006. if (stream.ConsumerCount <= 0)
  1007. {
  1008. _liveStreams.Remove(stream);
  1009. _logger.Info("Closing live stream {0}", id);
  1010. stream.Close();
  1011. _logger.Info("Live stream {0} closed successfully", id);
  1012. }
  1013. }
  1014. else
  1015. {
  1016. _logger.Warn("Live stream not found: {0}, unable to close", id);
  1017. }
  1018. }
  1019. catch (OperationCanceledException)
  1020. {
  1021. }
  1022. catch (Exception ex)
  1023. {
  1024. _logger.ErrorException("Error closing live stream", ex);
  1025. }
  1026. finally
  1027. {
  1028. _liveStreamsSemaphore.Release();
  1029. }
  1030. }
  1031. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  1032. {
  1033. return Task.FromResult(0);
  1034. }
  1035. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1036. {
  1037. return Task.FromResult(0);
  1038. }
  1039. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  1040. {
  1041. var timer = e.Argument;
  1042. _logger.Info("Recording timer fired.");
  1043. try
  1044. {
  1045. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  1046. if (recordingEndDate <= DateTime.UtcNow)
  1047. {
  1048. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  1049. OnTimerOutOfDate(timer);
  1050. return;
  1051. }
  1052. var registration = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false);
  1053. if (!registration.IsValid)
  1054. {
  1055. _logger.Warn("Emby Premiere required to use Emby DVR.");
  1056. OnTimerOutOfDate(timer);
  1057. return;
  1058. }
  1059. var activeRecordingInfo = new ActiveRecordingInfo
  1060. {
  1061. CancellationTokenSource = new CancellationTokenSource(),
  1062. Timer = timer,
  1063. Id = timer.Id
  1064. };
  1065. if (!_activeRecordings.ContainsKey(timer.Id))
  1066. {
  1067. await RecordStream(timer, recordingEndDate, activeRecordingInfo).ConfigureAwait(false);
  1068. }
  1069. else
  1070. {
  1071. _logger.Info("Skipping RecordStream because it's already in progress.");
  1072. }
  1073. }
  1074. catch (OperationCanceledException)
  1075. {
  1076. }
  1077. catch (Exception ex)
  1078. {
  1079. _logger.ErrorException("Error recording stream", ex);
  1080. }
  1081. }
  1082. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  1083. {
  1084. var recordPath = RecordingPath;
  1085. var config = GetConfiguration();
  1086. seriesPath = null;
  1087. if (timer.IsProgramSeries)
  1088. {
  1089. var customRecordingPath = config.SeriesRecordingPath;
  1090. var allowSubfolder = true;
  1091. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1092. {
  1093. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1094. recordPath = customRecordingPath;
  1095. }
  1096. if (allowSubfolder && config.EnableRecordingSubfolders)
  1097. {
  1098. recordPath = Path.Combine(recordPath, "Series");
  1099. }
  1100. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1101. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  1102. recordPath = Path.Combine(recordPath, folderName);
  1103. seriesPath = recordPath;
  1104. if (timer.SeasonNumber.HasValue)
  1105. {
  1106. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  1107. recordPath = Path.Combine(recordPath, folderName);
  1108. }
  1109. }
  1110. else if (timer.IsMovie)
  1111. {
  1112. var customRecordingPath = config.MovieRecordingPath;
  1113. var allowSubfolder = true;
  1114. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1115. {
  1116. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1117. recordPath = customRecordingPath;
  1118. }
  1119. if (allowSubfolder && config.EnableRecordingSubfolders)
  1120. {
  1121. recordPath = Path.Combine(recordPath, "Movies");
  1122. }
  1123. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1124. if (timer.ProductionYear.HasValue)
  1125. {
  1126. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1127. }
  1128. recordPath = Path.Combine(recordPath, folderName);
  1129. }
  1130. else if (timer.IsKids)
  1131. {
  1132. if (config.EnableRecordingSubfolders)
  1133. {
  1134. recordPath = Path.Combine(recordPath, "Kids");
  1135. }
  1136. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1137. if (timer.ProductionYear.HasValue)
  1138. {
  1139. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1140. }
  1141. recordPath = Path.Combine(recordPath, folderName);
  1142. }
  1143. else if (timer.IsSports)
  1144. {
  1145. if (config.EnableRecordingSubfolders)
  1146. {
  1147. recordPath = Path.Combine(recordPath, "Sports");
  1148. }
  1149. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1150. }
  1151. else
  1152. {
  1153. if (config.EnableRecordingSubfolders)
  1154. {
  1155. recordPath = Path.Combine(recordPath, "Other");
  1156. }
  1157. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1158. }
  1159. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1160. return Path.Combine(recordPath, recordingFileName);
  1161. }
  1162. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo)
  1163. {
  1164. if (timer == null)
  1165. {
  1166. throw new ArgumentNullException("timer");
  1167. }
  1168. LiveTvProgram programInfo = null;
  1169. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1170. {
  1171. programInfo = GetProgramInfoFromCache(timer);
  1172. }
  1173. if (programInfo == null)
  1174. {
  1175. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1176. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1177. }
  1178. if (programInfo != null)
  1179. {
  1180. CopyProgramInfoToTimerInfo(programInfo, timer);
  1181. }
  1182. string seriesPath = null;
  1183. var recordPath = GetRecordingPath(timer, out seriesPath);
  1184. var recordingStatus = RecordingStatus.New;
  1185. var recorder = await GetRecorder().ConfigureAwait(false);
  1186. string liveStreamId = null;
  1187. try
  1188. {
  1189. var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  1190. _logger.Info("Opening recording stream from tuner provider");
  1191. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  1192. .ConfigureAwait(false);
  1193. var mediaStreamInfo = liveStreamInfo.Item2;
  1194. liveStreamId = mediaStreamInfo.Id;
  1195. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1196. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1197. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1198. var duration = recordingEndDate - DateTime.UtcNow;
  1199. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1200. _logger.Info("Writing file to path: " + recordPath);
  1201. Action onStarted = async () =>
  1202. {
  1203. activeRecordingInfo.Path = recordPath;
  1204. _activeRecordings.TryAdd(timer.Id, activeRecordingInfo);
  1205. timer.Status = RecordingStatus.InProgress;
  1206. _timerProvider.AddOrUpdate(timer, false);
  1207. await SaveRecordingMetadata(timer, recordPath, seriesPath).ConfigureAwait(false);
  1208. CreateRecordingFolders();
  1209. TriggerRefresh(recordPath);
  1210. EnforceKeepUpTo(timer, seriesPath);
  1211. };
  1212. await recorder.Record(liveStreamInfo.Item1 as IDirectStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  1213. recordingStatus = RecordingStatus.Completed;
  1214. _logger.Info("Recording completed: {0}", recordPath);
  1215. }
  1216. catch (OperationCanceledException)
  1217. {
  1218. _logger.Info("Recording stopped: {0}", recordPath);
  1219. recordingStatus = RecordingStatus.Completed;
  1220. }
  1221. catch (Exception ex)
  1222. {
  1223. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  1224. recordingStatus = RecordingStatus.Error;
  1225. }
  1226. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1227. {
  1228. try
  1229. {
  1230. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1231. }
  1232. catch (Exception ex)
  1233. {
  1234. _logger.ErrorException("Error closing live stream", ex);
  1235. }
  1236. }
  1237. TriggerRefresh(recordPath);
  1238. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  1239. ActiveRecordingInfo removed;
  1240. _activeRecordings.TryRemove(timer.Id, out removed);
  1241. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1242. {
  1243. const int retryIntervalSeconds = 60;
  1244. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1245. timer.Status = RecordingStatus.New;
  1246. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1247. timer.RetryCount++;
  1248. _timerProvider.AddOrUpdate(timer);
  1249. }
  1250. else if (_fileSystem.FileExists(recordPath))
  1251. {
  1252. timer.RecordingPath = recordPath;
  1253. timer.Status = RecordingStatus.Completed;
  1254. _timerProvider.AddOrUpdate(timer, false);
  1255. OnSuccessfulRecording(timer, recordPath);
  1256. }
  1257. else
  1258. {
  1259. _timerProvider.Delete(timer);
  1260. }
  1261. }
  1262. private void TriggerRefresh(string path)
  1263. {
  1264. _logger.Info("Triggering refresh on {0}", path);
  1265. var item = GetAffectedBaseItem(_fileSystem.GetDirectoryName(path));
  1266. if (item != null)
  1267. {
  1268. _logger.Info("Refreshing recording parent {0}", item.Path);
  1269. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1270. {
  1271. ValidateChildren = true,
  1272. RefreshPaths = new List<string>
  1273. {
  1274. path,
  1275. _fileSystem.GetDirectoryName(path),
  1276. _fileSystem.GetDirectoryName(_fileSystem.GetDirectoryName(path))
  1277. }
  1278. }, RefreshPriority.High);
  1279. }
  1280. }
  1281. private BaseItem GetAffectedBaseItem(string path)
  1282. {
  1283. BaseItem item = null;
  1284. var parentPath = _fileSystem.GetDirectoryName(path);
  1285. while (item == null && !string.IsNullOrEmpty(path))
  1286. {
  1287. item = _libraryManager.FindByPath(path, null);
  1288. path = _fileSystem.GetDirectoryName(path);
  1289. }
  1290. if (item != null)
  1291. {
  1292. if (item.GetType() == typeof(Folder) && string.Equals(item.Path, parentPath, StringComparison.OrdinalIgnoreCase))
  1293. {
  1294. var parentItem = item.GetParent();
  1295. if (parentItem != null && !(parentItem is AggregateFolder))
  1296. {
  1297. item = parentItem;
  1298. }
  1299. }
  1300. }
  1301. return item;
  1302. }
  1303. private async void EnforceKeepUpTo(TimerInfo timer, string seriesPath)
  1304. {
  1305. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1306. {
  1307. return;
  1308. }
  1309. if (string.IsNullOrWhiteSpace(seriesPath))
  1310. {
  1311. return;
  1312. }
  1313. var seriesTimerId = timer.SeriesTimerId;
  1314. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1315. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1316. {
  1317. return;
  1318. }
  1319. if (_disposed)
  1320. {
  1321. return;
  1322. }
  1323. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1324. try
  1325. {
  1326. if (_disposed)
  1327. {
  1328. return;
  1329. }
  1330. var timersToDelete = _timerProvider.GetAll()
  1331. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1332. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1333. .OrderByDescending(i => i.EndDate)
  1334. .Where(i => _fileSystem.FileExists(i.RecordingPath))
  1335. .Skip(seriesTimer.KeepUpTo - 1)
  1336. .ToList();
  1337. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1338. var librarySeries = _libraryManager.FindByPath(seriesPath, true) as Folder;
  1339. if (librarySeries == null)
  1340. {
  1341. return;
  1342. }
  1343. var episodesToDelete = (librarySeries.GetItemList(new InternalItemsQuery
  1344. {
  1345. OrderBy = new[] { new Tuple<string, SortOrder>(ItemSortBy.DateCreated, SortOrder.Descending) },
  1346. IsVirtualItem = false,
  1347. IsFolder = false,
  1348. Recursive = true,
  1349. DtoOptions = new DtoOptions(true)
  1350. }))
  1351. .Where(i => i.LocationType == LocationType.FileSystem && _fileSystem.FileExists(i.Path))
  1352. .Skip(seriesTimer.KeepUpTo - 1)
  1353. .ToList();
  1354. foreach (var item in episodesToDelete)
  1355. {
  1356. try
  1357. {
  1358. await _libraryManager.DeleteItem(item, new DeleteOptions
  1359. {
  1360. DeleteFileLocation = true
  1361. }).ConfigureAwait(false);
  1362. }
  1363. catch (Exception ex)
  1364. {
  1365. _logger.ErrorException("Error deleting item", ex);
  1366. }
  1367. }
  1368. }
  1369. finally
  1370. {
  1371. _recordingDeleteSemaphore.Release();
  1372. }
  1373. }
  1374. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1375. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1376. {
  1377. foreach (var timer in timers)
  1378. {
  1379. if (_disposed)
  1380. {
  1381. return;
  1382. }
  1383. try
  1384. {
  1385. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1386. }
  1387. catch (Exception ex)
  1388. {
  1389. _logger.ErrorException("Error deleting recording", ex);
  1390. }
  1391. }
  1392. }
  1393. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1394. {
  1395. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1396. if (libraryItem != null)
  1397. {
  1398. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1399. {
  1400. DeleteFileLocation = true
  1401. }).ConfigureAwait(false);
  1402. }
  1403. else
  1404. {
  1405. try
  1406. {
  1407. _fileSystem.DeleteFile(timer.RecordingPath);
  1408. }
  1409. catch (IOException)
  1410. {
  1411. }
  1412. }
  1413. _timerProvider.Delete(timer);
  1414. }
  1415. private string EnsureFileUnique(string path, string timerId)
  1416. {
  1417. var originalPath = path;
  1418. var index = 1;
  1419. while (FileExists(path, timerId))
  1420. {
  1421. var parent = _fileSystem.GetDirectoryName(originalPath);
  1422. var name = Path.GetFileNameWithoutExtension(originalPath);
  1423. name += " - " + index.ToString(CultureInfo.InvariantCulture);
  1424. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1425. index++;
  1426. }
  1427. return path;
  1428. }
  1429. private bool FileExists(string path, string timerId)
  1430. {
  1431. if (_fileSystem.FileExists(path))
  1432. {
  1433. return true;
  1434. }
  1435. var hasRecordingAtPath = _activeRecordings
  1436. .Values
  1437. .ToList()
  1438. .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1439. if (hasRecordingAtPath)
  1440. {
  1441. return true;
  1442. }
  1443. return false;
  1444. }
  1445. private async Task<IRecorder> GetRecorder()
  1446. {
  1447. var config = GetConfiguration();
  1448. var regInfo = await _liveTvManager.GetRegistrationInfo("dvr").ConfigureAwait(false);
  1449. if (regInfo.IsValid)
  1450. {
  1451. if (config.EnableRecordingEncoding)
  1452. {
  1453. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient, _processFactory, _config);
  1454. }
  1455. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1456. //var options = new LiveTvOptions
  1457. //{
  1458. // EnableOriginalAudioWithEncodedRecordings = true,
  1459. // RecordedVideoCodec = "copy",
  1460. // RecordingEncodingFormat = "ts"
  1461. //};
  1462. //return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, options, _httpClient, _processFactory, _config);
  1463. }
  1464. throw new InvalidOperationException("Emby DVR Requires an active Emby Premiere subscription.");
  1465. }
  1466. private void OnSuccessfulRecording(TimerInfo timer, string path)
  1467. {
  1468. //if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1469. //{
  1470. // try
  1471. // {
  1472. // // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1473. // // ideally this shouldn't be hard-coded
  1474. // await Task.Delay(30000).ConfigureAwait(false);
  1475. // var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1476. // var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1477. // if (result.Status == FileSortingStatus.Success)
  1478. // {
  1479. // return;
  1480. // }
  1481. // }
  1482. // catch (Exception ex)
  1483. // {
  1484. // _logger.ErrorException("Error processing new recording", ex);
  1485. // }
  1486. //}
  1487. PostProcessRecording(timer, path);
  1488. }
  1489. private void PostProcessRecording(TimerInfo timer, string path)
  1490. {
  1491. var options = GetConfiguration();
  1492. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1493. {
  1494. return;
  1495. }
  1496. try
  1497. {
  1498. var process = _processFactory.Create(new ProcessOptions
  1499. {
  1500. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1501. CreateNoWindow = true,
  1502. EnableRaisingEvents = true,
  1503. ErrorDialog = false,
  1504. FileName = options.RecordingPostProcessor,
  1505. IsHidden = true,
  1506. UseShellExecute = false
  1507. });
  1508. _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1509. process.Exited += Process_Exited;
  1510. process.Start();
  1511. }
  1512. catch (Exception ex)
  1513. {
  1514. _logger.ErrorException("Error running recording post processor", ex);
  1515. }
  1516. }
  1517. private string GetPostProcessArguments(string path, string arguments)
  1518. {
  1519. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1520. }
  1521. private void Process_Exited(object sender, EventArgs e)
  1522. {
  1523. var process = (IProcess)sender;
  1524. try
  1525. {
  1526. _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
  1527. }
  1528. catch
  1529. {
  1530. }
  1531. process.Dispose();
  1532. }
  1533. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1534. {
  1535. if (!image.IsLocalFile)
  1536. {
  1537. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1538. }
  1539. string imageSaveFilenameWithoutExtension = null;
  1540. switch (image.Type)
  1541. {
  1542. case ImageType.Primary:
  1543. if (program.IsSeries)
  1544. {
  1545. imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
  1546. }
  1547. else
  1548. {
  1549. imageSaveFilenameWithoutExtension = "poster";
  1550. }
  1551. break;
  1552. case ImageType.Logo:
  1553. imageSaveFilenameWithoutExtension = "logo";
  1554. break;
  1555. case ImageType.Thumb:
  1556. imageSaveFilenameWithoutExtension = "landscape";
  1557. break;
  1558. case ImageType.Backdrop:
  1559. imageSaveFilenameWithoutExtension = "fanart";
  1560. break;
  1561. default:
  1562. break;
  1563. }
  1564. if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
  1565. {
  1566. return;
  1567. }
  1568. var imageSavePath = Path.Combine(_fileSystem.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1569. // preserve original image extension
  1570. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1571. _fileSystem.CopyFile(image.Path, imageSavePath, true);
  1572. }
  1573. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1574. {
  1575. var image = program.GetImageInfo(ImageType.Primary, 0);
  1576. if (image != null && program.IsMovie)
  1577. {
  1578. try
  1579. {
  1580. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1581. }
  1582. catch (Exception ex)
  1583. {
  1584. _logger.ErrorException("Error saving recording image", ex);
  1585. }
  1586. }
  1587. if (!program.IsSeries)
  1588. {
  1589. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1590. if (image != null)
  1591. {
  1592. try
  1593. {
  1594. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1595. }
  1596. catch (Exception ex)
  1597. {
  1598. _logger.ErrorException("Error saving recording image", ex);
  1599. }
  1600. }
  1601. image = program.GetImageInfo(ImageType.Thumb, 0);
  1602. if (image != null)
  1603. {
  1604. try
  1605. {
  1606. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1607. }
  1608. catch (Exception ex)
  1609. {
  1610. _logger.ErrorException("Error saving recording image", ex);
  1611. }
  1612. }
  1613. image = program.GetImageInfo(ImageType.Logo, 0);
  1614. if (image != null)
  1615. {
  1616. try
  1617. {
  1618. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1619. }
  1620. catch (Exception ex)
  1621. {
  1622. _logger.ErrorException("Error saving recording image", ex);
  1623. }
  1624. }
  1625. }
  1626. }
  1627. private async Task SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1628. {
  1629. try
  1630. {
  1631. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1632. {
  1633. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1634. Limit = 1,
  1635. ExternalId = timer.ProgramId,
  1636. DtoOptions = new DtoOptions(true)
  1637. }).FirstOrDefault() as LiveTvProgram;
  1638. // dummy this up
  1639. if (program == null)
  1640. {
  1641. program = new LiveTvProgram
  1642. {
  1643. Name = timer.Name,
  1644. HomePageUrl = timer.HomePageUrl,
  1645. Overview = timer.Overview,
  1646. Genres = timer.Genres,
  1647. CommunityRating = timer.CommunityRating,
  1648. OfficialRating = timer.OfficialRating,
  1649. ProductionYear = timer.ProductionYear,
  1650. PremiereDate = timer.OriginalAirDate,
  1651. IndexNumber = timer.EpisodeNumber,
  1652. ParentIndexNumber = timer.SeasonNumber
  1653. };
  1654. }
  1655. if (timer.IsSports)
  1656. {
  1657. AddGenre(program.Genres, "Sports");
  1658. }
  1659. if (timer.IsKids)
  1660. {
  1661. AddGenre(program.Genres, "Kids");
  1662. AddGenre(program.Genres, "Children");
  1663. }
  1664. if (timer.IsNews)
  1665. {
  1666. AddGenre(program.Genres, "News");
  1667. }
  1668. if (timer.IsProgramSeries)
  1669. {
  1670. SaveSeriesNfo(timer, seriesPath);
  1671. SaveVideoNfo(timer, recordingPath, program, false);
  1672. }
  1673. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1674. {
  1675. SaveVideoNfo(timer, recordingPath, program, true);
  1676. }
  1677. else
  1678. {
  1679. SaveVideoNfo(timer, recordingPath, program, false);
  1680. }
  1681. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1682. }
  1683. catch (Exception ex)
  1684. {
  1685. _logger.ErrorException("Error saving nfo", ex);
  1686. }
  1687. }
  1688. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1689. {
  1690. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1691. if (_fileSystem.FileExists(nfoPath))
  1692. {
  1693. return;
  1694. }
  1695. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1696. {
  1697. var settings = new XmlWriterSettings
  1698. {
  1699. Indent = true,
  1700. Encoding = Encoding.UTF8,
  1701. CloseOutput = false
  1702. };
  1703. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1704. {
  1705. writer.WriteStartDocument(true);
  1706. writer.WriteStartElement("tvshow");
  1707. if (!string.IsNullOrWhiteSpace(timer.Name))
  1708. {
  1709. writer.WriteElementString("title", timer.Name);
  1710. }
  1711. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1712. {
  1713. writer.WriteElementString("mpaa", timer.OfficialRating);
  1714. }
  1715. foreach (var genre in timer.Genres)
  1716. {
  1717. writer.WriteElementString("genre", genre);
  1718. }
  1719. writer.WriteEndElement();
  1720. writer.WriteEndDocument();
  1721. }
  1722. }
  1723. }
  1724. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1725. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1726. {
  1727. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1728. if (_fileSystem.FileExists(nfoPath))
  1729. {
  1730. return;
  1731. }
  1732. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1733. {
  1734. var settings = new XmlWriterSettings
  1735. {
  1736. Indent = true,
  1737. Encoding = Encoding.UTF8,
  1738. CloseOutput = false
  1739. };
  1740. var options = _config.GetNfoConfiguration();
  1741. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1742. {
  1743. writer.WriteStartDocument(true);
  1744. if (timer.IsProgramSeries)
  1745. {
  1746. writer.WriteStartElement("episodedetails");
  1747. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1748. {
  1749. writer.WriteElementString("title", timer.EpisodeTitle);
  1750. }
  1751. if (item.PremiereDate.HasValue)
  1752. {
  1753. var formatString = options.ReleaseDateFormat;
  1754. writer.WriteElementString("aired", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1755. }
  1756. if (item.IndexNumber.HasValue)
  1757. {
  1758. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1759. }
  1760. if (item.ParentIndexNumber.HasValue)
  1761. {
  1762. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1763. }
  1764. }
  1765. else
  1766. {
  1767. writer.WriteStartElement("movie");
  1768. if (!string.IsNullOrWhiteSpace(item.Name))
  1769. {
  1770. writer.WriteElementString("title", item.Name);
  1771. }
  1772. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1773. {
  1774. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1775. }
  1776. if (item.PremiereDate.HasValue)
  1777. {
  1778. var formatString = options.ReleaseDateFormat;
  1779. writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1780. writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1781. }
  1782. }
  1783. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1784. if (item.ProductionYear.HasValue)
  1785. {
  1786. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1787. }
  1788. if (!string.IsNullOrEmpty(item.OfficialRating))
  1789. {
  1790. writer.WriteElementString("mpaa", item.OfficialRating);
  1791. }
  1792. var overview = (item.Overview ?? string.Empty)
  1793. .StripHtml()
  1794. .Replace("&quot;", "'");
  1795. writer.WriteElementString("plot", overview);
  1796. if (lockData)
  1797. {
  1798. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1799. }
  1800. if (item.CommunityRating.HasValue)
  1801. {
  1802. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1803. }
  1804. foreach (var genre in item.Genres)
  1805. {
  1806. writer.WriteElementString("genre", genre);
  1807. }
  1808. if (!string.IsNullOrWhiteSpace(item.HomePageUrl))
  1809. {
  1810. writer.WriteElementString("website", item.HomePageUrl);
  1811. }
  1812. var people = item.Id == Guid.Empty ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1813. var directors = people
  1814. .Where(i => IsPersonType(i, PersonType.Director))
  1815. .Select(i => i.Name)
  1816. .ToList();
  1817. foreach (var person in directors)
  1818. {
  1819. writer.WriteElementString("director", person);
  1820. }
  1821. var writers = people
  1822. .Where(i => IsPersonType(i, PersonType.Writer))
  1823. .Select(i => i.Name)
  1824. .Distinct(StringComparer.OrdinalIgnoreCase)
  1825. .ToList();
  1826. foreach (var person in writers)
  1827. {
  1828. writer.WriteElementString("writer", person);
  1829. }
  1830. foreach (var person in writers)
  1831. {
  1832. writer.WriteElementString("credits", person);
  1833. }
  1834. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  1835. if (!string.IsNullOrEmpty(tmdbCollection))
  1836. {
  1837. writer.WriteElementString("collectionnumber", tmdbCollection);
  1838. }
  1839. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  1840. if (!string.IsNullOrEmpty(imdb))
  1841. {
  1842. if (item is Series)
  1843. {
  1844. writer.WriteElementString("imdb_id", imdb);
  1845. }
  1846. else
  1847. {
  1848. writer.WriteElementString("imdbid", imdb);
  1849. }
  1850. }
  1851. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  1852. if (!string.IsNullOrEmpty(tvdb))
  1853. {
  1854. writer.WriteElementString("tvdbid", tvdb);
  1855. }
  1856. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  1857. if (!string.IsNullOrEmpty(tmdb))
  1858. {
  1859. writer.WriteElementString("tmdbid", tmdb);
  1860. }
  1861. if (item.CriticRating.HasValue)
  1862. {
  1863. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1864. }
  1865. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1866. {
  1867. writer.WriteElementString("tagline", item.Tagline);
  1868. }
  1869. foreach (var studio in item.Studios)
  1870. {
  1871. writer.WriteElementString("studio", studio);
  1872. }
  1873. writer.WriteEndElement();
  1874. writer.WriteEndDocument();
  1875. }
  1876. }
  1877. }
  1878. private static bool IsPersonType(PersonInfo person, string type)
  1879. {
  1880. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1881. }
  1882. private void AddGenre(List<string> genres, string genre)
  1883. {
  1884. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1885. {
  1886. genres.Add(genre);
  1887. }
  1888. }
  1889. private LiveTvProgram GetProgramInfoFromCache(string programId)
  1890. {
  1891. var query = new InternalItemsQuery
  1892. {
  1893. ItemIds = new[] { _liveTvManager.GetInternalProgramId(Name, programId).ToString("N") },
  1894. Limit = 1,
  1895. DtoOptions = new DtoOptions()
  1896. };
  1897. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1898. }
  1899. private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
  1900. {
  1901. return GetProgramInfoFromCache(timer.ProgramId, timer.ChannelId);
  1902. }
  1903. private LiveTvProgram GetProgramInfoFromCache(string programId, string channelId)
  1904. {
  1905. return GetProgramInfoFromCache(programId);
  1906. }
  1907. private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1908. {
  1909. var query = new InternalItemsQuery
  1910. {
  1911. IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
  1912. Limit = 1,
  1913. DtoOptions = new DtoOptions(true)
  1914. {
  1915. EnableImages = false
  1916. },
  1917. MinStartDate = startDateUtc.AddMinutes(-3),
  1918. MaxStartDate = startDateUtc.AddMinutes(3),
  1919. OrderBy = new[] { new Tuple<string, SortOrder>(ItemSortBy.StartDate, SortOrder.Ascending) }
  1920. };
  1921. if (!string.IsNullOrWhiteSpace(channelId))
  1922. {
  1923. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId).ToString("N") };
  1924. }
  1925. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1926. }
  1927. private LiveTvOptions GetConfiguration()
  1928. {
  1929. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1930. }
  1931. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1932. {
  1933. if (timer.IsManual)
  1934. {
  1935. return false;
  1936. }
  1937. if (!seriesTimer.RecordAnyTime)
  1938. {
  1939. if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(5).Ticks)
  1940. {
  1941. return true;
  1942. }
  1943. }
  1944. //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
  1945. //{
  1946. // return true;
  1947. //}
  1948. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1949. {
  1950. return true;
  1951. }
  1952. if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1953. {
  1954. return true;
  1955. }
  1956. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1957. }
  1958. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1959. {
  1960. foreach (var timer in timers.Skip(1))
  1961. {
  1962. // TODO: Get smarter, prefer HD, etc
  1963. timer.Status = RecordingStatus.Cancelled;
  1964. _timerProvider.Update(timer);
  1965. }
  1966. }
  1967. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1968. {
  1969. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1970. foreach (var group in groups)
  1971. {
  1972. if (string.IsNullOrWhiteSpace(group.Key))
  1973. {
  1974. continue;
  1975. }
  1976. var groupTimers = group.ToList();
  1977. if (groupTimers.Count < 2)
  1978. {
  1979. continue;
  1980. }
  1981. HandleDuplicateShowIds(groupTimers);
  1982. }
  1983. }
  1984. private async Task UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1985. {
  1986. var allTimers = GetTimersForSeries(seriesTimer)
  1987. .ToList();
  1988. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1989. var enabledTimersForSeries = new List<TimerInfo>();
  1990. if (registration.IsValid)
  1991. {
  1992. foreach (var timer in allTimers)
  1993. {
  1994. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1995. if (existingTimer == null)
  1996. {
  1997. existingTimer = string.IsNullOrWhiteSpace(timer.ProgramId)
  1998. ? null
  1999. : _timerProvider.GetTimerByProgramId(timer.ProgramId);
  2000. }
  2001. if (existingTimer == null)
  2002. {
  2003. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  2004. {
  2005. timer.Status = RecordingStatus.Cancelled;
  2006. }
  2007. else
  2008. {
  2009. enabledTimersForSeries.Add(timer);
  2010. }
  2011. _timerProvider.Add(timer);
  2012. }
  2013. else
  2014. {
  2015. // Only update if not currently active - test both new timer and existing in case Id's are different
  2016. // Id's could be different if the timer was created manually prior to series timer creation
  2017. ActiveRecordingInfo activeRecordingInfo;
  2018. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo))
  2019. {
  2020. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  2021. // Needed by ShouldCancelTimerForSeriesTimer
  2022. timer.IsManual = existingTimer.IsManual;
  2023. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  2024. {
  2025. existingTimer.Status = RecordingStatus.Cancelled;
  2026. }
  2027. if (existingTimer.Status != RecordingStatus.Cancelled)
  2028. {
  2029. enabledTimersForSeries.Add(existingTimer);
  2030. }
  2031. if (updateTimerSettings)
  2032. {
  2033. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  2034. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  2035. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  2036. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  2037. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  2038. existingTimer.Priority = seriesTimer.Priority;
  2039. }
  2040. existingTimer.SeriesTimerId = seriesTimer.Id;
  2041. _timerProvider.Update(existingTimer);
  2042. }
  2043. }
  2044. }
  2045. }
  2046. SearchForDuplicateShowIds(enabledTimersForSeries);
  2047. if (deleteInvalidTimers)
  2048. {
  2049. var allTimerIds = allTimers
  2050. .Select(i => i.Id)
  2051. .ToList();
  2052. var deleteStatuses = new List<RecordingStatus>
  2053. {
  2054. RecordingStatus.New
  2055. };
  2056. var deletes = _timerProvider.GetAll()
  2057. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  2058. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  2059. .Where(i => deleteStatuses.Contains(i.Status))
  2060. .ToList();
  2061. foreach (var timer in deletes)
  2062. {
  2063. CancelTimerInternal(timer.Id, false);
  2064. }
  2065. }
  2066. }
  2067. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer)
  2068. {
  2069. if (seriesTimer == null)
  2070. {
  2071. throw new ArgumentNullException("seriesTimer");
  2072. }
  2073. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  2074. {
  2075. return new List<TimerInfo>();
  2076. }
  2077. var query = new InternalItemsQuery
  2078. {
  2079. IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
  2080. ExternalSeriesId = seriesTimer.SeriesId,
  2081. DtoOptions = new DtoOptions(true)
  2082. {
  2083. EnableImages = false
  2084. },
  2085. MinEndDate = DateTime.UtcNow
  2086. };
  2087. if (!seriesTimer.RecordAnyChannel)
  2088. {
  2089. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId).ToString("N") };
  2090. }
  2091. var tempChannelCache = new Dictionary<string, LiveTvChannel>();
  2092. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().Select(i => CreateTimer(i, seriesTimer, tempChannelCache));
  2093. }
  2094. private TimerInfo CreateTimer(LiveTvProgram parent, SeriesTimerInfo seriesTimer, Dictionary<string, LiveTvChannel> tempChannelCache)
  2095. {
  2096. string channelId = seriesTimer.RecordAnyChannel ? null : seriesTimer.ChannelId;
  2097. if (string.IsNullOrWhiteSpace(channelId) && !string.IsNullOrWhiteSpace(parent.ChannelId))
  2098. {
  2099. LiveTvChannel channel;
  2100. if (!tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  2101. {
  2102. channel = _libraryManager.GetItemList(new InternalItemsQuery
  2103. {
  2104. IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name },
  2105. ItemIds = new[] { parent.ChannelId },
  2106. DtoOptions = new DtoOptions()
  2107. }).Cast<LiveTvChannel>().FirstOrDefault();
  2108. if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2109. {
  2110. tempChannelCache[parent.ChannelId] = channel;
  2111. }
  2112. }
  2113. if (channel != null || tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  2114. {
  2115. channelId = channel.ExternalId;
  2116. }
  2117. }
  2118. var timer = new TimerInfo
  2119. {
  2120. ChannelId = channelId,
  2121. Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N"),
  2122. StartDate = parent.StartDate,
  2123. EndDate = parent.EndDate.Value,
  2124. ProgramId = parent.ExternalId,
  2125. PrePaddingSeconds = seriesTimer.PrePaddingSeconds,
  2126. PostPaddingSeconds = seriesTimer.PostPaddingSeconds,
  2127. IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired,
  2128. IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired,
  2129. KeepUntil = seriesTimer.KeepUntil,
  2130. Priority = seriesTimer.Priority,
  2131. Name = parent.Name,
  2132. Overview = parent.Overview,
  2133. SeriesId = parent.ExternalSeriesId,
  2134. SeriesTimerId = seriesTimer.Id,
  2135. ShowId = parent.ShowId
  2136. };
  2137. CopyProgramInfoToTimerInfo(parent, timer, tempChannelCache);
  2138. return timer;
  2139. }
  2140. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo)
  2141. {
  2142. var tempChannelCache = new Dictionary<string, LiveTvChannel>();
  2143. CopyProgramInfoToTimerInfo(programInfo, timerInfo, tempChannelCache);
  2144. }
  2145. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo, Dictionary<string, LiveTvChannel> tempChannelCache)
  2146. {
  2147. string channelId = null;
  2148. if (!string.IsNullOrWhiteSpace(programInfo.ChannelId))
  2149. {
  2150. LiveTvChannel channel;
  2151. if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2152. {
  2153. channel = _libraryManager.GetItemList(new InternalItemsQuery
  2154. {
  2155. IncludeItemTypes = new string[] { typeof(LiveTvChannel).Name },
  2156. ItemIds = new[] { programInfo.ChannelId },
  2157. DtoOptions = new DtoOptions()
  2158. }).Cast<LiveTvChannel>().FirstOrDefault();
  2159. if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2160. {
  2161. tempChannelCache[programInfo.ChannelId] = channel;
  2162. }
  2163. }
  2164. if (channel != null || tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2165. {
  2166. channelId = channel.ExternalId;
  2167. }
  2168. }
  2169. timerInfo.Name = programInfo.Name;
  2170. timerInfo.StartDate = programInfo.StartDate;
  2171. timerInfo.EndDate = programInfo.EndDate.Value;
  2172. if (!string.IsNullOrWhiteSpace(channelId))
  2173. {
  2174. timerInfo.ChannelId = channelId;
  2175. }
  2176. timerInfo.SeasonNumber = programInfo.ParentIndexNumber;
  2177. timerInfo.EpisodeNumber = programInfo.IndexNumber;
  2178. timerInfo.IsMovie = programInfo.IsMovie;
  2179. timerInfo.IsKids = programInfo.IsKids;
  2180. timerInfo.IsNews = programInfo.IsNews;
  2181. timerInfo.IsSports = programInfo.IsSports;
  2182. timerInfo.ProductionYear = programInfo.ProductionYear;
  2183. timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
  2184. timerInfo.OriginalAirDate = programInfo.PremiereDate;
  2185. timerInfo.IsProgramSeries = programInfo.IsSeries;
  2186. timerInfo.IsSeries = programInfo.IsSeries;
  2187. timerInfo.IsLive = programInfo.IsLive;
  2188. timerInfo.IsPremiere = programInfo.IsPremiere;
  2189. timerInfo.HomePageUrl = programInfo.HomePageUrl;
  2190. timerInfo.CommunityRating = programInfo.CommunityRating;
  2191. timerInfo.Overview = programInfo.Overview;
  2192. timerInfo.OfficialRating = programInfo.OfficialRating;
  2193. timerInfo.IsRepeat = programInfo.IsRepeat;
  2194. timerInfo.SeriesId = programInfo.ExternalSeriesId;
  2195. }
  2196. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2197. {
  2198. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2199. {
  2200. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  2201. {
  2202. IncludeItemTypes = new[] { typeof(Series).Name },
  2203. Name = program.Name
  2204. }).Select(i => i.ToString("N")).ToArray();
  2205. if (seriesIds.Length == 0)
  2206. {
  2207. return false;
  2208. }
  2209. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2210. {
  2211. var result = _libraryManager.GetItemIds(new InternalItemsQuery
  2212. {
  2213. IncludeItemTypes = new[] { typeof(Episode).Name },
  2214. ParentIndexNumber = program.SeasonNumber.Value,
  2215. IndexNumber = program.EpisodeNumber.Value,
  2216. AncestorIds = seriesIds,
  2217. IsVirtualItem = false,
  2218. Limit = 1
  2219. });
  2220. if (result.Count > 0)
  2221. {
  2222. return true;
  2223. }
  2224. }
  2225. }
  2226. return false;
  2227. }
  2228. private bool _disposed;
  2229. public void Dispose()
  2230. {
  2231. _disposed = true;
  2232. foreach (var pair in _activeRecordings.ToList())
  2233. {
  2234. pair.Value.CancellationTokenSource.Cancel();
  2235. }
  2236. GC.SuppressFinalize(this);
  2237. }
  2238. public List<VirtualFolderInfo> GetRecordingFolders()
  2239. {
  2240. var list = new List<VirtualFolderInfo>();
  2241. var defaultFolder = RecordingPath;
  2242. var defaultName = "Recordings";
  2243. if (_fileSystem.DirectoryExists(defaultFolder))
  2244. {
  2245. list.Add(new VirtualFolderInfo
  2246. {
  2247. Locations = new string[] { defaultFolder },
  2248. Name = defaultName
  2249. });
  2250. }
  2251. var customPath = GetConfiguration().MovieRecordingPath;
  2252. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2253. {
  2254. list.Add(new VirtualFolderInfo
  2255. {
  2256. Locations = new string[] { customPath },
  2257. Name = "Recorded Movies",
  2258. CollectionType = CollectionType.Movies
  2259. });
  2260. }
  2261. customPath = GetConfiguration().SeriesRecordingPath;
  2262. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2263. {
  2264. list.Add(new VirtualFolderInfo
  2265. {
  2266. Locations = new string[] { customPath },
  2267. Name = "Recorded Shows",
  2268. CollectionType = CollectionType.TvShows
  2269. });
  2270. }
  2271. return list;
  2272. }
  2273. private const int TunerDiscoveryDurationMs = 3000;
  2274. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2275. {
  2276. var list = new List<TunerHostInfo>();
  2277. var configuredDeviceIds = GetConfiguration().TunerHosts
  2278. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2279. .Select(i => i.DeviceId)
  2280. .ToList();
  2281. foreach (var host in _liveTvManager.TunerHosts)
  2282. {
  2283. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2284. if (newDevicesOnly)
  2285. {
  2286. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparer.OrdinalIgnoreCase))
  2287. .ToList();
  2288. }
  2289. list.AddRange(discoveredDevices);
  2290. }
  2291. return list;
  2292. }
  2293. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2294. {
  2295. foreach (var host in _liveTvManager.TunerHosts)
  2296. {
  2297. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2298. }
  2299. }
  2300. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2301. {
  2302. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2303. var configuredDevices = GetConfiguration().TunerHosts
  2304. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2305. .ToList();
  2306. foreach (var device in discoveredDevices)
  2307. {
  2308. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2309. if (configuredDevice != null)
  2310. {
  2311. if (!string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2312. {
  2313. _logger.Info("Tuner url has changed from {0} to {1}", configuredDevice.Url, device.Url);
  2314. configuredDevice.Url = device.Url;
  2315. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2316. }
  2317. }
  2318. }
  2319. }
  2320. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDuationMs, CancellationToken cancellationToken)
  2321. {
  2322. try
  2323. {
  2324. var discoveredDevices = await host.DiscoverDevices(discoveryDuationMs, cancellationToken).ConfigureAwait(false);
  2325. foreach (var device in discoveredDevices)
  2326. {
  2327. _logger.Info("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2328. }
  2329. return discoveredDevices;
  2330. }
  2331. catch (Exception ex)
  2332. {
  2333. _logger.ErrorException("Error discovering tuner devices", ex);
  2334. return new List<TunerHostInfo>();
  2335. }
  2336. }
  2337. }
  2338. public static class ConfigurationExtension
  2339. {
  2340. public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
  2341. {
  2342. return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  2343. }
  2344. }
  2345. }