LiveTvManager.cs 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Common.ScheduledTasks;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.LiveTv;
  12. using MediaBrowser.Controller.Localization;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Sorting;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.LiveTv;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Querying;
  21. using MediaBrowser.Model.Serialization;
  22. using MoreLinq;
  23. using System;
  24. using System.Collections.Concurrent;
  25. using System.Collections.Generic;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using CommonIO;
  31. using IniParser;
  32. using IniParser.Model;
  33. using MediaBrowser.Common.Events;
  34. using MediaBrowser.Controller.Entities.Movies;
  35. using MediaBrowser.Controller.Entities.TV;
  36. using MediaBrowser.Model.Events;
  37. namespace MediaBrowser.Server.Implementations.LiveTv
  38. {
  39. /// <summary>
  40. /// Class LiveTvManager
  41. /// </summary>
  42. public class LiveTvManager : ILiveTvManager, IDisposable
  43. {
  44. private readonly IServerConfigurationManager _config;
  45. private readonly ILogger _logger;
  46. private readonly IItemRepository _itemRepo;
  47. private readonly IUserManager _userManager;
  48. private readonly IUserDataManager _userDataManager;
  49. private readonly ILibraryManager _libraryManager;
  50. private readonly ITaskManager _taskManager;
  51. private readonly IJsonSerializer _jsonSerializer;
  52. private readonly IProviderManager _providerManager;
  53. private readonly IDtoService _dtoService;
  54. private readonly ILocalizationManager _localization;
  55. private readonly LiveTvDtoService _tvDtoService;
  56. private readonly List<ILiveTvService> _services = new List<ILiveTvService>();
  57. private readonly ConcurrentDictionary<string, LiveStreamData> _openStreams =
  58. new ConcurrentDictionary<string, LiveStreamData>();
  59. private readonly SemaphoreSlim _refreshRecordingsLock = new SemaphoreSlim(1, 1);
  60. private readonly List<ITunerHost> _tunerHosts = new List<ITunerHost>();
  61. private readonly List<IListingsProvider> _listingProviders = new List<IListingsProvider>();
  62. private readonly IFileSystem _fileSystem;
  63. public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCancelled;
  64. public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCancelled;
  65. public event EventHandler<GenericEventArgs<TimerEventInfo>> TimerCreated;
  66. public event EventHandler<GenericEventArgs<TimerEventInfo>> SeriesTimerCreated;
  67. public LiveTvManager(IApplicationHost appHost, IServerConfigurationManager config, ILogger logger, IItemRepository itemRepo, IImageProcessor imageProcessor, IUserDataManager userDataManager, IDtoService dtoService, IUserManager userManager, ILibraryManager libraryManager, ITaskManager taskManager, ILocalizationManager localization, IJsonSerializer jsonSerializer, IProviderManager providerManager, IFileSystem fileSystem)
  68. {
  69. _config = config;
  70. _logger = logger;
  71. _itemRepo = itemRepo;
  72. _userManager = userManager;
  73. _libraryManager = libraryManager;
  74. _taskManager = taskManager;
  75. _localization = localization;
  76. _jsonSerializer = jsonSerializer;
  77. _providerManager = providerManager;
  78. _fileSystem = fileSystem;
  79. _dtoService = dtoService;
  80. _userDataManager = userDataManager;
  81. _tvDtoService = new LiveTvDtoService(dtoService, userDataManager, imageProcessor, logger, appHost, _libraryManager);
  82. }
  83. /// <summary>
  84. /// Gets the services.
  85. /// </summary>
  86. /// <value>The services.</value>
  87. public IReadOnlyList<ILiveTvService> Services
  88. {
  89. get { return _services; }
  90. }
  91. private LiveTvOptions GetConfiguration()
  92. {
  93. return _config.GetConfiguration<LiveTvOptions>("livetv");
  94. }
  95. /// <summary>
  96. /// Adds the parts.
  97. /// </summary>
  98. /// <param name="services">The services.</param>
  99. /// <param name="tunerHosts">The tuner hosts.</param>
  100. /// <param name="listingProviders">The listing providers.</param>
  101. public void AddParts(IEnumerable<ILiveTvService> services, IEnumerable<ITunerHost> tunerHosts, IEnumerable<IListingsProvider> listingProviders)
  102. {
  103. _services.AddRange(services);
  104. _tunerHosts.AddRange(tunerHosts);
  105. _listingProviders.AddRange(listingProviders);
  106. foreach (var service in _services)
  107. {
  108. service.DataSourceChanged += service_DataSourceChanged;
  109. }
  110. }
  111. public List<ITunerHost> TunerHosts
  112. {
  113. get { return _tunerHosts; }
  114. }
  115. public List<IListingsProvider> ListingProviders
  116. {
  117. get { return _listingProviders; }
  118. }
  119. void service_DataSourceChanged(object sender, EventArgs e)
  120. {
  121. if (!_isDisposed)
  122. {
  123. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  124. }
  125. }
  126. public async Task<QueryResult<LiveTvChannel>> GetInternalChannels(LiveTvChannelQuery query, CancellationToken cancellationToken)
  127. {
  128. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  129. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  130. var channels = _libraryManager.GetItemList(new InternalItemsQuery
  131. {
  132. IncludeItemTypes = new[] { typeof(LiveTvChannel).Name },
  133. SortBy = new[] { ItemSortBy.SortName },
  134. TopParentIds = new[] { topFolder.Id.ToString("N") }
  135. }).Cast<LiveTvChannel>();
  136. if (user != null)
  137. {
  138. // Avoid implicitly captured closure
  139. var currentUser = user;
  140. channels = channels
  141. .Where(i => i.IsVisible(currentUser))
  142. .OrderBy(i =>
  143. {
  144. double number = 0;
  145. if (!string.IsNullOrEmpty(i.Number))
  146. {
  147. double.TryParse(i.Number, out number);
  148. }
  149. return number;
  150. });
  151. if (query.IsFavorite.HasValue)
  152. {
  153. var val = query.IsFavorite.Value;
  154. channels = channels
  155. .Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val);
  156. }
  157. if (query.IsLiked.HasValue)
  158. {
  159. var val = query.IsLiked.Value;
  160. channels = channels
  161. .Where(i =>
  162. {
  163. var likes = _userDataManager.GetUserData(user, i).Likes;
  164. return likes.HasValue && likes.Value == val;
  165. });
  166. }
  167. if (query.IsDisliked.HasValue)
  168. {
  169. var val = query.IsDisliked.Value;
  170. channels = channels
  171. .Where(i =>
  172. {
  173. var likes = _userDataManager.GetUserData(user, i).Likes;
  174. return likes.HasValue && likes.Value != val;
  175. });
  176. }
  177. }
  178. var enableFavoriteSorting = query.EnableFavoriteSorting;
  179. channels = channels.OrderBy(i =>
  180. {
  181. if (enableFavoriteSorting)
  182. {
  183. var userData = _userDataManager.GetUserData(user, i);
  184. if (userData.IsFavorite)
  185. {
  186. return 0;
  187. }
  188. if (userData.Likes.HasValue)
  189. {
  190. if (!userData.Likes.Value)
  191. {
  192. return 3;
  193. }
  194. return 1;
  195. }
  196. }
  197. return 2;
  198. });
  199. var allChannels = channels.ToList();
  200. IEnumerable<LiveTvChannel> allEnumerable = allChannels;
  201. if (query.StartIndex.HasValue)
  202. {
  203. allEnumerable = allEnumerable.Skip(query.StartIndex.Value);
  204. }
  205. if (query.Limit.HasValue)
  206. {
  207. allEnumerable = allEnumerable.Take(query.Limit.Value);
  208. }
  209. var result = new QueryResult<LiveTvChannel>
  210. {
  211. Items = allEnumerable.ToArray(),
  212. TotalRecordCount = allChannels.Count
  213. };
  214. return result;
  215. }
  216. public LiveTvChannel GetInternalChannel(string id)
  217. {
  218. return GetInternalChannel(new Guid(id));
  219. }
  220. private LiveTvChannel GetInternalChannel(Guid id)
  221. {
  222. return _libraryManager.GetItemById(id) as LiveTvChannel;
  223. }
  224. internal LiveTvProgram GetInternalProgram(string id)
  225. {
  226. return _libraryManager.GetItemById(id) as LiveTvProgram;
  227. }
  228. internal LiveTvProgram GetInternalProgram(Guid id)
  229. {
  230. return _libraryManager.GetItemById(id) as LiveTvProgram;
  231. }
  232. public async Task<BaseItem> GetInternalRecording(string id, CancellationToken cancellationToken)
  233. {
  234. if (string.IsNullOrWhiteSpace(id))
  235. {
  236. throw new ArgumentNullException("id");
  237. }
  238. var result = await GetInternalRecordings(new RecordingQuery
  239. {
  240. Id = id
  241. }, cancellationToken).ConfigureAwait(false);
  242. return result.Items.FirstOrDefault();
  243. }
  244. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  245. public async Task<MediaSourceInfo> GetRecordingStream(string id, CancellationToken cancellationToken)
  246. {
  247. return await GetLiveStream(id, null, false, cancellationToken).ConfigureAwait(false);
  248. }
  249. public async Task<MediaSourceInfo> GetChannelStream(string id, string mediaSourceId, CancellationToken cancellationToken)
  250. {
  251. return await GetLiveStream(id, mediaSourceId, true, cancellationToken).ConfigureAwait(false);
  252. }
  253. public async Task<IEnumerable<MediaSourceInfo>> GetRecordingMediaSources(string id, CancellationToken cancellationToken)
  254. {
  255. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  256. var service = GetService(item);
  257. return await service.GetRecordingStreamMediaSources(id, cancellationToken).ConfigureAwait(false);
  258. }
  259. public async Task<IEnumerable<MediaSourceInfo>> GetChannelMediaSources(string id, CancellationToken cancellationToken)
  260. {
  261. var item = GetInternalChannel(id);
  262. var service = GetService(item);
  263. var sources = await service.GetChannelStreamMediaSources(item.ExternalId, cancellationToken).ConfigureAwait(false);
  264. if (sources.Count == 0)
  265. {
  266. throw new NotImplementedException();
  267. }
  268. var list = sources.ToList();
  269. foreach (var source in list)
  270. {
  271. Normalize(source, service, item.ChannelType == ChannelType.TV);
  272. }
  273. return list;
  274. }
  275. private ILiveTvService GetService(ILiveTvRecording item)
  276. {
  277. return GetService(item.ServiceName);
  278. }
  279. private ILiveTvService GetService(BaseItem item)
  280. {
  281. return GetService(item.ServiceName);
  282. }
  283. private ILiveTvService GetService(string name)
  284. {
  285. return _services.FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  286. }
  287. private async Task<MediaSourceInfo> GetLiveStream(string id, string mediaSourceId, bool isChannel, CancellationToken cancellationToken)
  288. {
  289. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  290. if (string.Equals(id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  291. {
  292. mediaSourceId = null;
  293. }
  294. try
  295. {
  296. MediaSourceInfo info;
  297. bool isVideo;
  298. ILiveTvService service;
  299. if (isChannel)
  300. {
  301. var channel = GetInternalChannel(id);
  302. isVideo = channel.ChannelType == ChannelType.TV;
  303. service = GetService(channel);
  304. _logger.Info("Opening channel stream from {0}, external channel Id: {1}", service.Name, channel.ExternalId);
  305. info = await service.GetChannelStream(channel.ExternalId, mediaSourceId, cancellationToken).ConfigureAwait(false);
  306. info.RequiresClosing = true;
  307. if (info.RequiresClosing)
  308. {
  309. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  310. info.LiveStreamId = idPrefix + info.Id;
  311. }
  312. }
  313. else
  314. {
  315. var recording = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  316. isVideo = !string.Equals(recording.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase);
  317. service = GetService(recording);
  318. _logger.Info("Opening recording stream from {0}, external recording Id: {1}", service.Name, recording.ExternalId);
  319. info = await service.GetRecordingStream(recording.ExternalId, null, cancellationToken).ConfigureAwait(false);
  320. info.RequiresClosing = true;
  321. if (info.RequiresClosing)
  322. {
  323. var idPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  324. info.LiveStreamId = idPrefix + info.Id;
  325. }
  326. }
  327. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(info));
  328. Normalize(info, service, isVideo);
  329. var data = new LiveStreamData
  330. {
  331. Info = info,
  332. IsChannel = isChannel,
  333. ItemId = id
  334. };
  335. _openStreams.AddOrUpdate(info.Id, data, (key, i) => data);
  336. return info;
  337. }
  338. catch (Exception ex)
  339. {
  340. _logger.ErrorException("Error getting channel stream", ex);
  341. throw;
  342. }
  343. finally
  344. {
  345. _liveStreamSemaphore.Release();
  346. }
  347. }
  348. private void Normalize(MediaSourceInfo mediaSource, ILiveTvService service, bool isVideo)
  349. {
  350. if (mediaSource.MediaStreams.Count == 0)
  351. {
  352. if (isVideo)
  353. {
  354. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  355. {
  356. new MediaStream
  357. {
  358. Type = MediaStreamType.Video,
  359. // Set the index to -1 because we don't know the exact index of the video stream within the container
  360. Index = -1,
  361. // Set to true if unknown to enable deinterlacing
  362. IsInterlaced = true
  363. },
  364. new MediaStream
  365. {
  366. Type = MediaStreamType.Audio,
  367. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  368. Index = -1
  369. }
  370. });
  371. }
  372. else
  373. {
  374. mediaSource.MediaStreams.AddRange(new List<MediaStream>
  375. {
  376. new MediaStream
  377. {
  378. Type = MediaStreamType.Audio,
  379. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  380. Index = -1
  381. }
  382. });
  383. }
  384. }
  385. // Clean some bad data coming from providers
  386. foreach (var stream in mediaSource.MediaStreams)
  387. {
  388. if (stream.BitRate.HasValue && stream.BitRate <= 0)
  389. {
  390. stream.BitRate = null;
  391. }
  392. if (stream.Channels.HasValue && stream.Channels <= 0)
  393. {
  394. stream.Channels = null;
  395. }
  396. if (stream.AverageFrameRate.HasValue && stream.AverageFrameRate <= 0)
  397. {
  398. stream.AverageFrameRate = null;
  399. }
  400. if (stream.RealFrameRate.HasValue && stream.RealFrameRate <= 0)
  401. {
  402. stream.RealFrameRate = null;
  403. }
  404. if (stream.Width.HasValue && stream.Width <= 0)
  405. {
  406. stream.Width = null;
  407. }
  408. if (stream.Height.HasValue && stream.Height <= 0)
  409. {
  410. stream.Height = null;
  411. }
  412. if (stream.SampleRate.HasValue && stream.SampleRate <= 0)
  413. {
  414. stream.SampleRate = null;
  415. }
  416. if (stream.Level.HasValue && stream.Level <= 0)
  417. {
  418. stream.Level = null;
  419. }
  420. }
  421. var indexes = mediaSource.MediaStreams.Select(i => i.Index).Distinct().ToList();
  422. // If there are duplicate stream indexes, set them all to unknown
  423. if (indexes.Count != mediaSource.MediaStreams.Count)
  424. {
  425. foreach (var stream in mediaSource.MediaStreams)
  426. {
  427. stream.Index = -1;
  428. }
  429. }
  430. // Set the total bitrate if not already supplied
  431. if (!mediaSource.Bitrate.HasValue)
  432. {
  433. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  434. if (total > 0)
  435. {
  436. mediaSource.Bitrate = total;
  437. }
  438. }
  439. if (!(service is EmbyTV.EmbyTV))
  440. {
  441. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  442. mediaSource.SupportsDirectStream = false;
  443. mediaSource.SupportsTranscoding = true;
  444. foreach (var stream in mediaSource.MediaStreams)
  445. {
  446. if (stream.Type == MediaStreamType.Video && string.IsNullOrWhiteSpace(stream.NalLengthSize))
  447. {
  448. stream.NalLengthSize = "0";
  449. }
  450. }
  451. }
  452. }
  453. private async Task<LiveTvChannel> GetChannel(ChannelInfo channelInfo, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  454. {
  455. var isNew = false;
  456. var forceUpdate = false;
  457. var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id);
  458. var item = _itemRepo.RetrieveItem(id) as LiveTvChannel;
  459. if (item == null)
  460. {
  461. item = new LiveTvChannel
  462. {
  463. Name = channelInfo.Name,
  464. Id = id,
  465. DateCreated = DateTime.UtcNow,
  466. };
  467. isNew = true;
  468. }
  469. if (!string.Equals(channelInfo.Id, item.ExternalId))
  470. {
  471. isNew = true;
  472. }
  473. item.ExternalId = channelInfo.Id;
  474. if (!item.ParentId.Equals(parentFolderId))
  475. {
  476. isNew = true;
  477. }
  478. item.ParentId = parentFolderId;
  479. item.ChannelType = channelInfo.ChannelType;
  480. item.ServiceName = serviceName;
  481. item.Number = channelInfo.Number;
  482. //if (!string.Equals(item.ProviderImageUrl, channelInfo.ImageUrl, StringComparison.OrdinalIgnoreCase))
  483. //{
  484. // isNew = true;
  485. // replaceImages.Add(ImageType.Primary);
  486. //}
  487. //if (!string.Equals(item.ProviderImagePath, channelInfo.ImagePath, StringComparison.OrdinalIgnoreCase))
  488. //{
  489. // isNew = true;
  490. // replaceImages.Add(ImageType.Primary);
  491. //}
  492. if (!item.HasImage(ImageType.Primary))
  493. {
  494. if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath))
  495. {
  496. item.SetImagePath(ImageType.Primary, channelInfo.ImagePath);
  497. forceUpdate = true;
  498. }
  499. else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl))
  500. {
  501. item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl);
  502. forceUpdate = true;
  503. }
  504. }
  505. if (string.IsNullOrEmpty(item.Name))
  506. {
  507. item.Name = channelInfo.Name;
  508. }
  509. if (isNew)
  510. {
  511. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  512. }
  513. else if (forceUpdate)
  514. {
  515. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  516. }
  517. await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  518. {
  519. ForceSave = isNew || forceUpdate
  520. }, cancellationToken);
  521. return item;
  522. }
  523. private async Task<LiveTvProgram> GetProgram(ProgramInfo info, LiveTvChannel channel, ChannelType channelType, string serviceName, CancellationToken cancellationToken)
  524. {
  525. var id = _tvDtoService.GetInternalProgramId(serviceName, info.Id);
  526. var item = _libraryManager.GetItemById(id) as LiveTvProgram;
  527. var isNew = false;
  528. var forceUpdate = false;
  529. if (item == null)
  530. {
  531. isNew = true;
  532. item = new LiveTvProgram
  533. {
  534. Name = info.Name,
  535. Id = id,
  536. DateCreated = DateTime.UtcNow,
  537. DateModified = DateTime.UtcNow,
  538. ExternalEtag = info.Etag
  539. };
  540. }
  541. if (!item.ParentId.Equals(channel.Id))
  542. {
  543. forceUpdate = true;
  544. }
  545. item.ParentId = channel.Id;
  546. //item.ChannelType = channelType;
  547. if (!string.Equals(item.ServiceName, serviceName, StringComparison.Ordinal))
  548. {
  549. forceUpdate = true;
  550. }
  551. item.ServiceName = serviceName;
  552. item.Audio = info.Audio;
  553. item.ChannelId = channel.Id.ToString("N");
  554. item.CommunityRating = item.CommunityRating ?? info.CommunityRating;
  555. item.EpisodeTitle = info.EpisodeTitle;
  556. item.ExternalId = info.Id;
  557. item.Genres = info.Genres;
  558. item.IsHD = info.IsHD;
  559. item.IsKids = info.IsKids;
  560. item.IsLive = info.IsLive;
  561. item.IsMovie = info.IsMovie;
  562. item.IsNews = info.IsNews;
  563. item.IsPremiere = info.IsPremiere;
  564. item.IsRepeat = info.IsRepeat;
  565. item.IsSeries = info.IsSeries;
  566. item.IsSports = info.IsSports;
  567. item.Name = info.Name;
  568. item.OfficialRating = item.OfficialRating ?? info.OfficialRating;
  569. item.Overview = item.Overview ?? info.Overview;
  570. item.RunTimeTicks = (info.EndDate - info.StartDate).Ticks;
  571. if (item.StartDate != info.StartDate)
  572. {
  573. forceUpdate = true;
  574. }
  575. item.StartDate = info.StartDate;
  576. if (item.EndDate != info.EndDate)
  577. {
  578. forceUpdate = true;
  579. }
  580. item.EndDate = info.EndDate;
  581. item.HomePageUrl = info.HomePageUrl;
  582. item.ProductionYear = info.ProductionYear;
  583. item.PremiereDate = info.OriginalAirDate;
  584. item.IndexNumber = info.EpisodeNumber;
  585. item.ParentIndexNumber = info.SeasonNumber;
  586. if (!item.HasImage(ImageType.Primary))
  587. {
  588. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  589. {
  590. item.SetImage(new ItemImageInfo
  591. {
  592. Path = info.ImagePath,
  593. Type = ImageType.Primary,
  594. IsPlaceholder = true
  595. }, 0);
  596. }
  597. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  598. {
  599. item.SetImage(new ItemImageInfo
  600. {
  601. Path = info.ImageUrl,
  602. Type = ImageType.Primary,
  603. IsPlaceholder = true
  604. }, 0);
  605. }
  606. }
  607. if (isNew)
  608. {
  609. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  610. }
  611. else if (forceUpdate || string.IsNullOrWhiteSpace(info.Etag))
  612. {
  613. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  614. }
  615. else
  616. {
  617. // Increment this whenver some internal change deems it necessary
  618. var etag = info.Etag + "4";
  619. if (!string.Equals(etag, item.ExternalEtag, StringComparison.OrdinalIgnoreCase))
  620. {
  621. item.ExternalEtag = etag;
  622. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  623. }
  624. }
  625. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem));
  626. return item;
  627. }
  628. private async Task<Guid> CreateRecordingRecord(RecordingInfo info, string serviceName, Guid parentFolderId, CancellationToken cancellationToken)
  629. {
  630. var isNew = false;
  631. var id = _tvDtoService.GetInternalRecordingId(serviceName, info.Id);
  632. var item = _itemRepo.RetrieveItem(id);
  633. if (item == null)
  634. {
  635. if (info.ChannelType == ChannelType.TV)
  636. {
  637. item = new LiveTvVideoRecording
  638. {
  639. Name = info.Name,
  640. Id = id,
  641. DateCreated = DateTime.UtcNow,
  642. DateModified = DateTime.UtcNow,
  643. VideoType = VideoType.VideoFile
  644. };
  645. }
  646. else
  647. {
  648. item = new LiveTvAudioRecording
  649. {
  650. Name = info.Name,
  651. Id = id,
  652. DateCreated = DateTime.UtcNow,
  653. DateModified = DateTime.UtcNow
  654. };
  655. }
  656. isNew = true;
  657. }
  658. item.ChannelId = _tvDtoService.GetInternalChannelId(serviceName, info.ChannelId).ToString("N");
  659. item.CommunityRating = info.CommunityRating;
  660. item.OfficialRating = info.OfficialRating;
  661. item.Overview = info.Overview;
  662. item.EndDate = info.EndDate;
  663. item.Genres = info.Genres;
  664. item.PremiereDate = info.OriginalAirDate;
  665. var recording = (ILiveTvRecording)item;
  666. recording.ExternalId = info.Id;
  667. var dataChanged = false;
  668. recording.Audio = info.Audio;
  669. recording.EndDate = info.EndDate;
  670. recording.EpisodeTitle = info.EpisodeTitle;
  671. recording.IsHD = info.IsHD;
  672. recording.IsKids = info.IsKids;
  673. recording.IsLive = info.IsLive;
  674. recording.IsMovie = info.IsMovie;
  675. recording.IsNews = info.IsNews;
  676. recording.IsPremiere = info.IsPremiere;
  677. recording.IsRepeat = info.IsRepeat;
  678. recording.IsSports = info.IsSports;
  679. recording.SeriesTimerId = info.SeriesTimerId;
  680. recording.StartDate = info.StartDate;
  681. if (!dataChanged)
  682. {
  683. dataChanged = recording.IsSeries != info.IsSeries;
  684. }
  685. recording.IsSeries = info.IsSeries;
  686. if (!item.ParentId.Equals(parentFolderId))
  687. {
  688. dataChanged = true;
  689. }
  690. item.ParentId = parentFolderId;
  691. if (!item.HasImage(ImageType.Primary))
  692. {
  693. if (!string.IsNullOrWhiteSpace(info.ImagePath))
  694. {
  695. item.SetImage(new ItemImageInfo
  696. {
  697. Path = info.ImagePath,
  698. Type = ImageType.Primary,
  699. IsPlaceholder = true
  700. }, 0);
  701. }
  702. else if (!string.IsNullOrWhiteSpace(info.ImageUrl))
  703. {
  704. item.SetImage(new ItemImageInfo
  705. {
  706. Path = info.ImageUrl,
  707. Type = ImageType.Primary,
  708. IsPlaceholder = true
  709. }, 0);
  710. }
  711. }
  712. var statusChanged = info.Status != recording.Status;
  713. recording.Status = info.Status;
  714. recording.ServiceName = serviceName;
  715. if (!string.IsNullOrEmpty(info.Path))
  716. {
  717. if (!dataChanged)
  718. {
  719. dataChanged = !string.Equals(item.Path, info.Path);
  720. }
  721. var fileInfo = _fileSystem.GetFileInfo(info.Path);
  722. recording.DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo);
  723. recording.DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo);
  724. item.Path = info.Path;
  725. }
  726. else if (!string.IsNullOrEmpty(info.Url))
  727. {
  728. if (!dataChanged)
  729. {
  730. dataChanged = !string.Equals(item.Path, info.Url);
  731. }
  732. item.Path = info.Url;
  733. }
  734. var metadataRefreshMode = MetadataRefreshMode.Default;
  735. if (isNew)
  736. {
  737. await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
  738. }
  739. else if (dataChanged || info.DateLastUpdated > recording.DateLastSaved || statusChanged)
  740. {
  741. metadataRefreshMode = MetadataRefreshMode.FullRefresh;
  742. await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false);
  743. }
  744. if (info.Status != RecordingStatus.InProgress)
  745. {
  746. _providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  747. {
  748. MetadataRefreshMode = metadataRefreshMode
  749. });
  750. }
  751. return item.Id;
  752. }
  753. public async Task<BaseItemDto> GetProgram(string id, CancellationToken cancellationToken, User user = null)
  754. {
  755. var program = GetInternalProgram(id);
  756. var dto = _dtoService.GetBaseItemDto(program, new DtoOptions(), user);
  757. var list = new List<Tuple<BaseItemDto, string, string>>();
  758. list.Add(new Tuple<BaseItemDto, string, string>(dto, program.ServiceName, program.ExternalId));
  759. await AddRecordingInfo(list, cancellationToken).ConfigureAwait(false);
  760. return dto;
  761. }
  762. public async Task<QueryResult<BaseItemDto>> GetPrograms(ProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  763. {
  764. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  765. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  766. if (query.SortBy.Length == 0)
  767. {
  768. // Unless something else was specified, order by start date to take advantage of a specialized index
  769. query.SortBy = new[] { ItemSortBy.StartDate };
  770. }
  771. var internalQuery = new InternalItemsQuery(user)
  772. {
  773. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  774. MinEndDate = query.MinEndDate,
  775. MinStartDate = query.MinStartDate,
  776. MaxEndDate = query.MaxEndDate,
  777. MaxStartDate = query.MaxStartDate,
  778. ChannelIds = query.ChannelIds,
  779. IsMovie = query.IsMovie,
  780. IsSports = query.IsSports,
  781. IsKids = query.IsKids,
  782. Genres = query.Genres,
  783. StartIndex = query.StartIndex,
  784. Limit = query.Limit,
  785. SortBy = query.SortBy,
  786. SortOrder = query.SortOrder ?? SortOrder.Ascending,
  787. EnableTotalRecordCount = query.EnableTotalRecordCount,
  788. TopParentIds = new[] { topFolder.Id.ToString("N") }
  789. };
  790. if (query.HasAired.HasValue)
  791. {
  792. if (query.HasAired.Value)
  793. {
  794. internalQuery.MaxEndDate = DateTime.UtcNow;
  795. }
  796. else
  797. {
  798. internalQuery.MinEndDate = DateTime.UtcNow;
  799. }
  800. }
  801. var queryResult = _libraryManager.QueryItems(internalQuery);
  802. RemoveFields(options);
  803. var returnArray = (await _dtoService.GetBaseItemDtos(queryResult.Items, options, user).ConfigureAwait(false)).ToArray();
  804. var result = new QueryResult<BaseItemDto>
  805. {
  806. Items = returnArray,
  807. TotalRecordCount = queryResult.TotalRecordCount
  808. };
  809. return result;
  810. }
  811. public async Task<QueryResult<LiveTvProgram>> GetRecommendedProgramsInternal(RecommendedProgramQuery query, CancellationToken cancellationToken)
  812. {
  813. var user = _userManager.GetUserById(query.UserId);
  814. var topFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  815. var internalQuery = new InternalItemsQuery(user)
  816. {
  817. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  818. IsAiring = query.IsAiring,
  819. IsMovie = query.IsMovie,
  820. IsSports = query.IsSports,
  821. IsKids = query.IsKids,
  822. EnableTotalRecordCount = query.EnableTotalRecordCount,
  823. SortBy = new[] { ItemSortBy.StartDate },
  824. TopParentIds = new[] { topFolder.Id.ToString("N") }
  825. };
  826. if (query.Limit.HasValue)
  827. {
  828. internalQuery.Limit = Math.Max(query.Limit.Value * 4, 200);
  829. }
  830. if (query.HasAired.HasValue)
  831. {
  832. if (query.HasAired.Value)
  833. {
  834. internalQuery.MaxEndDate = DateTime.UtcNow;
  835. }
  836. else
  837. {
  838. internalQuery.MinEndDate = DateTime.UtcNow;
  839. }
  840. }
  841. IEnumerable<LiveTvProgram> programs = _libraryManager.QueryItems(internalQuery).Items.Cast<LiveTvProgram>();
  842. var programList = programs.ToList();
  843. var factorChannelWatchCount = (query.IsAiring ?? false) || (query.IsKids ?? false) || (query.IsSports ?? false) || (query.IsMovie ?? false);
  844. programs = programList.OrderBy(i => i.HasImage(ImageType.Primary) ? 0 : 1)
  845. .ThenByDescending(i => GetRecommendationScore(i, user.Id, factorChannelWatchCount))
  846. .ThenBy(i => i.StartDate);
  847. if (query.Limit.HasValue)
  848. {
  849. programs = programs.Take(query.Limit.Value);
  850. }
  851. programList = programs.ToList();
  852. var returnArray = programList.ToArray();
  853. var result = new QueryResult<LiveTvProgram>
  854. {
  855. Items = returnArray,
  856. TotalRecordCount = returnArray.Length
  857. };
  858. return result;
  859. }
  860. public async Task<QueryResult<BaseItemDto>> GetRecommendedPrograms(RecommendedProgramQuery query, DtoOptions options, CancellationToken cancellationToken)
  861. {
  862. var internalResult = await GetRecommendedProgramsInternal(query, cancellationToken).ConfigureAwait(false);
  863. var user = _userManager.GetUserById(query.UserId);
  864. RemoveFields(options);
  865. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
  866. var result = new QueryResult<BaseItemDto>
  867. {
  868. Items = returnArray,
  869. TotalRecordCount = internalResult.TotalRecordCount
  870. };
  871. return result;
  872. }
  873. private int GetRecommendationScore(LiveTvProgram program, Guid userId, bool factorChannelWatchCount)
  874. {
  875. var score = 0;
  876. if (program.IsLive)
  877. {
  878. score++;
  879. }
  880. if (program.IsSeries && !program.IsRepeat)
  881. {
  882. score++;
  883. }
  884. var channel = GetInternalChannel(program.ChannelId);
  885. var channelUserdata = _userDataManager.GetUserData(userId, channel);
  886. if (channelUserdata.Likes ?? false)
  887. {
  888. score += 2;
  889. }
  890. else if (!(channelUserdata.Likes ?? true))
  891. {
  892. score -= 2;
  893. }
  894. if (channelUserdata.IsFavorite)
  895. {
  896. score += 3;
  897. }
  898. if (factorChannelWatchCount)
  899. {
  900. score += channelUserdata.PlayCount;
  901. }
  902. return score;
  903. }
  904. private async Task AddRecordingInfo(IEnumerable<Tuple<BaseItemDto, string, string>> programs, CancellationToken cancellationToken)
  905. {
  906. var timers = new Dictionary<string, List<TimerInfo>>();
  907. foreach (var programTuple in programs)
  908. {
  909. var program = programTuple.Item1;
  910. var serviceName = programTuple.Item2;
  911. var externalProgramId = programTuple.Item3;
  912. if (string.IsNullOrWhiteSpace(serviceName))
  913. {
  914. continue;
  915. }
  916. List<TimerInfo> timerList;
  917. if (!timers.TryGetValue(serviceName, out timerList))
  918. {
  919. try
  920. {
  921. var tempTimers = await GetService(serviceName).GetTimersAsync(cancellationToken).ConfigureAwait(false);
  922. timers[serviceName] = timerList = tempTimers.ToList();
  923. }
  924. catch (Exception ex)
  925. {
  926. _logger.ErrorException("Error getting timer infos", ex);
  927. timers[serviceName] = timerList = new List<TimerInfo>();
  928. }
  929. }
  930. var timer = timerList.FirstOrDefault(i => string.Equals(i.ProgramId, externalProgramId, StringComparison.OrdinalIgnoreCase));
  931. if (timer != null)
  932. {
  933. program.TimerId = _tvDtoService.GetInternalTimerId(serviceName, timer.Id)
  934. .ToString("N");
  935. if (!string.IsNullOrEmpty(timer.SeriesTimerId))
  936. {
  937. program.SeriesTimerId = _tvDtoService.GetInternalSeriesTimerId(serviceName, timer.SeriesTimerId)
  938. .ToString("N");
  939. }
  940. }
  941. }
  942. }
  943. internal Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
  944. {
  945. return RefreshChannelsInternal(progress, cancellationToken);
  946. }
  947. private async Task RefreshChannelsInternal(IProgress<double> progress, CancellationToken cancellationToken)
  948. {
  949. EmbyTV.EmbyTV.Current.CreateRecordingFolders();
  950. var numComplete = 0;
  951. double progressPerService = _services.Count == 0
  952. ? 0
  953. : 1 / _services.Count;
  954. var newChannelIdList = new List<Guid>();
  955. var newProgramIdList = new List<Guid>();
  956. foreach (var service in _services)
  957. {
  958. cancellationToken.ThrowIfCancellationRequested();
  959. _logger.Debug("Refreshing guide from {0}", service.Name);
  960. try
  961. {
  962. var innerProgress = new ActionableProgress<double>();
  963. innerProgress.RegisterAction(p => progress.Report(p * progressPerService));
  964. var idList = await RefreshChannelsInternal(service, innerProgress, cancellationToken).ConfigureAwait(false);
  965. newChannelIdList.AddRange(idList.Item1);
  966. newProgramIdList.AddRange(idList.Item2);
  967. }
  968. catch (OperationCanceledException)
  969. {
  970. throw;
  971. }
  972. catch (Exception ex)
  973. {
  974. _logger.ErrorException("Error refreshing channels for service", ex);
  975. }
  976. numComplete++;
  977. double percent = numComplete;
  978. percent /= _services.Count;
  979. progress.Report(100 * percent);
  980. }
  981. await CleanDatabaseInternal(newChannelIdList, new[] { typeof(LiveTvChannel).Name }, progress, cancellationToken).ConfigureAwait(false);
  982. await CleanDatabaseInternal(newProgramIdList, new[] { typeof(LiveTvProgram).Name }, progress, cancellationToken).ConfigureAwait(false);
  983. var coreService = _services.OfType<EmbyTV.EmbyTV>().FirstOrDefault();
  984. if (coreService != null)
  985. {
  986. await coreService.RefreshSeriesTimers(cancellationToken, new Progress<double>()).ConfigureAwait(false);
  987. }
  988. // Load these now which will prefetch metadata
  989. var dtoOptions = new DtoOptions();
  990. dtoOptions.Fields.Remove(ItemFields.SyncInfo);
  991. dtoOptions.Fields.Remove(ItemFields.BasicSyncInfo);
  992. await GetRecordings(new RecordingQuery(), dtoOptions, cancellationToken).ConfigureAwait(false);
  993. progress.Report(100);
  994. }
  995. private async Task<Tuple<List<Guid>, List<Guid>>> RefreshChannelsInternal(ILiveTvService service, IProgress<double> progress, CancellationToken cancellationToken)
  996. {
  997. progress.Report(10);
  998. var allChannels = await GetChannels(service, cancellationToken).ConfigureAwait(false);
  999. var allChannelsList = allChannels.ToList();
  1000. var list = new List<LiveTvChannel>();
  1001. var numComplete = 0;
  1002. var parentFolder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1003. var parentFolderId = parentFolder.Id;
  1004. foreach (var channelInfo in allChannelsList)
  1005. {
  1006. cancellationToken.ThrowIfCancellationRequested();
  1007. try
  1008. {
  1009. var item = await GetChannel(channelInfo.Item2, channelInfo.Item1, parentFolderId, cancellationToken).ConfigureAwait(false);
  1010. list.Add(item);
  1011. }
  1012. catch (OperationCanceledException)
  1013. {
  1014. throw;
  1015. }
  1016. catch (Exception ex)
  1017. {
  1018. _logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Item2.Name);
  1019. }
  1020. numComplete++;
  1021. double percent = numComplete;
  1022. percent /= allChannelsList.Count;
  1023. progress.Report(5 * percent + 10);
  1024. }
  1025. progress.Report(15);
  1026. numComplete = 0;
  1027. var programs = new List<Guid>();
  1028. var channels = new List<Guid>();
  1029. var guideDays = GetGuideDays();
  1030. _logger.Info("Refreshing guide with {0} days of guide data", guideDays);
  1031. cancellationToken.ThrowIfCancellationRequested();
  1032. foreach (var currentChannel in list)
  1033. {
  1034. channels.Add(currentChannel.Id);
  1035. cancellationToken.ThrowIfCancellationRequested();
  1036. try
  1037. {
  1038. var start = DateTime.UtcNow.AddHours(-1);
  1039. var end = start.AddDays(guideDays);
  1040. var channelPrograms = await service.GetProgramsAsync(currentChannel.ExternalId, start, end, cancellationToken).ConfigureAwait(false);
  1041. foreach (var program in channelPrograms)
  1042. {
  1043. var programItem = await GetProgram(program, currentChannel, currentChannel.ChannelType, service.Name, cancellationToken).ConfigureAwait(false);
  1044. programs.Add(programItem.Id);
  1045. }
  1046. }
  1047. catch (OperationCanceledException)
  1048. {
  1049. throw;
  1050. }
  1051. catch (Exception ex)
  1052. {
  1053. _logger.ErrorException("Error getting programs for channel {0}", ex, currentChannel.Name);
  1054. }
  1055. numComplete++;
  1056. double percent = numComplete;
  1057. percent /= allChannelsList.Count;
  1058. progress.Report(80 * percent + 10);
  1059. }
  1060. progress.Report(100);
  1061. return new Tuple<List<Guid>, List<Guid>>(channels, programs);
  1062. }
  1063. private async Task CleanDatabaseInternal(List<Guid> currentIdList, string[] validTypes, IProgress<double> progress, CancellationToken cancellationToken)
  1064. {
  1065. var list = _itemRepo.GetItemIdsList(new InternalItemsQuery
  1066. {
  1067. IncludeItemTypes = validTypes
  1068. }).ToList();
  1069. var numComplete = 0;
  1070. foreach (var itemId in list)
  1071. {
  1072. cancellationToken.ThrowIfCancellationRequested();
  1073. if (itemId == Guid.Empty)
  1074. {
  1075. // Somehow some invalid data got into the db. It probably predates the boundary checking
  1076. continue;
  1077. }
  1078. if (!currentIdList.Contains(itemId))
  1079. {
  1080. var item = _libraryManager.GetItemById(itemId);
  1081. if (item != null)
  1082. {
  1083. await _libraryManager.DeleteItem(item, new DeleteOptions
  1084. {
  1085. DeleteFileLocation = false
  1086. }).ConfigureAwait(false);
  1087. }
  1088. }
  1089. numComplete++;
  1090. double percent = numComplete;
  1091. percent /= list.Count;
  1092. progress.Report(100 * percent);
  1093. }
  1094. }
  1095. private const int MaxGuideDays = 14;
  1096. private double GetGuideDays()
  1097. {
  1098. var config = GetConfiguration();
  1099. if (config.GuideDays.HasValue)
  1100. {
  1101. return Math.Max(1, Math.Min(config.GuideDays.Value, MaxGuideDays));
  1102. }
  1103. return 7;
  1104. }
  1105. private async Task<IEnumerable<Tuple<string, ChannelInfo>>> GetChannels(ILiveTvService service, CancellationToken cancellationToken)
  1106. {
  1107. var channels = await service.GetChannelsAsync(cancellationToken).ConfigureAwait(false);
  1108. return channels.Select(i => new Tuple<string, ChannelInfo>(service.Name, i));
  1109. }
  1110. private DateTime _lastRecordingRefreshTime;
  1111. private async Task RefreshRecordings(CancellationToken cancellationToken)
  1112. {
  1113. const int cacheMinutes = 5;
  1114. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1115. {
  1116. return;
  1117. }
  1118. await _refreshRecordingsLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1119. try
  1120. {
  1121. if ((DateTime.UtcNow - _lastRecordingRefreshTime).TotalMinutes < cacheMinutes)
  1122. {
  1123. return;
  1124. }
  1125. var tasks = _services.Select(async i =>
  1126. {
  1127. try
  1128. {
  1129. var recs = await i.GetRecordingsAsync(cancellationToken).ConfigureAwait(false);
  1130. return recs.Select(r => new Tuple<RecordingInfo, ILiveTvService>(r, i));
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. _logger.ErrorException("Error getting recordings", ex);
  1135. return new List<Tuple<RecordingInfo, ILiveTvService>>();
  1136. }
  1137. });
  1138. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1139. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  1140. var parentFolderId = folder.Id;
  1141. var recordingTasks = results.SelectMany(i => i.ToList()).Select(i => CreateRecordingRecord(i.Item1, i.Item2.Name, parentFolderId, cancellationToken));
  1142. var idList = await Task.WhenAll(recordingTasks).ConfigureAwait(false);
  1143. await CleanDatabaseInternal(idList.ToList(), new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }, new Progress<double>(), cancellationToken).ConfigureAwait(false);
  1144. _lastRecordingRefreshTime = DateTime.UtcNow;
  1145. }
  1146. finally
  1147. {
  1148. _refreshRecordingsLock.Release();
  1149. }
  1150. }
  1151. private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, User user)
  1152. {
  1153. if (user == null || (query.IsInProgress ?? false))
  1154. {
  1155. return new QueryResult<BaseItem>();
  1156. }
  1157. var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
  1158. .SelectMany(i => i.Locations)
  1159. .Distinct(StringComparer.OrdinalIgnoreCase)
  1160. .Select(i => _libraryManager.FindByPath(i, true))
  1161. .Where(i => i != null)
  1162. .Where(i => i.IsVisibleStandalone(user))
  1163. .ToList();
  1164. if (folders.Count == 0)
  1165. {
  1166. return new QueryResult<BaseItem>();
  1167. }
  1168. var includeItemTypes = new List<string>();
  1169. var excludeItemTypes = new List<string>();
  1170. if (query.IsMovie.HasValue)
  1171. {
  1172. if (query.IsMovie.Value)
  1173. {
  1174. includeItemTypes.Add(typeof (Movie).Name);
  1175. }
  1176. else
  1177. {
  1178. excludeItemTypes.Add(typeof(Movie).Name);
  1179. }
  1180. }
  1181. if (query.IsSeries.HasValue)
  1182. {
  1183. if (query.IsSeries.Value)
  1184. {
  1185. includeItemTypes.Add(typeof(Episode).Name);
  1186. }
  1187. else
  1188. {
  1189. excludeItemTypes.Add(typeof(Episode).Name);
  1190. }
  1191. }
  1192. return _libraryManager.GetItemsResult(new InternalItemsQuery(user)
  1193. {
  1194. MediaTypes = new[] { MediaType.Video },
  1195. Recursive = true,
  1196. AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(),
  1197. IsFolder = false,
  1198. ExcludeLocationTypes = new[] { LocationType.Virtual },
  1199. Limit = Math.Min(200, query.Limit ?? int.MaxValue),
  1200. SortBy = new[] { ItemSortBy.DateCreated },
  1201. SortOrder = SortOrder.Descending,
  1202. EnableTotalRecordCount = query.EnableTotalRecordCount,
  1203. IncludeItemTypes = includeItemTypes.ToArray(),
  1204. ExcludeItemTypes = excludeItemTypes.ToArray()
  1205. });
  1206. }
  1207. public async Task<QueryResult<BaseItem>> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken)
  1208. {
  1209. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1210. if (user != null && !IsLiveTvEnabled(user))
  1211. {
  1212. return new QueryResult<BaseItem>();
  1213. }
  1214. if (_services.Count == 1)
  1215. {
  1216. return GetEmbyRecordings(query, user);
  1217. }
  1218. await RefreshRecordings(cancellationToken).ConfigureAwait(false);
  1219. var internalQuery = new InternalItemsQuery(user)
  1220. {
  1221. IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name }
  1222. };
  1223. if (!string.IsNullOrEmpty(query.ChannelId))
  1224. {
  1225. internalQuery.ChannelIds = new[] { query.ChannelId };
  1226. }
  1227. var queryResult = _libraryManager.GetItemList(internalQuery);
  1228. IEnumerable<ILiveTvRecording> recordings = queryResult.Cast<ILiveTvRecording>();
  1229. if (!string.IsNullOrWhiteSpace(query.Id))
  1230. {
  1231. var guid = new Guid(query.Id);
  1232. recordings = recordings
  1233. .Where(i => i.Id == guid);
  1234. }
  1235. if (!string.IsNullOrWhiteSpace(query.GroupId))
  1236. {
  1237. var guid = new Guid(query.GroupId);
  1238. recordings = recordings.Where(i => GetRecordingGroupIds(i).Contains(guid));
  1239. }
  1240. if (query.IsInProgress.HasValue)
  1241. {
  1242. var val = query.IsInProgress.Value;
  1243. recordings = recordings.Where(i => i.Status == RecordingStatus.InProgress == val);
  1244. }
  1245. if (query.Status.HasValue)
  1246. {
  1247. var val = query.Status.Value;
  1248. recordings = recordings.Where(i => i.Status == val);
  1249. }
  1250. if (query.IsMovie.HasValue)
  1251. {
  1252. var val = query.IsMovie.Value;
  1253. recordings = recordings.Where(i => i.IsMovie == val);
  1254. }
  1255. if (query.IsSeries.HasValue)
  1256. {
  1257. var val = query.IsSeries.Value;
  1258. recordings = recordings.Where(i => i.IsSeries == val);
  1259. }
  1260. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1261. {
  1262. var guid = new Guid(query.SeriesTimerId);
  1263. recordings = recordings
  1264. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.ServiceName, i.SeriesTimerId) == guid);
  1265. }
  1266. recordings = recordings.OrderByDescending(i => i.StartDate);
  1267. var entityList = recordings.ToList();
  1268. IEnumerable<ILiveTvRecording> entities = entityList;
  1269. if (query.StartIndex.HasValue)
  1270. {
  1271. entities = entities.Skip(query.StartIndex.Value);
  1272. }
  1273. if (query.Limit.HasValue)
  1274. {
  1275. entities = entities.Take(query.Limit.Value);
  1276. }
  1277. return new QueryResult<BaseItem>
  1278. {
  1279. Items = entities.Cast<BaseItem>().ToArray(),
  1280. TotalRecordCount = entityList.Count
  1281. };
  1282. }
  1283. public async Task AddInfoToProgramDto(List<Tuple<BaseItem, BaseItemDto>> tuples, List<ItemFields> fields, User user = null)
  1284. {
  1285. var recordingTuples = new List<Tuple<BaseItemDto, string, string>>();
  1286. foreach (var tuple in tuples)
  1287. {
  1288. var program = (LiveTvProgram)tuple.Item1;
  1289. var dto = tuple.Item2;
  1290. dto.StartDate = program.StartDate;
  1291. dto.EpisodeTitle = program.EpisodeTitle;
  1292. if (program.IsRepeat)
  1293. {
  1294. dto.IsRepeat = program.IsRepeat;
  1295. }
  1296. if (program.IsMovie)
  1297. {
  1298. dto.IsMovie = program.IsMovie;
  1299. }
  1300. if (program.IsSeries)
  1301. {
  1302. dto.IsSeries = program.IsSeries;
  1303. }
  1304. if (program.IsSports)
  1305. {
  1306. dto.IsSports = program.IsSports;
  1307. }
  1308. if (program.IsLive)
  1309. {
  1310. dto.IsLive = program.IsLive;
  1311. }
  1312. if (program.IsNews)
  1313. {
  1314. dto.IsNews = program.IsNews;
  1315. }
  1316. if (program.IsKids)
  1317. {
  1318. dto.IsKids = program.IsKids;
  1319. }
  1320. if (program.IsPremiere)
  1321. {
  1322. dto.IsPremiere = program.IsPremiere;
  1323. }
  1324. if (fields.Contains(ItemFields.ChannelInfo))
  1325. {
  1326. var channel = GetInternalChannel(program.ChannelId);
  1327. if (channel != null)
  1328. {
  1329. dto.ChannelName = channel.Name;
  1330. dto.MediaType = channel.MediaType;
  1331. dto.ChannelNumber = channel.Number;
  1332. if (channel.HasImage(ImageType.Primary))
  1333. {
  1334. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1335. }
  1336. }
  1337. }
  1338. var service = GetService(program);
  1339. var serviceName = service == null ? null : service.Name;
  1340. if (fields.Contains(ItemFields.ServiceName))
  1341. {
  1342. dto.ServiceName = serviceName;
  1343. }
  1344. recordingTuples.Add(new Tuple<BaseItemDto, string, string>(dto, serviceName, program.ExternalId));
  1345. }
  1346. await AddRecordingInfo(recordingTuples, CancellationToken.None).ConfigureAwait(false);
  1347. }
  1348. public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null)
  1349. {
  1350. var recording = (ILiveTvRecording)item;
  1351. var service = GetService(recording);
  1352. var channel = string.IsNullOrWhiteSpace(recording.ChannelId) ? null : GetInternalChannel(recording.ChannelId);
  1353. var info = recording;
  1354. dto.SeriesTimerId = string.IsNullOrEmpty(info.SeriesTimerId)
  1355. ? null
  1356. : _tvDtoService.GetInternalSeriesTimerId(service.Name, info.SeriesTimerId).ToString("N");
  1357. dto.StartDate = info.StartDate;
  1358. dto.RecordingStatus = info.Status;
  1359. dto.IsRepeat = info.IsRepeat;
  1360. dto.EpisodeTitle = info.EpisodeTitle;
  1361. dto.IsMovie = info.IsMovie;
  1362. dto.IsSeries = info.IsSeries;
  1363. dto.IsSports = info.IsSports;
  1364. dto.IsLive = info.IsLive;
  1365. dto.IsNews = info.IsNews;
  1366. dto.IsKids = info.IsKids;
  1367. dto.IsPremiere = info.IsPremiere;
  1368. dto.CanDelete = user == null
  1369. ? recording.CanDelete()
  1370. : recording.CanDelete(user);
  1371. if (dto.MediaSources == null)
  1372. {
  1373. dto.MediaSources = recording.GetMediaSources(true).ToList();
  1374. }
  1375. if (dto.MediaStreams == null)
  1376. {
  1377. dto.MediaStreams = dto.MediaSources.SelectMany(i => i.MediaStreams).ToList();
  1378. }
  1379. if (info.Status == RecordingStatus.InProgress && info.EndDate.HasValue)
  1380. {
  1381. var now = DateTime.UtcNow.Ticks;
  1382. var start = info.StartDate.Ticks;
  1383. var end = info.EndDate.Value.Ticks;
  1384. var pct = now - start;
  1385. pct /= end;
  1386. pct *= 100;
  1387. dto.CompletionPercentage = pct;
  1388. }
  1389. if (channel != null)
  1390. {
  1391. dto.ChannelName = channel.Name;
  1392. if (channel.HasImage(ImageType.Primary))
  1393. {
  1394. dto.ChannelPrimaryImageTag = _tvDtoService.GetImageTag(channel);
  1395. }
  1396. }
  1397. }
  1398. public async Task<QueryResult<BaseItemDto>> GetRecordings(RecordingQuery query, DtoOptions options, CancellationToken cancellationToken)
  1399. {
  1400. var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId);
  1401. var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false);
  1402. RemoveFields(options);
  1403. var returnArray = (await _dtoService.GetBaseItemDtos(internalResult.Items, options, user).ConfigureAwait(false)).ToArray();
  1404. return new QueryResult<BaseItemDto>
  1405. {
  1406. Items = returnArray,
  1407. TotalRecordCount = internalResult.TotalRecordCount
  1408. };
  1409. }
  1410. public async Task<QueryResult<TimerInfoDto>> GetTimers(TimerQuery query, CancellationToken cancellationToken)
  1411. {
  1412. var tasks = _services.Select(async i =>
  1413. {
  1414. try
  1415. {
  1416. var recs = await i.GetTimersAsync(cancellationToken).ConfigureAwait(false);
  1417. return recs.Select(r => new Tuple<TimerInfo, ILiveTvService>(r, i));
  1418. }
  1419. catch (Exception ex)
  1420. {
  1421. _logger.ErrorException("Error getting recordings", ex);
  1422. return new List<Tuple<TimerInfo, ILiveTvService>>();
  1423. }
  1424. });
  1425. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1426. var timers = results.SelectMany(i => i.ToList());
  1427. if (query.IsActive.HasValue)
  1428. {
  1429. if (query.IsActive.Value)
  1430. {
  1431. timers = timers.Where(i => i.Item1.Status == RecordingStatus.InProgress);
  1432. }
  1433. else
  1434. {
  1435. timers = timers.Where(i => i.Item1.Status != RecordingStatus.InProgress);
  1436. }
  1437. }
  1438. if (!string.IsNullOrEmpty(query.ChannelId))
  1439. {
  1440. var guid = new Guid(query.ChannelId);
  1441. timers = timers.Where(i => guid == _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1442. }
  1443. if (!string.IsNullOrEmpty(query.SeriesTimerId))
  1444. {
  1445. var guid = new Guid(query.SeriesTimerId);
  1446. timers = timers
  1447. .Where(i => _tvDtoService.GetInternalSeriesTimerId(i.Item2.Name, i.Item1.SeriesTimerId) == guid);
  1448. }
  1449. var returnList = new List<TimerInfoDto>();
  1450. foreach (var i in timers)
  1451. {
  1452. var program = string.IsNullOrEmpty(i.Item1.ProgramId) ?
  1453. null :
  1454. GetInternalProgram(_tvDtoService.GetInternalProgramId(i.Item2.Name, i.Item1.ProgramId).ToString("N"));
  1455. var channel = string.IsNullOrEmpty(i.Item1.ChannelId) ? null : GetInternalChannel(_tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId));
  1456. returnList.Add(_tvDtoService.GetTimerInfoDto(i.Item1, i.Item2, program, channel));
  1457. }
  1458. var returnArray = returnList
  1459. .OrderBy(i => i.StartDate)
  1460. .ToArray();
  1461. return new QueryResult<TimerInfoDto>
  1462. {
  1463. Items = returnArray,
  1464. TotalRecordCount = returnArray.Length
  1465. };
  1466. }
  1467. public Task OnRecordingFileDeleted(BaseItem recording)
  1468. {
  1469. var service = GetService(recording);
  1470. if (service is EmbyTV.EmbyTV)
  1471. {
  1472. // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says
  1473. return service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None);
  1474. }
  1475. return Task.FromResult(true);
  1476. }
  1477. public async Task DeleteRecording(string recordingId)
  1478. {
  1479. var recording = await GetInternalRecording(recordingId, CancellationToken.None).ConfigureAwait(false);
  1480. if (recording == null)
  1481. {
  1482. throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId));
  1483. }
  1484. await DeleteRecording((BaseItem)recording).ConfigureAwait(false);
  1485. }
  1486. public async Task DeleteRecording(BaseItem recording)
  1487. {
  1488. var service = GetService(recording.ServiceName);
  1489. try
  1490. {
  1491. await service.DeleteRecordingAsync(recording.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1492. }
  1493. catch (ResourceNotFoundException)
  1494. {
  1495. }
  1496. _lastRecordingRefreshTime = DateTime.MinValue;
  1497. // This is the responsibility of the live tv service
  1498. await _libraryManager.DeleteItem((BaseItem)recording, new DeleteOptions
  1499. {
  1500. DeleteFileLocation = false
  1501. }).ConfigureAwait(false);
  1502. _lastRecordingRefreshTime = DateTime.MinValue;
  1503. }
  1504. public async Task CancelTimer(string id)
  1505. {
  1506. var timer = await GetTimer(id, CancellationToken.None).ConfigureAwait(false);
  1507. if (timer == null)
  1508. {
  1509. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1510. }
  1511. var service = GetService(timer.ServiceName);
  1512. await service.CancelTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1513. _lastRecordingRefreshTime = DateTime.MinValue;
  1514. EventHelper.QueueEventIfNotNull(TimerCancelled, this, new GenericEventArgs<TimerEventInfo>
  1515. {
  1516. Argument = new TimerEventInfo
  1517. {
  1518. Id = id
  1519. }
  1520. }, _logger);
  1521. }
  1522. public async Task CancelSeriesTimer(string id)
  1523. {
  1524. var timer = await GetSeriesTimer(id, CancellationToken.None).ConfigureAwait(false);
  1525. if (timer == null)
  1526. {
  1527. throw new ResourceNotFoundException(string.Format("Timer with Id {0} not found", id));
  1528. }
  1529. var service = GetService(timer.ServiceName);
  1530. await service.CancelSeriesTimerAsync(timer.ExternalId, CancellationToken.None).ConfigureAwait(false);
  1531. _lastRecordingRefreshTime = DateTime.MinValue;
  1532. EventHelper.QueueEventIfNotNull(SeriesTimerCancelled, this, new GenericEventArgs<TimerEventInfo>
  1533. {
  1534. Argument = new TimerEventInfo
  1535. {
  1536. Id = id
  1537. }
  1538. }, _logger);
  1539. }
  1540. public async Task<BaseItemDto> GetRecording(string id, DtoOptions options, CancellationToken cancellationToken, User user = null)
  1541. {
  1542. var item = await GetInternalRecording(id, cancellationToken).ConfigureAwait(false);
  1543. if (item == null)
  1544. {
  1545. return null;
  1546. }
  1547. return _dtoService.GetBaseItemDto((BaseItem)item, options, user);
  1548. }
  1549. public async Task<TimerInfoDto> GetTimer(string id, CancellationToken cancellationToken)
  1550. {
  1551. var results = await GetTimers(new TimerQuery(), cancellationToken).ConfigureAwait(false);
  1552. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1553. }
  1554. public async Task<SeriesTimerInfoDto> GetSeriesTimer(string id, CancellationToken cancellationToken)
  1555. {
  1556. var results = await GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false);
  1557. return results.Items.FirstOrDefault(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  1558. }
  1559. public async Task<QueryResult<SeriesTimerInfoDto>> GetSeriesTimers(SeriesTimerQuery query, CancellationToken cancellationToken)
  1560. {
  1561. var tasks = _services.Select(async i =>
  1562. {
  1563. try
  1564. {
  1565. var recs = await i.GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  1566. return recs.Select(r => new Tuple<SeriesTimerInfo, ILiveTvService>(r, i));
  1567. }
  1568. catch (Exception ex)
  1569. {
  1570. _logger.ErrorException("Error getting recordings", ex);
  1571. return new List<Tuple<SeriesTimerInfo, ILiveTvService>>();
  1572. }
  1573. });
  1574. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  1575. var timers = results.SelectMany(i => i.ToList());
  1576. if (string.Equals(query.SortBy, "Priority", StringComparison.OrdinalIgnoreCase))
  1577. {
  1578. timers = query.SortOrder == SortOrder.Descending ?
  1579. timers.OrderBy(i => i.Item1.Priority).ThenByStringDescending(i => i.Item1.Name) :
  1580. timers.OrderByDescending(i => i.Item1.Priority).ThenByString(i => i.Item1.Name);
  1581. }
  1582. else
  1583. {
  1584. timers = query.SortOrder == SortOrder.Descending ?
  1585. timers.OrderByStringDescending(i => i.Item1.Name) :
  1586. timers.OrderByString(i => i.Item1.Name);
  1587. }
  1588. var returnArray = timers
  1589. .Select(i =>
  1590. {
  1591. string channelName = null;
  1592. if (!string.IsNullOrEmpty(i.Item1.ChannelId))
  1593. {
  1594. var internalChannelId = _tvDtoService.GetInternalChannelId(i.Item2.Name, i.Item1.ChannelId);
  1595. var channel = GetInternalChannel(internalChannelId);
  1596. channelName = channel == null ? null : channel.Name;
  1597. }
  1598. return _tvDtoService.GetSeriesTimerInfoDto(i.Item1, i.Item2, channelName);
  1599. })
  1600. .ToArray();
  1601. return new QueryResult<SeriesTimerInfoDto>
  1602. {
  1603. Items = returnArray,
  1604. TotalRecordCount = returnArray.Length
  1605. };
  1606. }
  1607. public void AddChannelInfo(List<Tuple<BaseItemDto, LiveTvChannel>> tuples, DtoOptions options, User user)
  1608. {
  1609. var now = DateTime.UtcNow;
  1610. var channelIds = tuples.Select(i => i.Item2.Id.ToString("N")).Distinct().ToArray();
  1611. var programs = options.AddCurrentProgram ? _libraryManager.GetItemList(new InternalItemsQuery(user)
  1612. {
  1613. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1614. ChannelIds = channelIds,
  1615. MaxStartDate = now,
  1616. MinEndDate = now,
  1617. Limit = channelIds.Length,
  1618. SortBy = new[] { "StartDate" },
  1619. TopParentIds = new[] { GetInternalLiveTvFolder(CancellationToken.None).Result.Id.ToString("N") }
  1620. }).ToList() : new List<BaseItem>();
  1621. RemoveFields(options);
  1622. foreach (var tuple in tuples)
  1623. {
  1624. var dto = tuple.Item1;
  1625. var channel = tuple.Item2;
  1626. dto.Number = channel.Number;
  1627. dto.ChannelNumber = channel.Number;
  1628. dto.ChannelType = channel.ChannelType;
  1629. dto.ServiceName = channel.ServiceName;
  1630. if (options.Fields.Contains(ItemFields.MediaSources))
  1631. {
  1632. dto.MediaSources = channel.GetMediaSources(true).ToList();
  1633. }
  1634. if (options.AddCurrentProgram)
  1635. {
  1636. var channelIdString = channel.Id.ToString("N");
  1637. var currentProgram = programs.FirstOrDefault(i => string.Equals(i.ChannelId, channelIdString));
  1638. if (currentProgram != null)
  1639. {
  1640. dto.CurrentProgram = _dtoService.GetBaseItemDto(currentProgram, options, user);
  1641. }
  1642. }
  1643. }
  1644. }
  1645. private async Task<Tuple<SeriesTimerInfo, ILiveTvService>> GetNewTimerDefaultsInternal(CancellationToken cancellationToken, LiveTvProgram program = null)
  1646. {
  1647. var service = program != null && !string.IsNullOrWhiteSpace(program.ServiceName) ?
  1648. GetService(program) :
  1649. _services.FirstOrDefault();
  1650. ProgramInfo programInfo = null;
  1651. if (program != null)
  1652. {
  1653. var channel = GetInternalChannel(program.ChannelId);
  1654. programInfo = new ProgramInfo
  1655. {
  1656. Audio = program.Audio,
  1657. ChannelId = channel.ExternalId,
  1658. CommunityRating = program.CommunityRating,
  1659. EndDate = program.EndDate ?? DateTime.MinValue,
  1660. EpisodeTitle = program.EpisodeTitle,
  1661. Genres = program.Genres,
  1662. Id = program.ExternalId,
  1663. IsHD = program.IsHD,
  1664. IsKids = program.IsKids,
  1665. IsLive = program.IsLive,
  1666. IsMovie = program.IsMovie,
  1667. IsNews = program.IsNews,
  1668. IsPremiere = program.IsPremiere,
  1669. IsRepeat = program.IsRepeat,
  1670. IsSeries = program.IsSeries,
  1671. IsSports = program.IsSports,
  1672. OriginalAirDate = program.PremiereDate,
  1673. Overview = program.Overview,
  1674. StartDate = program.StartDate,
  1675. //ImagePath = program.ExternalImagePath,
  1676. Name = program.Name,
  1677. OfficialRating = program.OfficialRating
  1678. };
  1679. }
  1680. var info = await service.GetNewTimerDefaultsAsync(cancellationToken, programInfo).ConfigureAwait(false);
  1681. info.Id = null;
  1682. return new Tuple<SeriesTimerInfo, ILiveTvService>(info, service);
  1683. }
  1684. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(CancellationToken cancellationToken)
  1685. {
  1686. var info = await GetNewTimerDefaultsInternal(cancellationToken).ConfigureAwait(false);
  1687. var obj = _tvDtoService.GetSeriesTimerInfoDto(info.Item1, info.Item2, null);
  1688. return obj;
  1689. }
  1690. public async Task<SeriesTimerInfoDto> GetNewTimerDefaults(string programId, CancellationToken cancellationToken)
  1691. {
  1692. var program = GetInternalProgram(programId);
  1693. var programDto = await GetProgram(programId, cancellationToken).ConfigureAwait(false);
  1694. var defaults = await GetNewTimerDefaultsInternal(cancellationToken, program).ConfigureAwait(false);
  1695. var info = _tvDtoService.GetSeriesTimerInfoDto(defaults.Item1, defaults.Item2, null);
  1696. info.Days = defaults.Item1.Days;
  1697. info.DayPattern = _tvDtoService.GetDayPattern(info.Days);
  1698. info.Name = program.Name;
  1699. info.ChannelId = programDto.ChannelId;
  1700. info.ChannelName = programDto.ChannelName;
  1701. info.StartDate = program.StartDate;
  1702. info.Name = program.Name;
  1703. info.Overview = program.Overview;
  1704. info.ProgramId = programDto.Id;
  1705. info.ExternalProgramId = program.ExternalId;
  1706. if (program.EndDate.HasValue)
  1707. {
  1708. info.EndDate = program.EndDate.Value;
  1709. }
  1710. return info;
  1711. }
  1712. public async Task CreateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1713. {
  1714. var service = GetService(timer.ServiceName);
  1715. var info = await _tvDtoService.GetTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1716. // Set priority from default values
  1717. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1718. info.Priority = defaultValues.Priority;
  1719. string newTimerId = null;
  1720. var supportsNewTimerIds = service as ISupportsNewTimerIds;
  1721. if (supportsNewTimerIds != null)
  1722. {
  1723. newTimerId = await supportsNewTimerIds.CreateTimer(info, cancellationToken).ConfigureAwait(false);
  1724. newTimerId = _tvDtoService.GetInternalTimerId(timer.ServiceName, newTimerId).ToString("N");
  1725. }
  1726. else
  1727. {
  1728. await service.CreateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1729. }
  1730. _lastRecordingRefreshTime = DateTime.MinValue;
  1731. _logger.Info("New recording scheduled");
  1732. EventHelper.QueueEventIfNotNull(TimerCreated, this, new GenericEventArgs<TimerEventInfo>
  1733. {
  1734. Argument = new TimerEventInfo
  1735. {
  1736. ProgramId = _tvDtoService.GetInternalProgramId(timer.ServiceName, info.ProgramId).ToString("N"),
  1737. Id = newTimerId
  1738. }
  1739. }, _logger);
  1740. }
  1741. public async Task CreateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1742. {
  1743. var service = GetService(timer.ServiceName);
  1744. var info = await _tvDtoService.GetSeriesTimerInfo(timer, true, this, cancellationToken).ConfigureAwait(false);
  1745. // Set priority from default values
  1746. var defaultValues = await service.GetNewTimerDefaultsAsync(cancellationToken).ConfigureAwait(false);
  1747. info.Priority = defaultValues.Priority;
  1748. string newTimerId = null;
  1749. var supportsNewTimerIds = service as ISupportsNewTimerIds;
  1750. if (supportsNewTimerIds != null)
  1751. {
  1752. newTimerId = await supportsNewTimerIds.CreateSeriesTimer(info, cancellationToken).ConfigureAwait(false);
  1753. newTimerId = _tvDtoService.GetInternalSeriesTimerId(timer.ServiceName, newTimerId).ToString("N");
  1754. }
  1755. else
  1756. {
  1757. await service.CreateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1758. }
  1759. _lastRecordingRefreshTime = DateTime.MinValue;
  1760. EventHelper.QueueEventIfNotNull(SeriesTimerCreated, this, new GenericEventArgs<TimerEventInfo>
  1761. {
  1762. Argument = new TimerEventInfo
  1763. {
  1764. ProgramId = _tvDtoService.GetInternalProgramId(timer.ServiceName, info.ProgramId).ToString("N"),
  1765. Id = newTimerId
  1766. }
  1767. }, _logger);
  1768. }
  1769. public async Task UpdateTimer(TimerInfoDto timer, CancellationToken cancellationToken)
  1770. {
  1771. var info = await _tvDtoService.GetTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1772. var service = GetService(timer.ServiceName);
  1773. await service.UpdateTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1774. _lastRecordingRefreshTime = DateTime.MinValue;
  1775. }
  1776. public async Task UpdateSeriesTimer(SeriesTimerInfoDto timer, CancellationToken cancellationToken)
  1777. {
  1778. var info = await _tvDtoService.GetSeriesTimerInfo(timer, false, this, cancellationToken).ConfigureAwait(false);
  1779. var service = GetService(timer.ServiceName);
  1780. await service.UpdateSeriesTimerAsync(info, cancellationToken).ConfigureAwait(false);
  1781. _lastRecordingRefreshTime = DateTime.MinValue;
  1782. }
  1783. private IEnumerable<string> GetRecordingGroupNames(ILiveTvRecording recording)
  1784. {
  1785. var list = new List<string>();
  1786. if (recording.IsSeries)
  1787. {
  1788. list.Add(recording.Name);
  1789. }
  1790. if (recording.IsKids)
  1791. {
  1792. list.Add("Kids");
  1793. }
  1794. if (recording.IsMovie)
  1795. {
  1796. list.Add("Movies");
  1797. }
  1798. if (recording.IsNews)
  1799. {
  1800. list.Add("News");
  1801. }
  1802. if (recording.IsSports)
  1803. {
  1804. list.Add("Sports");
  1805. }
  1806. if (!recording.IsSports && !recording.IsNews && !recording.IsMovie && !recording.IsKids && !recording.IsSeries)
  1807. {
  1808. list.Add("Others");
  1809. }
  1810. return list;
  1811. }
  1812. private List<Guid> GetRecordingGroupIds(ILiveTvRecording recording)
  1813. {
  1814. return GetRecordingGroupNames(recording).Select(i => i.ToLower()
  1815. .GetMD5())
  1816. .ToList();
  1817. }
  1818. public async Task<QueryResult<BaseItemDto>> GetRecordingGroups(RecordingGroupQuery query, CancellationToken cancellationToken)
  1819. {
  1820. var recordingResult = await GetInternalRecordings(new RecordingQuery
  1821. {
  1822. UserId = query.UserId
  1823. }, cancellationToken).ConfigureAwait(false);
  1824. var recordings = recordingResult.Items.OfType<ILiveTvRecording>().ToList();
  1825. var groups = new List<BaseItemDto>();
  1826. var series = recordings
  1827. .Where(i => i.IsSeries)
  1828. .ToLookup(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1829. .ToList();
  1830. groups.AddRange(series.OrderByString(i => i.Key).Select(i => new BaseItemDto
  1831. {
  1832. Name = i.Key,
  1833. RecordingCount = i.Count()
  1834. }));
  1835. groups.Add(new BaseItemDto
  1836. {
  1837. Name = "Kids",
  1838. RecordingCount = recordings.Count(i => i.IsKids)
  1839. });
  1840. groups.Add(new BaseItemDto
  1841. {
  1842. Name = "Movies",
  1843. RecordingCount = recordings.Count(i => i.IsMovie)
  1844. });
  1845. groups.Add(new BaseItemDto
  1846. {
  1847. Name = "News",
  1848. RecordingCount = recordings.Count(i => i.IsNews)
  1849. });
  1850. groups.Add(new BaseItemDto
  1851. {
  1852. Name = "Sports",
  1853. RecordingCount = recordings.Count(i => i.IsSports)
  1854. });
  1855. groups.Add(new BaseItemDto
  1856. {
  1857. Name = "Others",
  1858. RecordingCount = recordings.Count(i => !i.IsSports && !i.IsNews && !i.IsMovie && !i.IsKids && !i.IsSeries)
  1859. });
  1860. groups = groups
  1861. .Where(i => i.RecordingCount > 0)
  1862. .ToList();
  1863. foreach (var group in groups)
  1864. {
  1865. group.Id = group.Name.ToLower().GetMD5().ToString("N");
  1866. }
  1867. return new QueryResult<BaseItemDto>
  1868. {
  1869. Items = groups.ToArray(),
  1870. TotalRecordCount = groups.Count
  1871. };
  1872. }
  1873. class LiveStreamData
  1874. {
  1875. internal MediaSourceInfo Info;
  1876. internal string ItemId;
  1877. internal bool IsChannel;
  1878. }
  1879. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1880. {
  1881. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1882. try
  1883. {
  1884. var parts = id.Split(new[] { '_' }, 2);
  1885. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  1886. if (service == null)
  1887. {
  1888. throw new ArgumentException("Service not found.");
  1889. }
  1890. id = parts[1];
  1891. LiveStreamData data;
  1892. _openStreams.TryRemove(id, out data);
  1893. _logger.Info("Closing live stream from {0}, stream Id: {1}", service.Name, id);
  1894. await service.CloseLiveStream(id, cancellationToken).ConfigureAwait(false);
  1895. }
  1896. catch (Exception ex)
  1897. {
  1898. _logger.ErrorException("Error closing live stream", ex);
  1899. throw;
  1900. }
  1901. finally
  1902. {
  1903. _liveStreamSemaphore.Release();
  1904. }
  1905. }
  1906. public GuideInfo GetGuideInfo()
  1907. {
  1908. var startDate = DateTime.UtcNow;
  1909. var endDate = startDate.AddDays(14);
  1910. return new GuideInfo
  1911. {
  1912. StartDate = startDate,
  1913. EndDate = endDate
  1914. };
  1915. }
  1916. /// <summary>
  1917. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1918. /// </summary>
  1919. public void Dispose()
  1920. {
  1921. Dispose(true);
  1922. }
  1923. private readonly object _disposeLock = new object();
  1924. private bool _isDisposed = false;
  1925. /// <summary>
  1926. /// Releases unmanaged and - optionally - managed resources.
  1927. /// </summary>
  1928. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1929. protected virtual void Dispose(bool dispose)
  1930. {
  1931. if (dispose)
  1932. {
  1933. _isDisposed = true;
  1934. lock (_disposeLock)
  1935. {
  1936. foreach (var stream in _openStreams.Values.ToList())
  1937. {
  1938. var task = CloseLiveStream(stream.Info.Id, CancellationToken.None);
  1939. Task.WaitAll(task);
  1940. }
  1941. _openStreams.Clear();
  1942. }
  1943. }
  1944. }
  1945. private async Task<IEnumerable<LiveTvServiceInfo>> GetServiceInfos(CancellationToken cancellationToken)
  1946. {
  1947. var tasks = Services.Select(i => GetServiceInfo(i, cancellationToken));
  1948. return await Task.WhenAll(tasks).ConfigureAwait(false);
  1949. }
  1950. private async Task<LiveTvServiceInfo> GetServiceInfo(ILiveTvService service, CancellationToken cancellationToken)
  1951. {
  1952. var info = new LiveTvServiceInfo
  1953. {
  1954. Name = service.Name
  1955. };
  1956. var tunerIdPrefix = service.GetType().FullName.GetMD5().ToString("N") + "_";
  1957. try
  1958. {
  1959. var statusInfo = await service.GetStatusInfoAsync(cancellationToken).ConfigureAwait(false);
  1960. info.Status = statusInfo.Status;
  1961. info.StatusMessage = statusInfo.StatusMessage;
  1962. info.Version = statusInfo.Version;
  1963. info.HasUpdateAvailable = statusInfo.HasUpdateAvailable;
  1964. info.HomePageUrl = service.HomePageUrl;
  1965. info.IsVisible = statusInfo.IsVisible;
  1966. info.Tuners = statusInfo.Tuners.Select(i =>
  1967. {
  1968. string channelName = null;
  1969. if (!string.IsNullOrEmpty(i.ChannelId))
  1970. {
  1971. var internalChannelId = _tvDtoService.GetInternalChannelId(service.Name, i.ChannelId);
  1972. var channel = GetInternalChannel(internalChannelId);
  1973. channelName = channel == null ? null : channel.Name;
  1974. }
  1975. var dto = _tvDtoService.GetTunerInfoDto(service.Name, i, channelName);
  1976. dto.Id = tunerIdPrefix + dto.Id;
  1977. return dto;
  1978. }).ToList();
  1979. }
  1980. catch (Exception ex)
  1981. {
  1982. _logger.ErrorException("Error getting service status info from {0}", ex, service.Name ?? string.Empty);
  1983. info.Status = LiveTvServiceStatus.Unavailable;
  1984. info.StatusMessage = ex.Message;
  1985. }
  1986. return info;
  1987. }
  1988. public async Task<LiveTvInfo> GetLiveTvInfo(CancellationToken cancellationToken)
  1989. {
  1990. var services = await GetServiceInfos(CancellationToken.None).ConfigureAwait(false);
  1991. var servicesList = services.ToList();
  1992. var info = new LiveTvInfo
  1993. {
  1994. Services = servicesList.ToList(),
  1995. IsEnabled = servicesList.Count > 0
  1996. };
  1997. info.EnabledUsers = _userManager.Users
  1998. .Where(IsLiveTvEnabled)
  1999. .Select(i => i.Id.ToString("N"))
  2000. .ToList();
  2001. return info;
  2002. }
  2003. private bool IsLiveTvEnabled(User user)
  2004. {
  2005. return user.Policy.EnableLiveTvAccess && (Services.Count > 1 || GetConfiguration().TunerHosts.Count(i => i.IsEnabled) > 0);
  2006. }
  2007. public IEnumerable<User> GetEnabledUsers()
  2008. {
  2009. return _userManager.Users
  2010. .Where(IsLiveTvEnabled);
  2011. }
  2012. /// <summary>
  2013. /// Resets the tuner.
  2014. /// </summary>
  2015. /// <param name="id">The identifier.</param>
  2016. /// <param name="cancellationToken">The cancellation token.</param>
  2017. /// <returns>Task.</returns>
  2018. public Task ResetTuner(string id, CancellationToken cancellationToken)
  2019. {
  2020. var parts = id.Split(new[] { '_' }, 2);
  2021. var service = _services.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), parts[0], StringComparison.OrdinalIgnoreCase));
  2022. if (service == null)
  2023. {
  2024. throw new ArgumentException("Service not found.");
  2025. }
  2026. return service.ResetTuner(parts[1], cancellationToken);
  2027. }
  2028. public async Task<BaseItemDto> GetLiveTvFolder(string userId, CancellationToken cancellationToken)
  2029. {
  2030. var user = string.IsNullOrEmpty(userId) ? null : _userManager.GetUserById(userId);
  2031. var folder = await GetInternalLiveTvFolder(cancellationToken).ConfigureAwait(false);
  2032. return _dtoService.GetBaseItemDto(folder, new DtoOptions(), user);
  2033. }
  2034. private void RemoveFields(DtoOptions options)
  2035. {
  2036. options.Fields.Remove(ItemFields.CanDelete);
  2037. options.Fields.Remove(ItemFields.CanDownload);
  2038. options.Fields.Remove(ItemFields.DisplayPreferencesId);
  2039. options.Fields.Remove(ItemFields.Etag);
  2040. }
  2041. public async Task<Folder> GetInternalLiveTvFolder(CancellationToken cancellationToken)
  2042. {
  2043. var name = _localization.GetLocalizedString("ViewTypeLiveTV");
  2044. return await _libraryManager.GetNamedView(name, CollectionType.LiveTv, name, cancellationToken).ConfigureAwait(false);
  2045. }
  2046. public async Task<TunerHostInfo> SaveTunerHost(TunerHostInfo info, bool dataSourceChanged = true)
  2047. {
  2048. info = (TunerHostInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(TunerHostInfo));
  2049. var provider = _tunerHosts.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2050. if (provider == null)
  2051. {
  2052. throw new ResourceNotFoundException();
  2053. }
  2054. var configurable = provider as IConfigurableTunerHost;
  2055. if (configurable != null)
  2056. {
  2057. await configurable.Validate(info).ConfigureAwait(false);
  2058. }
  2059. var config = GetConfiguration();
  2060. var index = config.TunerHosts.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2061. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2062. {
  2063. info.Id = Guid.NewGuid().ToString("N");
  2064. config.TunerHosts.Add(info);
  2065. }
  2066. else
  2067. {
  2068. config.TunerHosts[index] = info;
  2069. }
  2070. _config.SaveConfiguration("livetv", config);
  2071. if (dataSourceChanged)
  2072. {
  2073. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2074. }
  2075. return info;
  2076. }
  2077. public async Task<ListingsProviderInfo> SaveListingProvider(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  2078. {
  2079. info = (ListingsProviderInfo)_jsonSerializer.DeserializeFromString(_jsonSerializer.SerializeToString(info), typeof(ListingsProviderInfo));
  2080. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2081. if (provider == null)
  2082. {
  2083. throw new ResourceNotFoundException();
  2084. }
  2085. await provider.Validate(info, validateLogin, validateListings).ConfigureAwait(false);
  2086. var config = GetConfiguration();
  2087. var index = config.ListingProviders.FindIndex(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  2088. if (index == -1 || string.IsNullOrWhiteSpace(info.Id))
  2089. {
  2090. info.Id = Guid.NewGuid().ToString("N");
  2091. config.ListingProviders.Add(info);
  2092. }
  2093. else
  2094. {
  2095. config.ListingProviders[index] = info;
  2096. }
  2097. _config.SaveConfiguration("livetv", config);
  2098. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2099. return info;
  2100. }
  2101. public void DeleteListingsProvider(string id)
  2102. {
  2103. var config = GetConfiguration();
  2104. config.ListingProviders = config.ListingProviders.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToList();
  2105. _config.SaveConfiguration("livetv", config);
  2106. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2107. }
  2108. public async Task<TunerChannelMapping> SetChannelMapping(string providerId, string tunerChannelNumber, string providerChannelNumber)
  2109. {
  2110. var config = GetConfiguration();
  2111. var listingsProviderInfo = config.ListingProviders.First(i => string.Equals(providerId, i.Id, StringComparison.OrdinalIgnoreCase));
  2112. listingsProviderInfo.ChannelMappings = listingsProviderInfo.ChannelMappings.Where(i => !string.Equals(i.Name, tunerChannelNumber, StringComparison.OrdinalIgnoreCase)).ToArray();
  2113. if (!string.Equals(tunerChannelNumber, providerChannelNumber, StringComparison.OrdinalIgnoreCase))
  2114. {
  2115. var list = listingsProviderInfo.ChannelMappings.ToList();
  2116. list.Add(new NameValuePair
  2117. {
  2118. Name = tunerChannelNumber,
  2119. Value = providerChannelNumber
  2120. });
  2121. listingsProviderInfo.ChannelMappings = list.ToArray();
  2122. }
  2123. _config.SaveConfiguration("livetv", config);
  2124. var tunerChannels = await GetChannelsForListingsProvider(providerId, CancellationToken.None)
  2125. .ConfigureAwait(false);
  2126. var providerChannels = await GetChannelsFromListingsProviderData(providerId, CancellationToken.None)
  2127. .ConfigureAwait(false);
  2128. var mappings = listingsProviderInfo.ChannelMappings.ToList();
  2129. var tunerChannelMappings =
  2130. tunerChannels.Select(i => GetTunerChannelMapping(i, mappings, providerChannels)).ToList();
  2131. _taskManager.CancelIfRunningAndQueue<RefreshChannelsScheduledTask>();
  2132. return tunerChannelMappings.First(i => string.Equals(i.Number, tunerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2133. }
  2134. public TunerChannelMapping GetTunerChannelMapping(ChannelInfo channel, List<NameValuePair> mappings, List<ChannelInfo> providerChannels)
  2135. {
  2136. var result = new TunerChannelMapping
  2137. {
  2138. Name = channel.Number + " " + channel.Name,
  2139. Number = channel.Number
  2140. };
  2141. var mapping = mappings.FirstOrDefault(i => string.Equals(i.Name, channel.Number, StringComparison.OrdinalIgnoreCase));
  2142. var providerChannelNumber = channel.Number;
  2143. if (mapping != null)
  2144. {
  2145. providerChannelNumber = mapping.Value;
  2146. }
  2147. var providerChannel = providerChannels.FirstOrDefault(i => string.Equals(i.Number, providerChannelNumber, StringComparison.OrdinalIgnoreCase));
  2148. if (providerChannel != null)
  2149. {
  2150. result.ProviderChannelNumber = providerChannel.Number;
  2151. result.ProviderChannelName = providerChannel.Name;
  2152. }
  2153. return result;
  2154. }
  2155. public Task<List<NameIdPair>> GetLineups(string providerType, string providerId, string country, string location)
  2156. {
  2157. var config = GetConfiguration();
  2158. if (string.IsNullOrWhiteSpace(providerId))
  2159. {
  2160. var provider = _listingProviders.FirstOrDefault(i => string.Equals(providerType, i.Type, StringComparison.OrdinalIgnoreCase));
  2161. if (provider == null)
  2162. {
  2163. throw new ResourceNotFoundException();
  2164. }
  2165. return provider.GetLineups(null, country, location);
  2166. }
  2167. else
  2168. {
  2169. var info = config.ListingProviders.FirstOrDefault(i => string.Equals(i.Id, providerId, StringComparison.OrdinalIgnoreCase));
  2170. var provider = _listingProviders.FirstOrDefault(i => string.Equals(info.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  2171. if (provider == null)
  2172. {
  2173. throw new ResourceNotFoundException();
  2174. }
  2175. return provider.GetLineups(info, country, location);
  2176. }
  2177. }
  2178. public Task<MBRegistrationRecord> GetRegistrationInfo(string channelId, string programId, string feature)
  2179. {
  2180. ILiveTvService service;
  2181. if (string.IsNullOrWhiteSpace(programId))
  2182. {
  2183. var channel = GetInternalChannel(channelId);
  2184. service = GetService(channel);
  2185. }
  2186. else
  2187. {
  2188. var program = GetInternalProgram(programId);
  2189. service = GetService(program);
  2190. }
  2191. var hasRegistration = service as IHasRegistrationInfo;
  2192. if (hasRegistration != null)
  2193. {
  2194. return hasRegistration.GetRegistrationInfo(feature);
  2195. }
  2196. return Task.FromResult(new MBRegistrationRecord
  2197. {
  2198. IsValid = true,
  2199. IsRegistered = true
  2200. });
  2201. }
  2202. public List<NameValuePair> GetSatIniMappings()
  2203. {
  2204. var names = GetType().Assembly.GetManifestResourceNames().Where(i => i.IndexOf("SatIp.ini", StringComparison.OrdinalIgnoreCase) != -1).ToList();
  2205. return names.Select(GetSatIniMappings).Where(i => i != null).DistinctBy(i => i.Value.Split('|')[0]).ToList();
  2206. }
  2207. public NameValuePair GetSatIniMappings(string resource)
  2208. {
  2209. using (var stream = GetType().Assembly.GetManifestResourceStream(resource))
  2210. {
  2211. using (var reader = new StreamReader(stream))
  2212. {
  2213. var parser = new StreamIniDataParser();
  2214. IniData data = parser.ReadData(reader);
  2215. var satType1 = data["SATTYPE"]["1"];
  2216. var satType2 = data["SATTYPE"]["2"];
  2217. if (string.IsNullOrWhiteSpace(satType2))
  2218. {
  2219. return null;
  2220. }
  2221. var srch = "SatIp.ini.";
  2222. var filename = Path.GetFileName(resource);
  2223. return new NameValuePair
  2224. {
  2225. Name = satType1 + " " + satType2,
  2226. Value = satType2 + "|" + filename.Substring(filename.IndexOf(srch) + srch.Length)
  2227. };
  2228. }
  2229. }
  2230. }
  2231. public Task<List<ChannelInfo>> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken)
  2232. {
  2233. return new TunerHosts.SatIp.ChannelScan(_logger).Scan(info, cancellationToken);
  2234. }
  2235. public Task<List<ChannelInfo>> GetChannelsForListingsProvider(string id, CancellationToken cancellationToken)
  2236. {
  2237. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2238. return EmbyTV.EmbyTV.Current.GetChannelsForListingsProvider(info, cancellationToken);
  2239. }
  2240. public Task<List<ChannelInfo>> GetChannelsFromListingsProviderData(string id, CancellationToken cancellationToken)
  2241. {
  2242. var info = GetConfiguration().ListingProviders.First(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase));
  2243. var provider = _listingProviders.First(i => string.Equals(i.Type, info.Type, StringComparison.OrdinalIgnoreCase));
  2244. return provider.GetChannels(info, cancellationToken);
  2245. }
  2246. }
  2247. }