EmbyTV.cs 105 KB

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