LibraryManager.cs 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195
  1. #pragma warning disable CS1591
  2. #pragma warning disable CA5394
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Emby.Naming.Common;
  14. using Emby.Naming.TV;
  15. using Emby.Server.Implementations.Library.Resolvers;
  16. using Emby.Server.Implementations.Library.Validators;
  17. using Emby.Server.Implementations.Playlists;
  18. using Emby.Server.Implementations.ScheduledTasks.Tasks;
  19. using Emby.Server.Implementations.Sorting;
  20. using Jellyfin.Data.Entities;
  21. using Jellyfin.Data.Enums;
  22. using Jellyfin.Extensions;
  23. using MediaBrowser.Common.Extensions;
  24. using MediaBrowser.Controller;
  25. using MediaBrowser.Controller.Configuration;
  26. using MediaBrowser.Controller.Drawing;
  27. using MediaBrowser.Controller.Dto;
  28. using MediaBrowser.Controller.Entities;
  29. using MediaBrowser.Controller.Entities.Audio;
  30. using MediaBrowser.Controller.IO;
  31. using MediaBrowser.Controller.Library;
  32. using MediaBrowser.Controller.LiveTv;
  33. using MediaBrowser.Controller.MediaEncoding;
  34. using MediaBrowser.Controller.Persistence;
  35. using MediaBrowser.Controller.Providers;
  36. using MediaBrowser.Controller.Resolvers;
  37. using MediaBrowser.Controller.Sorting;
  38. using MediaBrowser.Model.Configuration;
  39. using MediaBrowser.Model.Dlna;
  40. using MediaBrowser.Model.Drawing;
  41. using MediaBrowser.Model.Dto;
  42. using MediaBrowser.Model.Entities;
  43. using MediaBrowser.Model.IO;
  44. using MediaBrowser.Model.Library;
  45. using MediaBrowser.Model.Querying;
  46. using MediaBrowser.Model.Tasks;
  47. using Microsoft.Extensions.Logging;
  48. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  49. using EpisodeInfo = Emby.Naming.TV.EpisodeInfo;
  50. using Genre = MediaBrowser.Controller.Entities.Genre;
  51. using Person = MediaBrowser.Controller.Entities.Person;
  52. using VideoResolver = Emby.Naming.Video.VideoResolver;
  53. namespace Emby.Server.Implementations.Library
  54. {
  55. /// <summary>
  56. /// Class LibraryManager.
  57. /// </summary>
  58. public class LibraryManager : ILibraryManager
  59. {
  60. private const string ShortcutFileExtension = ".mblink";
  61. private readonly ILogger<LibraryManager> _logger;
  62. private readonly ConcurrentDictionary<Guid, BaseItem> _cache;
  63. private readonly ITaskManager _taskManager;
  64. private readonly IUserManager _userManager;
  65. private readonly IUserDataManager _userDataRepository;
  66. private readonly IServerConfigurationManager _configurationManager;
  67. private readonly Lazy<ILibraryMonitor> _libraryMonitorFactory;
  68. private readonly Lazy<IProviderManager> _providerManagerFactory;
  69. private readonly Lazy<IUserViewManager> _userviewManagerFactory;
  70. private readonly IServerApplicationHost _appHost;
  71. private readonly IMediaEncoder _mediaEncoder;
  72. private readonly IFileSystem _fileSystem;
  73. private readonly IItemRepository _itemRepository;
  74. private readonly IImageProcessor _imageProcessor;
  75. private readonly NamingOptions _namingOptions;
  76. private readonly IPeopleRepository _peopleRepository;
  77. private readonly ExtraResolver _extraResolver;
  78. /// <summary>
  79. /// The _root folder sync lock.
  80. /// </summary>
  81. private readonly Lock _rootFolderSyncLock = new();
  82. private readonly Lock _userRootFolderSyncLock = new();
  83. private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
  84. /// <summary>
  85. /// The _root folder.
  86. /// </summary>
  87. private volatile AggregateFolder? _rootFolder;
  88. private volatile UserRootFolder? _userRootFolder;
  89. private bool _wizardCompleted;
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  92. /// </summary>
  93. /// <param name="appHost">The application host.</param>
  94. /// <param name="loggerFactory">The logger factory.</param>
  95. /// <param name="taskManager">The task manager.</param>
  96. /// <param name="userManager">The user manager.</param>
  97. /// <param name="configurationManager">The configuration manager.</param>
  98. /// <param name="userDataRepository">The user data repository.</param>
  99. /// <param name="libraryMonitorFactory">The library monitor.</param>
  100. /// <param name="fileSystem">The file system.</param>
  101. /// <param name="providerManagerFactory">The provider manager.</param>
  102. /// <param name="userviewManagerFactory">The userview manager.</param>
  103. /// <param name="mediaEncoder">The media encoder.</param>
  104. /// <param name="itemRepository">The item repository.</param>
  105. /// <param name="imageProcessor">The image processor.</param>
  106. /// <param name="namingOptions">The naming options.</param>
  107. /// <param name="directoryService">The directory service.</param>
  108. /// <param name="peopleRepository">The People Repository.</param>
  109. public LibraryManager(
  110. IServerApplicationHost appHost,
  111. ILoggerFactory loggerFactory,
  112. ITaskManager taskManager,
  113. IUserManager userManager,
  114. IServerConfigurationManager configurationManager,
  115. IUserDataManager userDataRepository,
  116. Lazy<ILibraryMonitor> libraryMonitorFactory,
  117. IFileSystem fileSystem,
  118. Lazy<IProviderManager> providerManagerFactory,
  119. Lazy<IUserViewManager> userviewManagerFactory,
  120. IMediaEncoder mediaEncoder,
  121. IItemRepository itemRepository,
  122. IImageProcessor imageProcessor,
  123. NamingOptions namingOptions,
  124. IDirectoryService directoryService,
  125. IPeopleRepository peopleRepository)
  126. {
  127. _appHost = appHost;
  128. _logger = loggerFactory.CreateLogger<LibraryManager>();
  129. _taskManager = taskManager;
  130. _userManager = userManager;
  131. _configurationManager = configurationManager;
  132. _userDataRepository = userDataRepository;
  133. _libraryMonitorFactory = libraryMonitorFactory;
  134. _fileSystem = fileSystem;
  135. _providerManagerFactory = providerManagerFactory;
  136. _userviewManagerFactory = userviewManagerFactory;
  137. _mediaEncoder = mediaEncoder;
  138. _itemRepository = itemRepository;
  139. _imageProcessor = imageProcessor;
  140. _cache = new ConcurrentDictionary<Guid, BaseItem>();
  141. _namingOptions = namingOptions;
  142. _peopleRepository = peopleRepository;
  143. _extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryService);
  144. _configurationManager.ConfigurationUpdated += ConfigurationUpdated;
  145. RecordConfigurationValues(configurationManager.Configuration);
  146. }
  147. /// <summary>
  148. /// Occurs when [item added].
  149. /// </summary>
  150. public event EventHandler<ItemChangeEventArgs>? ItemAdded;
  151. /// <summary>
  152. /// Occurs when [item updated].
  153. /// </summary>
  154. public event EventHandler<ItemChangeEventArgs>? ItemUpdated;
  155. /// <summary>
  156. /// Occurs when [item removed].
  157. /// </summary>
  158. public event EventHandler<ItemChangeEventArgs>? ItemRemoved;
  159. /// <summary>
  160. /// Gets the root folder.
  161. /// </summary>
  162. /// <value>The root folder.</value>
  163. public AggregateFolder RootFolder
  164. {
  165. get
  166. {
  167. if (_rootFolder is null)
  168. {
  169. lock (_rootFolderSyncLock)
  170. {
  171. _rootFolder ??= CreateRootFolder();
  172. }
  173. }
  174. return _rootFolder;
  175. }
  176. }
  177. private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
  178. private IProviderManager ProviderManager => _providerManagerFactory.Value;
  179. private IUserViewManager UserViewManager => _userviewManagerFactory.Value;
  180. /// <summary>
  181. /// Gets or sets the postscan tasks.
  182. /// </summary>
  183. /// <value>The postscan tasks.</value>
  184. private ILibraryPostScanTask[] PostscanTasks { get; set; } = Array.Empty<ILibraryPostScanTask>();
  185. /// <summary>
  186. /// Gets or sets the intro providers.
  187. /// </summary>
  188. /// <value>The intro providers.</value>
  189. private IIntroProvider[] IntroProviders { get; set; } = Array.Empty<IIntroProvider>();
  190. /// <summary>
  191. /// Gets or sets the list of entity resolution ignore rules.
  192. /// </summary>
  193. /// <value>The entity resolution ignore rules.</value>
  194. private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; } = Array.Empty<IResolverIgnoreRule>();
  195. /// <summary>
  196. /// Gets or sets the list of currently registered entity resolvers.
  197. /// </summary>
  198. /// <value>The entity resolvers enumerable.</value>
  199. private IItemResolver[] EntityResolvers { get; set; } = Array.Empty<IItemResolver>();
  200. private IMultiItemResolver[] MultiItemResolvers { get; set; } = Array.Empty<IMultiItemResolver>();
  201. /// <summary>
  202. /// Gets or sets the comparers.
  203. /// </summary>
  204. /// <value>The comparers.</value>
  205. private IBaseItemComparer[] Comparers { get; set; } = Array.Empty<IBaseItemComparer>();
  206. public bool IsScanRunning { get; private set; }
  207. /// <summary>
  208. /// Adds the parts.
  209. /// </summary>
  210. /// <param name="rules">The rules.</param>
  211. /// <param name="resolvers">The resolvers.</param>
  212. /// <param name="introProviders">The intro providers.</param>
  213. /// <param name="itemComparers">The item comparers.</param>
  214. /// <param name="postscanTasks">The post scan tasks.</param>
  215. public void AddParts(
  216. IEnumerable<IResolverIgnoreRule> rules,
  217. IEnumerable<IItemResolver> resolvers,
  218. IEnumerable<IIntroProvider> introProviders,
  219. IEnumerable<IBaseItemComparer> itemComparers,
  220. IEnumerable<ILibraryPostScanTask> postscanTasks)
  221. {
  222. EntityResolutionIgnoreRules = rules.ToArray();
  223. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  224. MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
  225. IntroProviders = introProviders.ToArray();
  226. Comparers = itemComparers.ToArray();
  227. PostscanTasks = postscanTasks.ToArray();
  228. }
  229. /// <summary>
  230. /// Records the configuration values.
  231. /// </summary>
  232. /// <param name="configuration">The configuration.</param>
  233. private void RecordConfigurationValues(ServerConfiguration configuration)
  234. {
  235. _wizardCompleted = configuration.IsStartupWizardCompleted;
  236. }
  237. /// <summary>
  238. /// Configurations the updated.
  239. /// </summary>
  240. /// <param name="sender">The sender.</param>
  241. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  242. private void ConfigurationUpdated(object? sender, EventArgs e)
  243. {
  244. var config = _configurationManager.Configuration;
  245. var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
  246. RecordConfigurationValues(config);
  247. if (wizardChanged)
  248. {
  249. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  250. }
  251. }
  252. public void RegisterItem(BaseItem item)
  253. {
  254. ArgumentNullException.ThrowIfNull(item);
  255. if (item is IItemByName)
  256. {
  257. if (item is not MusicArtist)
  258. {
  259. return;
  260. }
  261. }
  262. else if (!item.IsFolder)
  263. {
  264. if (item is not Video && item is not LiveTvChannel)
  265. {
  266. return;
  267. }
  268. }
  269. _cache[item.Id] = item;
  270. }
  271. public void DeleteItem(BaseItem item, DeleteOptions options)
  272. {
  273. DeleteItem(item, options, false);
  274. }
  275. public void DeleteItem(BaseItem item, DeleteOptions options, bool notifyParentItem)
  276. {
  277. ArgumentNullException.ThrowIfNull(item);
  278. var parent = item.GetOwner() ?? item.GetParent();
  279. DeleteItem(item, options, parent, notifyParentItem);
  280. }
  281. public void DeleteItem(BaseItem item, DeleteOptions options, BaseItem parent, bool notifyParentItem)
  282. {
  283. ArgumentNullException.ThrowIfNull(item);
  284. if (item.SourceType == SourceType.Channel)
  285. {
  286. if (options.DeleteFromExternalProvider)
  287. {
  288. try
  289. {
  290. BaseItem.ChannelManager.DeleteItem(item).GetAwaiter().GetResult();
  291. }
  292. catch (ArgumentException)
  293. {
  294. // channel no longer installed
  295. }
  296. }
  297. options.DeleteFileLocation = false;
  298. }
  299. if (item is LiveTvProgram)
  300. {
  301. _logger.LogDebug(
  302. "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  303. item.GetType().Name,
  304. item.Name ?? "Unknown name",
  305. item.Path ?? string.Empty,
  306. item.Id);
  307. }
  308. else
  309. {
  310. _logger.LogInformation(
  311. "Removing item, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  312. item.GetType().Name,
  313. item.Name ?? "Unknown name",
  314. item.Path ?? string.Empty,
  315. item.Id);
  316. }
  317. var children = item.IsFolder
  318. ? ((Folder)item).GetRecursiveChildren(false)
  319. : Array.Empty<BaseItem>();
  320. foreach (var metadataPath in GetMetadataPaths(item, children))
  321. {
  322. if (!Directory.Exists(metadataPath))
  323. {
  324. continue;
  325. }
  326. _logger.LogDebug(
  327. "Deleting metadata path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  328. item.GetType().Name,
  329. item.Name ?? "Unknown name",
  330. metadataPath,
  331. item.Id);
  332. try
  333. {
  334. Directory.Delete(metadataPath, true);
  335. }
  336. catch (Exception ex)
  337. {
  338. _logger.LogError(ex, "Error deleting {MetadataPath}", metadataPath);
  339. }
  340. }
  341. if (options.DeleteFileLocation && item.IsFileProtocol)
  342. {
  343. // Assume only the first is required
  344. // Add this flag to GetDeletePaths if required in the future
  345. var isRequiredForDelete = true;
  346. foreach (var fileSystemInfo in item.GetDeletePaths())
  347. {
  348. if (Directory.Exists(fileSystemInfo.FullName) || File.Exists(fileSystemInfo.FullName))
  349. {
  350. try
  351. {
  352. _logger.LogInformation(
  353. "Deleting item path, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  354. item.GetType().Name,
  355. item.Name ?? "Unknown name",
  356. fileSystemInfo.FullName,
  357. item.Id);
  358. if (fileSystemInfo.IsDirectory)
  359. {
  360. Directory.Delete(fileSystemInfo.FullName, true);
  361. }
  362. else
  363. {
  364. File.Delete(fileSystemInfo.FullName);
  365. }
  366. }
  367. catch (DirectoryNotFoundException)
  368. {
  369. _logger.LogInformation(
  370. "Directory not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  371. item.GetType().Name,
  372. item.Name ?? "Unknown name",
  373. fileSystemInfo.FullName,
  374. item.Id);
  375. }
  376. catch (FileNotFoundException)
  377. {
  378. _logger.LogInformation(
  379. "File not found, only removing from database, Type: {Type}, Name: {Name}, Path: {Path}, Id: {Id}",
  380. item.GetType().Name,
  381. item.Name ?? "Unknown name",
  382. fileSystemInfo.FullName,
  383. item.Id);
  384. }
  385. catch (IOException)
  386. {
  387. if (isRequiredForDelete)
  388. {
  389. throw;
  390. }
  391. }
  392. catch (UnauthorizedAccessException)
  393. {
  394. if (isRequiredForDelete)
  395. {
  396. throw;
  397. }
  398. }
  399. }
  400. isRequiredForDelete = false;
  401. }
  402. }
  403. item.SetParent(null);
  404. _itemRepository.DeleteItem(item.Id);
  405. foreach (var child in children)
  406. {
  407. _itemRepository.DeleteItem(child.Id);
  408. }
  409. _cache.TryRemove(item.Id, out _);
  410. ReportItemRemoved(item, parent);
  411. }
  412. private static List<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
  413. {
  414. var list = new List<string>
  415. {
  416. item.GetInternalMetadataPath()
  417. };
  418. list.AddRange(children.Select(i => i.GetInternalMetadataPath()));
  419. return list;
  420. }
  421. /// <summary>
  422. /// Resolves the item.
  423. /// </summary>
  424. /// <param name="args">The args.</param>
  425. /// <param name="resolvers">The resolvers.</param>
  426. /// <returns>BaseItem.</returns>
  427. private BaseItem? ResolveItem(ItemResolveArgs args, IItemResolver[]? resolvers)
  428. {
  429. var item = (resolvers ?? EntityResolvers).Select(r => Resolve(args, r))
  430. .FirstOrDefault(i => i is not null);
  431. if (item is not null)
  432. {
  433. ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
  434. }
  435. return item;
  436. }
  437. private BaseItem? Resolve(ItemResolveArgs args, IItemResolver resolver)
  438. {
  439. try
  440. {
  441. return resolver.ResolvePath(args);
  442. }
  443. catch (Exception ex)
  444. {
  445. _logger.LogError(ex, "Error in {Resolver} resolving {Path}", resolver.GetType().Name, args.Path);
  446. return null;
  447. }
  448. }
  449. public Guid GetNewItemId(string key, Type type)
  450. {
  451. return GetNewItemIdInternal(key, type, false);
  452. }
  453. private Guid GetNewItemIdInternal(string key, Type type, bool forceCaseInsensitive)
  454. {
  455. ArgumentException.ThrowIfNullOrEmpty(key);
  456. ArgumentNullException.ThrowIfNull(type);
  457. string programDataPath = _configurationManager.ApplicationPaths.ProgramDataPath;
  458. if (key.StartsWith(programDataPath, StringComparison.Ordinal))
  459. {
  460. // Try to normalize paths located underneath program-data in an attempt to make them more portable
  461. key = key.Substring(programDataPath.Length)
  462. .TrimStart('/', '\\')
  463. .Replace('/', '\\');
  464. }
  465. if (forceCaseInsensitive || !_configurationManager.Configuration.EnableCaseSensitiveItemIds)
  466. {
  467. key = key.ToLowerInvariant();
  468. }
  469. key = type.FullName + key;
  470. return key.GetMD5();
  471. }
  472. public BaseItem? ResolvePath(FileSystemMetadata fileInfo, Folder? parent = null, IDirectoryService? directoryService = null)
  473. => ResolvePath(fileInfo, directoryService ?? new DirectoryService(_fileSystem), null, parent);
  474. private BaseItem? ResolvePath(
  475. FileSystemMetadata fileInfo,
  476. IDirectoryService directoryService,
  477. IItemResolver[]? resolvers,
  478. Folder? parent = null,
  479. CollectionType? collectionType = null,
  480. LibraryOptions? libraryOptions = null)
  481. {
  482. ArgumentNullException.ThrowIfNull(fileInfo);
  483. var fullPath = fileInfo.FullName;
  484. if (collectionType is null && parent is not null)
  485. {
  486. collectionType = GetContentTypeOverride(fullPath, true);
  487. }
  488. var args = new ItemResolveArgs(_configurationManager.ApplicationPaths, this)
  489. {
  490. Parent = parent,
  491. FileInfo = fileInfo,
  492. CollectionType = collectionType,
  493. LibraryOptions = libraryOptions
  494. };
  495. // Return null if ignore rules deem that we should do so
  496. if (IgnoreFile(args.FileInfo, args.Parent))
  497. {
  498. return null;
  499. }
  500. // Gather child folder and files
  501. if (args.IsDirectory)
  502. {
  503. var isPhysicalRoot = args.IsPhysicalRoot;
  504. // When resolving the root, we need it's grandchildren (children of user views)
  505. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  506. FileSystemMetadata[] files;
  507. var isVf = args.IsVf;
  508. try
  509. {
  510. files = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _appHost, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || isVf);
  511. }
  512. catch (Exception ex)
  513. {
  514. if (parent is not null && parent.IsPhysicalRoot)
  515. {
  516. _logger.LogError(ex, "Error in GetFilteredFileSystemEntries isPhysicalRoot: {0} IsVf: {1}", isPhysicalRoot, isVf);
  517. files = Array.Empty<FileSystemMetadata>();
  518. }
  519. else
  520. {
  521. throw;
  522. }
  523. }
  524. // Need to remove subpaths that may have been resolved from shortcuts
  525. // Example: if \\server\movies exists, then strip out \\server\movies\action
  526. if (isPhysicalRoot)
  527. {
  528. files = NormalizeRootPathList(files).ToArray();
  529. }
  530. args.FileSystemChildren = files;
  531. }
  532. // Check to see if we should resolve based on our contents
  533. if (args.IsDirectory && !ShouldResolvePathContents(args))
  534. {
  535. return null;
  536. }
  537. return ResolveItem(args, resolvers);
  538. }
  539. public bool IgnoreFile(FileSystemMetadata file, BaseItem? parent)
  540. => EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent));
  541. public List<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
  542. {
  543. var originalList = paths.ToList();
  544. var list = originalList.Where(i => i.IsDirectory)
  545. .Select(i => Path.TrimEndingDirectorySeparator(i.FullName))
  546. .Distinct(StringComparer.OrdinalIgnoreCase)
  547. .ToList();
  548. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  549. .ToList();
  550. foreach (var dupe in dupes)
  551. {
  552. _logger.LogInformation("Found duplicate path: {0}", dupe);
  553. }
  554. var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList();
  555. newList.AddRange(originalList.Where(i => !i.IsDirectory));
  556. return newList;
  557. }
  558. /// <summary>
  559. /// Determines whether a path should be ignored based on its contents - called after the contents have been read.
  560. /// </summary>
  561. /// <param name="args">The args.</param>
  562. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  563. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  564. {
  565. // Ignore any folders containing a file called .ignore
  566. return !args.ContainsFileSystemEntryByName(".ignore");
  567. }
  568. public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryService, Folder parent, LibraryOptions libraryOptions, CollectionType? collectionType = null)
  569. {
  570. return ResolvePaths(files, directoryService, parent, libraryOptions, collectionType, EntityResolvers);
  571. }
  572. public IEnumerable<BaseItem> ResolvePaths(
  573. IEnumerable<FileSystemMetadata> files,
  574. IDirectoryService directoryService,
  575. Folder parent,
  576. LibraryOptions libraryOptions,
  577. CollectionType? collectionType,
  578. IItemResolver[] resolvers)
  579. {
  580. var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList();
  581. if (parent is not null)
  582. {
  583. var multiItemResolvers = resolvers is null ? MultiItemResolvers : resolvers.OfType<IMultiItemResolver>();
  584. foreach (var resolver in multiItemResolvers)
  585. {
  586. var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
  587. if (result?.Items.Count > 0)
  588. {
  589. var items = result.Items;
  590. items.RemoveAll(item => !ResolverHelper.SetInitialItemValues(item, parent, this, directoryService));
  591. items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType, resolvers, libraryOptions));
  592. return items;
  593. }
  594. }
  595. }
  596. return ResolveFileList(fileList, directoryService, parent, collectionType, resolvers, libraryOptions);
  597. }
  598. private IEnumerable<BaseItem> ResolveFileList(
  599. IReadOnlyList<FileSystemMetadata> fileList,
  600. IDirectoryService directoryService,
  601. Folder? parent,
  602. CollectionType? collectionType,
  603. IItemResolver[]? resolvers,
  604. LibraryOptions libraryOptions)
  605. {
  606. // Given that fileList is a list we can save enumerator allocations by indexing
  607. for (var i = 0; i < fileList.Count; i++)
  608. {
  609. var file = fileList[i];
  610. BaseItem? result = null;
  611. try
  612. {
  613. result = ResolvePath(file, directoryService, resolvers, parent, collectionType, libraryOptions);
  614. }
  615. catch (Exception ex)
  616. {
  617. _logger.LogError(ex, "Error resolving path {Path}", file.FullName);
  618. }
  619. if (result is not null)
  620. {
  621. yield return result;
  622. }
  623. }
  624. }
  625. /// <summary>
  626. /// Creates the root media folder.
  627. /// </summary>
  628. /// <returns>AggregateFolder.</returns>
  629. /// <exception cref="InvalidOperationException">Cannot create the root folder until plugins have loaded.</exception>
  630. public AggregateFolder CreateRootFolder()
  631. {
  632. var rootFolderPath = _configurationManager.ApplicationPaths.RootFolderPath;
  633. Directory.CreateDirectory(rootFolderPath);
  634. var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
  635. (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOperationException("Something went very wong"))
  636. .DeepCopy<Folder, AggregateFolder>();
  637. // In case program data folder was moved
  638. if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
  639. {
  640. _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
  641. rootFolder.Path = rootFolderPath;
  642. }
  643. // Add in the plug-in folders
  644. var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
  645. Directory.CreateDirectory(path);
  646. Folder folder = new PlaylistsFolder
  647. {
  648. Path = path
  649. };
  650. if (folder.Id.IsEmpty())
  651. {
  652. folder.Id = GetNewItemId(folder.Path, folder.GetType());
  653. }
  654. var dbItem = GetItemById(folder.Id) as BasePluginFolder;
  655. if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
  656. {
  657. folder = dbItem;
  658. }
  659. if (!folder.ParentId.Equals(rootFolder.Id))
  660. {
  661. folder.ParentId = rootFolder.Id;
  662. folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
  663. }
  664. rootFolder.AddVirtualChild(folder);
  665. RegisterItem(folder);
  666. return rootFolder;
  667. }
  668. public Folder GetUserRootFolder()
  669. {
  670. if (_userRootFolder is null)
  671. {
  672. lock (_userRootFolderSyncLock)
  673. {
  674. if (_userRootFolder is null)
  675. {
  676. var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  677. _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
  678. Directory.CreateDirectory(userRootPath);
  679. var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
  680. UserRootFolder? tmpItem = null;
  681. try
  682. {
  683. tmpItem = GetItemById(newItemId) as UserRootFolder;
  684. }
  685. catch (Exception ex)
  686. {
  687. _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
  688. }
  689. if (tmpItem is null)
  690. {
  691. _logger.LogDebug("Creating new userRootFolder with DeepCopy");
  692. tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new InvalidOperationException("Failed to get user root path"))
  693. .DeepCopy<Folder, UserRootFolder>();
  694. }
  695. // In case program data folder was moved
  696. if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
  697. {
  698. _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
  699. tmpItem.Path = userRootPath;
  700. }
  701. _userRootFolder = tmpItem;
  702. _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
  703. }
  704. }
  705. }
  706. return _userRootFolder;
  707. }
  708. /// <inheritdoc />
  709. public BaseItem? FindByPath(string path, bool? isFolder)
  710. {
  711. // If this returns multiple items it could be tricky figuring out which one is correct.
  712. // In most cases, the newest one will be and the others obsolete but not yet cleaned up
  713. ArgumentException.ThrowIfNullOrEmpty(path);
  714. var query = new InternalItemsQuery
  715. {
  716. Path = path,
  717. IsFolder = isFolder,
  718. OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
  719. Limit = 1,
  720. DtoOptions = new DtoOptions(true)
  721. };
  722. return GetItemList(query)
  723. .FirstOrDefault();
  724. }
  725. /// <inheritdoc />
  726. public Person? GetPerson(string name)
  727. {
  728. var path = Person.GetPath(name);
  729. var id = GetItemByNameId<Person>(path);
  730. if (GetItemById(id) is Person item)
  731. {
  732. return item;
  733. }
  734. return null;
  735. }
  736. /// <summary>
  737. /// Gets the studio.
  738. /// </summary>
  739. /// <param name="name">The name.</param>
  740. /// <returns>Task{Studio}.</returns>
  741. public Studio GetStudio(string name)
  742. {
  743. return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
  744. }
  745. public Guid GetStudioId(string name)
  746. {
  747. return GetItemByNameId<Studio>(Studio.GetPath(name));
  748. }
  749. public Guid GetGenreId(string name)
  750. {
  751. return GetItemByNameId<Genre>(Genre.GetPath(name));
  752. }
  753. public Guid GetMusicGenreId(string name)
  754. {
  755. return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
  756. }
  757. /// <summary>
  758. /// Gets the genre.
  759. /// </summary>
  760. /// <param name="name">The name.</param>
  761. /// <returns>Task{Genre}.</returns>
  762. public Genre GetGenre(string name)
  763. {
  764. return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
  765. }
  766. /// <summary>
  767. /// Gets the music genre.
  768. /// </summary>
  769. /// <param name="name">The name.</param>
  770. /// <returns>Task{MusicGenre}.</returns>
  771. public MusicGenre GetMusicGenre(string name)
  772. {
  773. return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
  774. }
  775. /// <summary>
  776. /// Gets the year.
  777. /// </summary>
  778. /// <param name="value">The value.</param>
  779. /// <returns>Task{Year}.</returns>
  780. public Year GetYear(int value)
  781. {
  782. if (value <= 0)
  783. {
  784. throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
  785. }
  786. var name = value.ToString(CultureInfo.InvariantCulture);
  787. return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
  788. }
  789. /// <summary>
  790. /// Gets a Genre.
  791. /// </summary>
  792. /// <param name="name">The name.</param>
  793. /// <returns>Task{Genre}.</returns>
  794. public MusicArtist GetArtist(string name)
  795. {
  796. return GetArtist(name, new DtoOptions(true));
  797. }
  798. public MusicArtist GetArtist(string name, DtoOptions options)
  799. {
  800. return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
  801. }
  802. private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
  803. where T : BaseItem, new()
  804. {
  805. if (typeof(T) == typeof(MusicArtist))
  806. {
  807. var existing = GetItemList(new InternalItemsQuery
  808. {
  809. IncludeItemTypes = new[] { BaseItemKind.MusicArtist },
  810. Name = name,
  811. DtoOptions = options
  812. }).Cast<MusicArtist>()
  813. .OrderBy(i => i.IsAccessedByName ? 1 : 0)
  814. .Cast<T>()
  815. .FirstOrDefault();
  816. if (existing is not null)
  817. {
  818. return existing;
  819. }
  820. }
  821. var path = getPathFn(name);
  822. var id = GetItemByNameId<T>(path);
  823. var item = GetItemById(id) as T;
  824. if (item is null)
  825. {
  826. item = new T
  827. {
  828. Name = name,
  829. Id = id,
  830. DateCreated = DateTime.UtcNow,
  831. DateModified = DateTime.UtcNow,
  832. Path = path
  833. };
  834. CreateItem(item, null);
  835. }
  836. return item;
  837. }
  838. private Guid GetItemByNameId<T>(string path)
  839. where T : BaseItem, new()
  840. {
  841. var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
  842. return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
  843. }
  844. /// <inheritdoc />
  845. public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
  846. {
  847. // Ensure the location is available.
  848. Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
  849. return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
  850. }
  851. /// <summary>
  852. /// Reloads the root media folder.
  853. /// </summary>
  854. /// <param name="progress">The progress.</param>
  855. /// <param name="cancellationToken">The cancellation token.</param>
  856. /// <returns>Task.</returns>
  857. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  858. {
  859. // Just run the scheduled task so that the user can see it
  860. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  861. return Task.CompletedTask;
  862. }
  863. /// <summary>
  864. /// Validates the media library internal.
  865. /// </summary>
  866. /// <param name="progress">The progress.</param>
  867. /// <param name="cancellationToken">The cancellation token.</param>
  868. /// <returns>Task.</returns>
  869. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  870. {
  871. IsScanRunning = true;
  872. LibraryMonitor.Stop();
  873. try
  874. {
  875. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  876. }
  877. finally
  878. {
  879. LibraryMonitor.Start();
  880. IsScanRunning = false;
  881. }
  882. }
  883. public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
  884. {
  885. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  886. // Start by just validating the children of the root, but go no further
  887. await RootFolder.ValidateChildren(
  888. new Progress<double>(),
  889. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  890. recursive: false,
  891. allowRemoveRoot: removeRoot,
  892. cancellationToken: cancellationToken).ConfigureAwait(false);
  893. await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
  894. await GetUserRootFolder().ValidateChildren(
  895. new Progress<double>(),
  896. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  897. recursive: false,
  898. allowRemoveRoot: removeRoot,
  899. cancellationToken: cancellationToken).ConfigureAwait(false);
  900. // Quickly scan CollectionFolders for changes
  901. foreach (var child in GetUserRootFolder().Children.OfType<Folder>())
  902. {
  903. // If the user has somehow deleted the collection directory, remove the metadata from the database.
  904. if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
  905. {
  906. _itemRepository.DeleteItem(collectionFolder.Id);
  907. }
  908. else
  909. {
  910. await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  911. }
  912. }
  913. }
  914. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  915. {
  916. _logger.LogInformation("Validating media library");
  917. await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
  918. var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
  919. // Validate the entire media library
  920. await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  921. progress.Report(96);
  922. innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
  923. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  924. progress.Report(100);
  925. }
  926. /// <summary>
  927. /// Runs the post scan tasks.
  928. /// </summary>
  929. /// <param name="progress">The progress.</param>
  930. /// <param name="cancellationToken">The cancellation token.</param>
  931. /// <returns>Task.</returns>
  932. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  933. {
  934. var tasks = PostscanTasks.ToList();
  935. var numComplete = 0;
  936. var numTasks = tasks.Count;
  937. foreach (var task in tasks)
  938. {
  939. // Prevent access to modified closure
  940. var currentNumComplete = numComplete;
  941. var innerProgress = new Progress<double>(pct =>
  942. {
  943. double innerPercent = pct;
  944. innerPercent /= 100;
  945. innerPercent += currentNumComplete;
  946. innerPercent /= numTasks;
  947. innerPercent *= 100;
  948. progress.Report(innerPercent);
  949. });
  950. _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
  951. try
  952. {
  953. await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
  954. }
  955. catch (OperationCanceledException)
  956. {
  957. _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
  958. throw;
  959. }
  960. catch (Exception ex)
  961. {
  962. _logger.LogError(ex, "Error running post-scan task");
  963. }
  964. numComplete++;
  965. double percent = numComplete;
  966. percent /= numTasks;
  967. progress.Report(percent * 100);
  968. }
  969. _itemRepository.UpdateInheritedValues();
  970. progress.Report(100);
  971. }
  972. /// <summary>
  973. /// Gets the default view.
  974. /// </summary>
  975. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  976. public List<VirtualFolderInfo> GetVirtualFolders()
  977. {
  978. return GetVirtualFolders(false);
  979. }
  980. public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
  981. {
  982. _logger.LogDebug("Getting topLibraryFolders");
  983. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  984. _logger.LogDebug("Getting refreshQueue");
  985. var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
  986. return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
  987. .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
  988. .ToList();
  989. }
  990. private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? refreshQueue)
  991. {
  992. var info = new VirtualFolderInfo
  993. {
  994. Name = Path.GetFileName(dir),
  995. Locations = _fileSystem.GetFilePaths(dir, false)
  996. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  997. .Select(i =>
  998. {
  999. try
  1000. {
  1001. return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
  1002. }
  1003. catch (Exception ex)
  1004. {
  1005. _logger.LogError(ex, "Error resolving shortcut file {File}", i);
  1006. return null;
  1007. }
  1008. })
  1009. .Where(i => i is not null)
  1010. .Order()
  1011. .ToArray(),
  1012. CollectionType = GetCollectionType(dir)
  1013. };
  1014. var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.OrdinalIgnoreCase));
  1015. if (libraryFolder is not null)
  1016. {
  1017. var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
  1018. info.ItemId = libraryFolderId;
  1019. if (libraryFolder.HasImage(ImageType.Primary))
  1020. {
  1021. info.PrimaryImageItemId = libraryFolderId;
  1022. }
  1023. info.LibraryOptions = GetLibraryOptions(libraryFolder);
  1024. if (refreshQueue is not null)
  1025. {
  1026. info.RefreshProgress = libraryFolder.GetRefreshProgress();
  1027. info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.Id) ? "Queued" : "Idle";
  1028. }
  1029. }
  1030. return info;
  1031. }
  1032. private CollectionTypeOptions? GetCollectionType(string path)
  1033. {
  1034. var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false);
  1035. foreach (ReadOnlySpan<char> file in files)
  1036. {
  1037. if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
  1038. {
  1039. return res;
  1040. }
  1041. }
  1042. return null;
  1043. }
  1044. /// <inheritdoc />
  1045. public BaseItem? GetItemById(Guid id)
  1046. {
  1047. if (id.IsEmpty())
  1048. {
  1049. throw new ArgumentException("Guid can't be empty", nameof(id));
  1050. }
  1051. if (_cache.TryGetValue(id, out BaseItem? item))
  1052. {
  1053. return item;
  1054. }
  1055. item = RetrieveItem(id);
  1056. if (item is not null)
  1057. {
  1058. RegisterItem(item);
  1059. }
  1060. return item;
  1061. }
  1062. /// <inheritdoc />
  1063. public T? GetItemById<T>(Guid id)
  1064. where T : BaseItem
  1065. {
  1066. var item = GetItemById(id);
  1067. if (item is T typedItem)
  1068. {
  1069. return typedItem;
  1070. }
  1071. return null;
  1072. }
  1073. /// <inheritdoc />
  1074. public T? GetItemById<T>(Guid id, Guid userId)
  1075. where T : BaseItem
  1076. {
  1077. var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
  1078. return GetItemById<T>(id, user);
  1079. }
  1080. /// <inheritdoc />
  1081. public T? GetItemById<T>(Guid id, User? user)
  1082. where T : BaseItem
  1083. {
  1084. var item = GetItemById<T>(id);
  1085. return ItemIsVisible(item, user) ? item : null;
  1086. }
  1087. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
  1088. {
  1089. if (query.Recursive && !query.ParentId.IsEmpty())
  1090. {
  1091. var parent = GetItemById(query.ParentId);
  1092. if (parent is not null)
  1093. {
  1094. SetTopParentIdsOrAncestors(query, new[] { parent });
  1095. }
  1096. }
  1097. if (query.User is not null)
  1098. {
  1099. AddUserToQuery(query, query.User, allowExternalContent);
  1100. }
  1101. var itemList = _itemRepository.GetItemList(query);
  1102. var user = query.User;
  1103. if (user is not null)
  1104. {
  1105. return itemList.Where(i => i.IsVisible(user)).ToList();
  1106. }
  1107. return itemList;
  1108. }
  1109. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  1110. {
  1111. return GetItemList(query, true);
  1112. }
  1113. public int GetCount(InternalItemsQuery query)
  1114. {
  1115. if (query.Recursive && !query.ParentId.IsEmpty())
  1116. {
  1117. var parent = GetItemById(query.ParentId);
  1118. if (parent is not null)
  1119. {
  1120. SetTopParentIdsOrAncestors(query, new[] { parent });
  1121. }
  1122. }
  1123. if (query.User is not null)
  1124. {
  1125. AddUserToQuery(query, query.User);
  1126. }
  1127. return _itemRepository.GetCount(query);
  1128. }
  1129. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
  1130. {
  1131. SetTopParentIdsOrAncestors(query, parents);
  1132. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1133. {
  1134. if (query.User is not null)
  1135. {
  1136. AddUserToQuery(query, query.User);
  1137. }
  1138. }
  1139. return _itemRepository.GetItemList(query);
  1140. }
  1141. public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
  1142. {
  1143. if (query.User is not null)
  1144. {
  1145. AddUserToQuery(query, query.User);
  1146. }
  1147. if (query.EnableTotalRecordCount)
  1148. {
  1149. return _itemRepository.GetItems(query);
  1150. }
  1151. return new QueryResult<BaseItem>(
  1152. query.StartIndex,
  1153. null,
  1154. _itemRepository.GetItemList(query));
  1155. }
  1156. public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
  1157. {
  1158. if (query.User is not null)
  1159. {
  1160. AddUserToQuery(query, query.User);
  1161. }
  1162. return _itemRepository.GetItemIdsList(query);
  1163. }
  1164. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
  1165. {
  1166. if (query.User is not null)
  1167. {
  1168. AddUserToQuery(query, query.User);
  1169. }
  1170. SetTopParentOrAncestorIds(query);
  1171. return _itemRepository.GetStudios(query);
  1172. }
  1173. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
  1174. {
  1175. if (query.User is not null)
  1176. {
  1177. AddUserToQuery(query, query.User);
  1178. }
  1179. SetTopParentOrAncestorIds(query);
  1180. return _itemRepository.GetGenres(query);
  1181. }
  1182. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
  1183. {
  1184. if (query.User is not null)
  1185. {
  1186. AddUserToQuery(query, query.User);
  1187. }
  1188. SetTopParentOrAncestorIds(query);
  1189. return _itemRepository.GetMusicGenres(query);
  1190. }
  1191. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
  1192. {
  1193. if (query.User is not null)
  1194. {
  1195. AddUserToQuery(query, query.User);
  1196. }
  1197. SetTopParentOrAncestorIds(query);
  1198. return _itemRepository.GetAllArtists(query);
  1199. }
  1200. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
  1201. {
  1202. if (query.User is not null)
  1203. {
  1204. AddUserToQuery(query, query.User);
  1205. }
  1206. SetTopParentOrAncestorIds(query);
  1207. return _itemRepository.GetArtists(query);
  1208. }
  1209. private void SetTopParentOrAncestorIds(InternalItemsQuery query)
  1210. {
  1211. var ancestorIds = query.AncestorIds;
  1212. int len = ancestorIds.Length;
  1213. if (len == 0)
  1214. {
  1215. return;
  1216. }
  1217. var parents = new BaseItem[len];
  1218. for (int i = 0; i < len; i++)
  1219. {
  1220. parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id: {ancestorIds[i]}");
  1221. if (parents[i] is not (ICollectionFolder or UserView))
  1222. {
  1223. return;
  1224. }
  1225. }
  1226. // Optimize by querying against top level views
  1227. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1228. query.AncestorIds = Array.Empty<Guid>();
  1229. // Prevent searching in all libraries due to empty filter
  1230. if (query.TopParentIds.Length == 0)
  1231. {
  1232. query.TopParentIds = [Guid.NewGuid()];
  1233. }
  1234. }
  1235. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
  1236. {
  1237. if (query.User is not null)
  1238. {
  1239. AddUserToQuery(query, query.User);
  1240. }
  1241. SetTopParentOrAncestorIds(query);
  1242. return _itemRepository.GetAlbumArtists(query);
  1243. }
  1244. public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
  1245. {
  1246. if (query.Recursive && !query.ParentId.IsEmpty())
  1247. {
  1248. var parent = GetItemById(query.ParentId);
  1249. if (parent is not null)
  1250. {
  1251. SetTopParentIdsOrAncestors(query, new[] { parent });
  1252. }
  1253. }
  1254. if (query.User is not null)
  1255. {
  1256. AddUserToQuery(query, query.User);
  1257. }
  1258. if (query.EnableTotalRecordCount)
  1259. {
  1260. return _itemRepository.GetItems(query);
  1261. }
  1262. return new QueryResult<BaseItem>(
  1263. query.StartIndex,
  1264. null,
  1265. _itemRepository.GetItemList(query));
  1266. }
  1267. private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
  1268. {
  1269. if (parents.All(i => i is ICollectionFolder || i is UserView))
  1270. {
  1271. // Optimize by querying against top level views
  1272. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1273. // Prevent searching in all libraries due to empty filter
  1274. if (query.TopParentIds.Length == 0)
  1275. {
  1276. query.TopParentIds = new[] { Guid.NewGuid() };
  1277. }
  1278. }
  1279. else
  1280. {
  1281. // We need to be able to query from any arbitrary ancestor up the tree
  1282. query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
  1283. // Prevent searching in all libraries due to empty filter
  1284. if (query.AncestorIds.Length == 0)
  1285. {
  1286. query.AncestorIds = new[] { Guid.NewGuid() };
  1287. }
  1288. }
  1289. query.Parent = null;
  1290. }
  1291. private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
  1292. {
  1293. if (query.AncestorIds.Length == 0 &&
  1294. query.ParentId.IsEmpty() &&
  1295. query.ChannelIds.Count == 0 &&
  1296. query.TopParentIds.Length == 0 &&
  1297. string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
  1298. string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
  1299. query.ItemIds.Length == 0)
  1300. {
  1301. var userViews = UserViewManager.GetUserViews(new UserViewQuery
  1302. {
  1303. User = user,
  1304. IncludeHidden = true,
  1305. IncludeExternalContent = allowExternalContent
  1306. });
  1307. query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
  1308. // Prevent searching in all libraries due to empty filter
  1309. if (query.TopParentIds.Length == 0)
  1310. {
  1311. query.TopParentIds = new[] { Guid.NewGuid() };
  1312. }
  1313. }
  1314. }
  1315. private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
  1316. {
  1317. if (item is UserView view)
  1318. {
  1319. if (view.ViewType == CollectionType.livetv)
  1320. {
  1321. return new[] { view.Id };
  1322. }
  1323. // Translate view into folders
  1324. if (!view.DisplayParentId.IsEmpty())
  1325. {
  1326. var displayParent = GetItemById(view.DisplayParentId);
  1327. if (displayParent is not null)
  1328. {
  1329. return GetTopParentIdsForQuery(displayParent, user);
  1330. }
  1331. return Array.Empty<Guid>();
  1332. }
  1333. if (!view.ParentId.IsEmpty())
  1334. {
  1335. var displayParent = GetItemById(view.ParentId);
  1336. if (displayParent is not null)
  1337. {
  1338. return GetTopParentIdsForQuery(displayParent, user);
  1339. }
  1340. return Array.Empty<Guid>();
  1341. }
  1342. // Handle grouping
  1343. if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.ViewType)
  1344. && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
  1345. {
  1346. return GetUserRootFolder()
  1347. .GetChildren(user, true)
  1348. .OfType<CollectionFolder>()
  1349. .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
  1350. .Where(i => user.IsFolderGrouped(i.Id))
  1351. .SelectMany(i => GetTopParentIdsForQuery(i, user));
  1352. }
  1353. return Array.Empty<Guid>();
  1354. }
  1355. if (item is CollectionFolder collectionFolder)
  1356. {
  1357. return collectionFolder.PhysicalFolderIds;
  1358. }
  1359. var topParent = item.GetTopParent();
  1360. if (topParent is not null)
  1361. {
  1362. return new[] { topParent.Id };
  1363. }
  1364. return Array.Empty<Guid>();
  1365. }
  1366. /// <summary>
  1367. /// Gets the intros.
  1368. /// </summary>
  1369. /// <param name="item">The item.</param>
  1370. /// <param name="user">The user.</param>
  1371. /// <returns>IEnumerable{System.String}.</returns>
  1372. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1373. {
  1374. if (IntroProviders.Length == 0)
  1375. {
  1376. return [];
  1377. }
  1378. var tasks = IntroProviders
  1379. .Select(i => GetIntros(i, item, user));
  1380. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1381. return items
  1382. .SelectMany(i => i)
  1383. .Select(ResolveIntro)
  1384. .Where(i => i is not null)!; // null values got filtered out
  1385. }
  1386. /// <summary>
  1387. /// Gets the intros.
  1388. /// </summary>
  1389. /// <param name="provider">The provider.</param>
  1390. /// <param name="item">The item.</param>
  1391. /// <param name="user">The user.</param>
  1392. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1393. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1394. {
  1395. try
  1396. {
  1397. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1398. }
  1399. catch (Exception ex)
  1400. {
  1401. _logger.LogError(ex, "Error getting intros");
  1402. return Enumerable.Empty<IntroInfo>();
  1403. }
  1404. }
  1405. /// <summary>
  1406. /// Resolves the intro.
  1407. /// </summary>
  1408. /// <param name="info">The info.</param>
  1409. /// <returns>Video.</returns>
  1410. private Video? ResolveIntro(IntroInfo info)
  1411. {
  1412. Video? video = null;
  1413. if (info.ItemId.HasValue)
  1414. {
  1415. // Get an existing item by Id
  1416. video = GetItemById(info.ItemId.Value) as Video;
  1417. if (video is null)
  1418. {
  1419. _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
  1420. }
  1421. }
  1422. else if (!string.IsNullOrEmpty(info.Path))
  1423. {
  1424. try
  1425. {
  1426. // Try to resolve the path into a video
  1427. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1428. if (video is null)
  1429. {
  1430. _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
  1431. }
  1432. else
  1433. {
  1434. // Pull the saved db item that will include metadata
  1435. var dbItem = GetItemById(video.Id) as Video;
  1436. if (dbItem is not null)
  1437. {
  1438. video = dbItem;
  1439. }
  1440. else
  1441. {
  1442. return null;
  1443. }
  1444. }
  1445. }
  1446. catch (Exception ex)
  1447. {
  1448. _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
  1449. }
  1450. }
  1451. else
  1452. {
  1453. _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1454. }
  1455. return video;
  1456. }
  1457. /// <inheritdoc />
  1458. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortOrder sortOrder)
  1459. {
  1460. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1461. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
  1462. {
  1463. if (orderBy is RandomComparer)
  1464. {
  1465. var randomItems = items.ToArray();
  1466. Random.Shared.Shuffle(randomItems);
  1467. items = randomItems;
  1468. // Items are no longer ordered at this point, so set orderedItems back to null
  1469. orderedItems = null;
  1470. }
  1471. else if (orderedItems is null)
  1472. {
  1473. orderedItems = sortOrder == SortOrder.Descending
  1474. ? items.OrderByDescending(i => i, orderBy)
  1475. : items.OrderBy(i => i, orderBy);
  1476. }
  1477. else
  1478. {
  1479. orderedItems = sortOrder == SortOrder.Descending
  1480. ? orderedItems!.ThenByDescending(i => i, orderBy)
  1481. : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
  1482. }
  1483. }
  1484. return orderedItems ?? items;
  1485. }
  1486. /// <inheritdoc />
  1487. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, SortOrder SortOrder)> orderBy)
  1488. {
  1489. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1490. foreach (var (name, sortOrder) in orderBy)
  1491. {
  1492. var comparer = GetComparer(name, user);
  1493. if (comparer is null)
  1494. {
  1495. continue;
  1496. }
  1497. if (comparer is RandomComparer)
  1498. {
  1499. var randomItems = items.ToArray();
  1500. Random.Shared.Shuffle(randomItems);
  1501. items = randomItems;
  1502. // Items are no longer ordered at this point, so set orderedItems back to null
  1503. orderedItems = null;
  1504. }
  1505. else if (orderedItems is null)
  1506. {
  1507. orderedItems = sortOrder == SortOrder.Descending
  1508. ? items.OrderByDescending(i => i, comparer)
  1509. : items.OrderBy(i => i, comparer);
  1510. }
  1511. else
  1512. {
  1513. orderedItems = sortOrder == SortOrder.Descending
  1514. ? orderedItems!.ThenByDescending(i => i, comparer)
  1515. : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
  1516. }
  1517. }
  1518. return orderedItems ?? items;
  1519. }
  1520. /// <summary>
  1521. /// Gets the comparer.
  1522. /// </summary>
  1523. /// <param name="name">The name.</param>
  1524. /// <param name="user">The user.</param>
  1525. /// <returns>IBaseItemComparer.</returns>
  1526. private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
  1527. {
  1528. var comparer = Comparers.FirstOrDefault(c => name == c.Type);
  1529. // If it requires a user, create a new one, and assign the user
  1530. if (comparer is IUserBaseItemComparer)
  1531. {
  1532. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null for Nullable<T> instances
  1533. userComparer.User = user;
  1534. userComparer.UserManager = _userManager;
  1535. userComparer.UserDataRepository = _userDataRepository;
  1536. return userComparer;
  1537. }
  1538. return comparer;
  1539. }
  1540. /// <inheritdoc />
  1541. public void CreateItem(BaseItem item, BaseItem? parent)
  1542. {
  1543. CreateOrUpdateItems(new[] { item }, parent, CancellationToken.None);
  1544. }
  1545. /// <inheritdoc />
  1546. public void CreateOrUpdateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
  1547. {
  1548. _itemRepository.SaveItems(items, cancellationToken);
  1549. foreach (var item in items)
  1550. {
  1551. RegisterItem(item);
  1552. }
  1553. if (ItemAdded is not null)
  1554. {
  1555. foreach (var item in items)
  1556. {
  1557. // With the live tv guide this just creates too much noise
  1558. if (item.SourceType != SourceType.Library)
  1559. {
  1560. continue;
  1561. }
  1562. try
  1563. {
  1564. ItemAdded(
  1565. this,
  1566. new ItemChangeEventArgs
  1567. {
  1568. Item = item,
  1569. Parent = parent ?? item.GetParent()
  1570. });
  1571. }
  1572. catch (Exception ex)
  1573. {
  1574. _logger.LogError(ex, "Error in ItemAdded event handler");
  1575. }
  1576. }
  1577. }
  1578. }
  1579. private bool ImageNeedsRefresh(ItemImageInfo image)
  1580. {
  1581. if (image.Path is not null && image.IsLocalFile)
  1582. {
  1583. if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
  1584. {
  1585. return true;
  1586. }
  1587. try
  1588. {
  1589. return _fileSystem.GetLastWriteTimeUtc(image.Path) != image.DateModified;
  1590. }
  1591. catch (Exception ex)
  1592. {
  1593. _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
  1594. return false;
  1595. }
  1596. }
  1597. return image.Path is not null && !image.IsLocalFile;
  1598. }
  1599. /// <inheritdoc />
  1600. public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
  1601. {
  1602. ArgumentNullException.ThrowIfNull(item);
  1603. var outdated = forceUpdate
  1604. ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
  1605. : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
  1606. // Skip image processing if current or live tv source
  1607. if (outdated.Length == 0 || item.SourceType != SourceType.Library)
  1608. {
  1609. RegisterItem(item);
  1610. return;
  1611. }
  1612. foreach (var img in outdated)
  1613. {
  1614. var image = img;
  1615. if (!img.IsLocalFile)
  1616. {
  1617. try
  1618. {
  1619. var index = item.GetImageIndex(img);
  1620. image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
  1621. }
  1622. catch (ArgumentException)
  1623. {
  1624. _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
  1625. continue;
  1626. }
  1627. catch (Exception ex) when (ex is InvalidOperationException or IOException)
  1628. {
  1629. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
  1630. continue;
  1631. }
  1632. catch (HttpRequestException ex)
  1633. {
  1634. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode);
  1635. continue;
  1636. }
  1637. }
  1638. ImageDimensions size;
  1639. try
  1640. {
  1641. size = _imageProcessor.GetImageDimensions(item, image);
  1642. image.Width = size.Width;
  1643. image.Height = size.Height;
  1644. }
  1645. catch (Exception ex)
  1646. {
  1647. _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
  1648. size = default;
  1649. image.Width = 0;
  1650. image.Height = 0;
  1651. }
  1652. try
  1653. {
  1654. image.BlurHash = _imageProcessor.GetImageBlurHash(image.Path, size);
  1655. }
  1656. catch (Exception ex)
  1657. {
  1658. _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
  1659. image.BlurHash = string.Empty;
  1660. }
  1661. try
  1662. {
  1663. image.DateModified = _fileSystem.GetLastWriteTimeUtc(image.Path);
  1664. }
  1665. catch (Exception ex)
  1666. {
  1667. _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
  1668. }
  1669. }
  1670. _itemRepository.SaveImages(item);
  1671. RegisterItem(item);
  1672. }
  1673. /// <inheritdoc />
  1674. public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1675. {
  1676. _itemRepository.SaveItems(items, cancellationToken);
  1677. foreach (var item in items)
  1678. {
  1679. await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
  1680. }
  1681. if (ItemUpdated is not null)
  1682. {
  1683. foreach (var item in items)
  1684. {
  1685. // With the live tv guide this just creates too much noise
  1686. if (item.SourceType != SourceType.Library)
  1687. {
  1688. continue;
  1689. }
  1690. try
  1691. {
  1692. ItemUpdated(
  1693. this,
  1694. new ItemChangeEventArgs
  1695. {
  1696. Item = item,
  1697. Parent = parent,
  1698. UpdateReason = updateReason
  1699. });
  1700. }
  1701. catch (Exception ex)
  1702. {
  1703. _logger.LogError(ex, "Error in ItemUpdated event handler");
  1704. }
  1705. }
  1706. }
  1707. }
  1708. /// <inheritdoc />
  1709. public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1710. => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken);
  1711. public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
  1712. {
  1713. if (item.IsFileProtocol)
  1714. {
  1715. await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
  1716. }
  1717. item.DateLastSaved = DateTime.UtcNow;
  1718. await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
  1719. }
  1720. /// <summary>
  1721. /// Reports the item removed.
  1722. /// </summary>
  1723. /// <param name="item">The item.</param>
  1724. /// <param name="parent">The parent item.</param>
  1725. public void ReportItemRemoved(BaseItem item, BaseItem parent)
  1726. {
  1727. if (ItemRemoved is not null)
  1728. {
  1729. try
  1730. {
  1731. ItemRemoved(
  1732. this,
  1733. new ItemChangeEventArgs
  1734. {
  1735. Item = item,
  1736. Parent = parent
  1737. });
  1738. }
  1739. catch (Exception ex)
  1740. {
  1741. _logger.LogError(ex, "Error in ItemRemoved event handler");
  1742. }
  1743. }
  1744. }
  1745. /// <summary>
  1746. /// Retrieves the item.
  1747. /// </summary>
  1748. /// <param name="id">The id.</param>
  1749. /// <returns>BaseItem.</returns>
  1750. public BaseItem RetrieveItem(Guid id)
  1751. {
  1752. return _itemRepository.RetrieveItem(id);
  1753. }
  1754. public List<Folder> GetCollectionFolders(BaseItem item)
  1755. {
  1756. return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
  1757. }
  1758. public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1759. {
  1760. while (item is not null)
  1761. {
  1762. var parent = item.GetParent();
  1763. if (parent is AggregateFolder)
  1764. {
  1765. break;
  1766. }
  1767. if (parent is null)
  1768. {
  1769. var owner = item.GetOwner();
  1770. if (owner is null)
  1771. {
  1772. break;
  1773. }
  1774. item = owner;
  1775. }
  1776. else
  1777. {
  1778. item = parent;
  1779. }
  1780. }
  1781. if (item is null)
  1782. {
  1783. return new List<Folder>();
  1784. }
  1785. return GetCollectionFoldersInternal(item, allUserRootChildren);
  1786. }
  1787. private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1788. {
  1789. return allUserRootChildren
  1790. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path.AsSpan(), StringComparison.OrdinalIgnoreCase))
  1791. .ToList();
  1792. }
  1793. public LibraryOptions GetLibraryOptions(BaseItem item)
  1794. {
  1795. if (item is CollectionFolder collectionFolder)
  1796. {
  1797. return collectionFolder.GetLibraryOptions();
  1798. }
  1799. // List.Find is more performant than FirstOrDefault due to enumerator allocation
  1800. return GetCollectionFolders(item)
  1801. .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
  1802. ? collectionFolder2.GetLibraryOptions()
  1803. : new LibraryOptions();
  1804. }
  1805. public CollectionType? GetContentType(BaseItem item)
  1806. {
  1807. var configuredContentType = GetConfiguredContentType(item, false);
  1808. if (configuredContentType is not null)
  1809. {
  1810. return configuredContentType;
  1811. }
  1812. configuredContentType = GetConfiguredContentType(item, true);
  1813. if (configuredContentType is not null)
  1814. {
  1815. return configuredContentType;
  1816. }
  1817. return GetInheritedContentType(item);
  1818. }
  1819. public CollectionType? GetInheritedContentType(BaseItem item)
  1820. {
  1821. var type = GetTopFolderContentType(item);
  1822. if (type is not null)
  1823. {
  1824. return type;
  1825. }
  1826. return item.GetParents()
  1827. .Select(GetConfiguredContentType)
  1828. .LastOrDefault(i => i is not null);
  1829. }
  1830. public CollectionType? GetConfiguredContentType(BaseItem item)
  1831. {
  1832. return GetConfiguredContentType(item, false);
  1833. }
  1834. public CollectionType? GetConfiguredContentType(string path)
  1835. {
  1836. return GetContentTypeOverride(path, false);
  1837. }
  1838. public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1839. {
  1840. if (item is ICollectionFolder collectionFolder)
  1841. {
  1842. return collectionFolder.CollectionType;
  1843. }
  1844. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1845. }
  1846. private CollectionType? GetContentTypeOverride(string path, bool inherit)
  1847. {
  1848. var nameValuePair = _configurationManager.Configuration.ContentTypes
  1849. .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
  1850. || (inherit && !string.IsNullOrEmpty(i.Name)
  1851. && _fileSystem.ContainsSubPath(i.Name, path)));
  1852. if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
  1853. {
  1854. return collectionType;
  1855. }
  1856. return null;
  1857. }
  1858. private CollectionType? GetTopFolderContentType(BaseItem item)
  1859. {
  1860. if (item is null)
  1861. {
  1862. return null;
  1863. }
  1864. while (!item.ParentId.IsEmpty())
  1865. {
  1866. var parent = item.GetParent();
  1867. if (parent is null || parent is AggregateFolder)
  1868. {
  1869. break;
  1870. }
  1871. item = parent;
  1872. }
  1873. return GetUserRootFolder().Children
  1874. .OfType<ICollectionFolder>()
  1875. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1876. .Select(i => i.CollectionType)
  1877. .FirstOrDefault(i => i is not null);
  1878. }
  1879. public UserView GetNamedView(
  1880. User user,
  1881. string name,
  1882. CollectionType? viewType,
  1883. string sortName)
  1884. {
  1885. return GetNamedView(user, name, Guid.Empty, viewType, sortName);
  1886. }
  1887. public UserView GetNamedView(
  1888. string name,
  1889. CollectionType viewType,
  1890. string sortName)
  1891. {
  1892. var path = Path.Combine(
  1893. _configurationManager.ApplicationPaths.InternalMetadataPath,
  1894. "views",
  1895. _fileSystem.GetValidFilename(viewType.ToString()));
  1896. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1897. var item = GetItemById(id) as UserView;
  1898. var refresh = false;
  1899. if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1900. {
  1901. Directory.CreateDirectory(path);
  1902. item = new UserView
  1903. {
  1904. Path = path,
  1905. Id = id,
  1906. DateCreated = DateTime.UtcNow,
  1907. Name = name,
  1908. ViewType = viewType,
  1909. ForcedSortName = sortName
  1910. };
  1911. CreateItem(item, null);
  1912. refresh = true;
  1913. }
  1914. if (refresh)
  1915. {
  1916. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
  1917. ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
  1918. }
  1919. return item;
  1920. }
  1921. public UserView GetNamedView(
  1922. User user,
  1923. string name,
  1924. Guid parentId,
  1925. CollectionType? viewType,
  1926. string sortName)
  1927. {
  1928. var parentIdString = parentId.IsEmpty()
  1929. ? null
  1930. : parentId.ToString("N", CultureInfo.InvariantCulture);
  1931. var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  1932. var id = GetNewItemId(idValues, typeof(UserView));
  1933. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1934. var item = GetItemById(id) as UserView;
  1935. var isNew = false;
  1936. if (item is null)
  1937. {
  1938. Directory.CreateDirectory(path);
  1939. item = new UserView
  1940. {
  1941. Path = path,
  1942. Id = id,
  1943. DateCreated = DateTime.UtcNow,
  1944. Name = name,
  1945. ViewType = viewType,
  1946. ForcedSortName = sortName,
  1947. UserId = user.Id,
  1948. DisplayParentId = parentId
  1949. };
  1950. CreateItem(item, null);
  1951. isNew = true;
  1952. }
  1953. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1954. if (!refresh && !item.DisplayParentId.IsEmpty())
  1955. {
  1956. var displayParent = GetItemById(item.DisplayParentId);
  1957. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1958. }
  1959. if (refresh)
  1960. {
  1961. ProviderManager.QueueRefresh(
  1962. item.Id,
  1963. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1964. {
  1965. // Need to force save to increment DateLastSaved
  1966. ForceSave = true
  1967. },
  1968. RefreshPriority.Normal);
  1969. }
  1970. return item;
  1971. }
  1972. public UserView GetShadowView(
  1973. BaseItem parent,
  1974. CollectionType? viewType,
  1975. string sortName)
  1976. {
  1977. ArgumentNullException.ThrowIfNull(parent);
  1978. var name = parent.Name;
  1979. var parentId = parent.Id;
  1980. var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
  1981. var id = GetNewItemId(idValues, typeof(UserView));
  1982. var path = parent.Path;
  1983. var item = GetItemById(id) as UserView;
  1984. var isNew = false;
  1985. if (item is null)
  1986. {
  1987. Directory.CreateDirectory(path);
  1988. item = new UserView
  1989. {
  1990. Path = path,
  1991. Id = id,
  1992. DateCreated = DateTime.UtcNow,
  1993. Name = name,
  1994. ViewType = viewType,
  1995. ForcedSortName = sortName
  1996. };
  1997. item.DisplayParentId = parentId;
  1998. CreateItem(item, null);
  1999. isNew = true;
  2000. }
  2001. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  2002. if (!refresh && !item.DisplayParentId.IsEmpty())
  2003. {
  2004. var displayParent = GetItemById(item.DisplayParentId);
  2005. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  2006. }
  2007. if (refresh)
  2008. {
  2009. ProviderManager.QueueRefresh(
  2010. item.Id,
  2011. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2012. {
  2013. // Need to force save to increment DateLastSaved
  2014. ForceSave = true
  2015. },
  2016. RefreshPriority.Normal);
  2017. }
  2018. return item;
  2019. }
  2020. public UserView GetNamedView(
  2021. string name,
  2022. Guid parentId,
  2023. CollectionType? viewType,
  2024. string sortName,
  2025. string uniqueId)
  2026. {
  2027. ArgumentException.ThrowIfNullOrEmpty(name);
  2028. var parentIdString = parentId.IsEmpty()
  2029. ? null
  2030. : parentId.ToString("N", CultureInfo.InvariantCulture);
  2031. var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  2032. if (!string.IsNullOrEmpty(uniqueId))
  2033. {
  2034. idValues += uniqueId;
  2035. }
  2036. var id = GetNewItemId(idValues, typeof(UserView));
  2037. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  2038. var item = GetItemById(id) as UserView;
  2039. var isNew = false;
  2040. if (item is null)
  2041. {
  2042. Directory.CreateDirectory(path);
  2043. item = new UserView
  2044. {
  2045. Path = path,
  2046. Id = id,
  2047. DateCreated = DateTime.UtcNow,
  2048. Name = name,
  2049. ViewType = viewType,
  2050. ForcedSortName = sortName
  2051. };
  2052. item.DisplayParentId = parentId;
  2053. CreateItem(item, null);
  2054. isNew = true;
  2055. }
  2056. if (viewType != item.ViewType)
  2057. {
  2058. item.ViewType = viewType;
  2059. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult();
  2060. }
  2061. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  2062. if (!refresh && !item.DisplayParentId.IsEmpty())
  2063. {
  2064. var displayParent = GetItemById(item.DisplayParentId);
  2065. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  2066. }
  2067. if (refresh)
  2068. {
  2069. ProviderManager.QueueRefresh(
  2070. item.Id,
  2071. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2072. {
  2073. // Need to force save to increment DateLastSaved
  2074. ForceSave = true
  2075. },
  2076. RefreshPriority.Normal);
  2077. }
  2078. return item;
  2079. }
  2080. public BaseItem GetParentItem(Guid? parentId, Guid? userId)
  2081. {
  2082. if (parentId.HasValue)
  2083. {
  2084. return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}");
  2085. }
  2086. if (!userId.IsNullOrEmpty())
  2087. {
  2088. return GetUserRootFolder();
  2089. }
  2090. return RootFolder;
  2091. }
  2092. /// <inheritdoc />
  2093. public void QueueLibraryScan()
  2094. {
  2095. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  2096. }
  2097. /// <inheritdoc />
  2098. public int? GetSeasonNumberFromPath(string path)
  2099. => SeasonPathParser.Parse(path, true, true).SeasonNumber;
  2100. /// <inheritdoc />
  2101. public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
  2102. {
  2103. var series = episode.Series;
  2104. bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
  2105. if (!isAbsoluteNaming.Value)
  2106. {
  2107. // In other words, no filter applied
  2108. isAbsoluteNaming = null;
  2109. }
  2110. var resolver = new EpisodeResolver(_namingOptions);
  2111. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
  2112. // TODO nullable - what are we trying to do there with empty episodeInfo?
  2113. EpisodeInfo? episodeInfo = null;
  2114. if (episode.IsFileProtocol)
  2115. {
  2116. episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
  2117. // Resolve from parent folder if it's not the Season folder
  2118. var parent = episode.GetParent();
  2119. if (episodeInfo is null && parent.GetType() == typeof(Folder))
  2120. {
  2121. episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
  2122. if (episodeInfo is not null)
  2123. {
  2124. // add the container
  2125. episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
  2126. }
  2127. }
  2128. }
  2129. episodeInfo ??= new EpisodeInfo(episode.Path);
  2130. try
  2131. {
  2132. var libraryOptions = GetLibraryOptions(episode);
  2133. if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(episodeInfo.Container, "mp4", StringComparison.OrdinalIgnoreCase))
  2134. {
  2135. // Read from metadata
  2136. var mediaInfo = _mediaEncoder.GetMediaInfo(
  2137. new MediaInfoRequest
  2138. {
  2139. MediaSource = episode.GetMediaSources(false)[0],
  2140. MediaType = DlnaProfileType.Video
  2141. },
  2142. CancellationToken.None).GetAwaiter().GetResult();
  2143. if (mediaInfo.ParentIndexNumber > 0)
  2144. {
  2145. episodeInfo.SeasonNumber = mediaInfo.ParentIndexNumber;
  2146. }
  2147. if (mediaInfo.IndexNumber > 0)
  2148. {
  2149. episodeInfo.EpisodeNumber = mediaInfo.IndexNumber;
  2150. }
  2151. if (!string.IsNullOrEmpty(mediaInfo.ShowName))
  2152. {
  2153. episodeInfo.SeriesName = mediaInfo.ShowName;
  2154. }
  2155. }
  2156. }
  2157. catch (Exception ex)
  2158. {
  2159. _logger.LogError(ex, "Error reading the episode information with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
  2160. }
  2161. var changed = false;
  2162. if (episodeInfo.IsByDate)
  2163. {
  2164. if (episode.IndexNumber.HasValue)
  2165. {
  2166. episode.IndexNumber = null;
  2167. changed = true;
  2168. }
  2169. if (episode.IndexNumberEnd.HasValue)
  2170. {
  2171. episode.IndexNumberEnd = null;
  2172. changed = true;
  2173. }
  2174. if (!episode.PremiereDate.HasValue)
  2175. {
  2176. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  2177. {
  2178. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  2179. }
  2180. if (episode.PremiereDate.HasValue)
  2181. {
  2182. changed = true;
  2183. }
  2184. }
  2185. if (!episode.ProductionYear.HasValue)
  2186. {
  2187. episode.ProductionYear = episodeInfo.Year;
  2188. if (episode.ProductionYear.HasValue)
  2189. {
  2190. changed = true;
  2191. }
  2192. }
  2193. }
  2194. else
  2195. {
  2196. if (!episode.IndexNumber.HasValue || forceRefresh)
  2197. {
  2198. if (episode.IndexNumber != episodeInfo.EpisodeNumber)
  2199. {
  2200. changed = true;
  2201. }
  2202. episode.IndexNumber = episodeInfo.EpisodeNumber;
  2203. }
  2204. if (!episode.IndexNumberEnd.HasValue || forceRefresh)
  2205. {
  2206. if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
  2207. {
  2208. changed = true;
  2209. }
  2210. episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
  2211. }
  2212. if (!episode.ParentIndexNumber.HasValue || forceRefresh)
  2213. {
  2214. if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
  2215. {
  2216. changed = true;
  2217. }
  2218. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  2219. }
  2220. }
  2221. if (!episode.ParentIndexNumber.HasValue)
  2222. {
  2223. var season = episode.Season;
  2224. if (season is not null)
  2225. {
  2226. episode.ParentIndexNumber = season.IndexNumber;
  2227. }
  2228. else
  2229. {
  2230. /*
  2231. Anime series don't generally have a season in their file name, however,
  2232. TVDb needs a season to correctly get the metadata.
  2233. Hence, a null season needs to be filled with something. */
  2234. // FIXME perhaps this would be better for TVDb parser to ask for season 1 if no season is specified
  2235. episode.ParentIndexNumber = 1;
  2236. }
  2237. if (episode.ParentIndexNumber.HasValue)
  2238. {
  2239. changed = true;
  2240. }
  2241. }
  2242. return changed;
  2243. }
  2244. public ItemLookupInfo ParseName(string name)
  2245. {
  2246. var namingOptions = _namingOptions;
  2247. var result = VideoResolver.CleanDateTime(name, namingOptions);
  2248. return new ItemLookupInfo
  2249. {
  2250. Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name,
  2251. Year = result.Year
  2252. };
  2253. }
  2254. public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2255. {
  2256. var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions);
  2257. if (ownerVideoInfo is null)
  2258. {
  2259. yield break;
  2260. }
  2261. var count = fileSystemChildren.Count;
  2262. for (var i = 0; i < count; i++)
  2263. {
  2264. var current = fileSystemChildren[i];
  2265. if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
  2266. {
  2267. var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
  2268. foreach (var file in filesInSubFolder)
  2269. {
  2270. if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
  2271. {
  2272. continue;
  2273. }
  2274. var extra = GetExtra(file, extraType.Value);
  2275. if (extra is not null)
  2276. {
  2277. yield return extra;
  2278. }
  2279. }
  2280. }
  2281. else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo, out var extraType))
  2282. {
  2283. var extra = GetExtra(current, extraType.Value);
  2284. if (extra is not null)
  2285. {
  2286. yield return extra;
  2287. }
  2288. }
  2289. }
  2290. BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType)
  2291. {
  2292. var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetResolversForExtraType(extraType));
  2293. if (extra is not Video && extra is not Audio)
  2294. {
  2295. return null;
  2296. }
  2297. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2298. var itemById = GetItemById(extra.Id);
  2299. if (itemById is not null)
  2300. {
  2301. extra = itemById;
  2302. }
  2303. // Only update extra type if it is more specific then the currently known extra type
  2304. if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
  2305. {
  2306. extra.ExtraType = extraType;
  2307. }
  2308. extra.ParentId = Guid.Empty;
  2309. extra.OwnerId = owner.Id;
  2310. return extra;
  2311. }
  2312. }
  2313. public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
  2314. {
  2315. foreach (var map in _configurationManager.Configuration.PathSubstitutions)
  2316. {
  2317. if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
  2318. {
  2319. return newPath;
  2320. }
  2321. }
  2322. return path;
  2323. }
  2324. public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
  2325. {
  2326. return _peopleRepository.GetPeople(query);
  2327. }
  2328. public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
  2329. {
  2330. if (item.SupportsPeople)
  2331. {
  2332. var people = GetPeople(new InternalPeopleQuery
  2333. {
  2334. ItemId = item.Id
  2335. });
  2336. if (people.Count > 0)
  2337. {
  2338. return people;
  2339. }
  2340. }
  2341. return [];
  2342. }
  2343. public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
  2344. {
  2345. return _peopleRepository.GetPeopleNames(query)
  2346. .Select(i =>
  2347. {
  2348. try
  2349. {
  2350. return GetPerson(i);
  2351. }
  2352. catch (Exception ex)
  2353. {
  2354. _logger.LogError(ex, "Error getting person");
  2355. return null;
  2356. }
  2357. })
  2358. .Where(i => i is not null)
  2359. .Where(i => query.User is null || i!.IsVisible(query.User))
  2360. .ToList()!; // null values are filtered out
  2361. }
  2362. public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
  2363. {
  2364. return _peopleRepository.GetPeopleNames(query);
  2365. }
  2366. public void UpdatePeople(BaseItem item, List<PersonInfo> people)
  2367. {
  2368. UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
  2369. }
  2370. /// <inheritdoc />
  2371. public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellationToken)
  2372. {
  2373. if (!item.SupportsPeople)
  2374. {
  2375. return;
  2376. }
  2377. if (people is not null)
  2378. {
  2379. people = people.Where(e => e is not null).ToArray();
  2380. _peopleRepository.UpdatePeople(item.Id, people);
  2381. await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
  2382. }
  2383. }
  2384. public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure)
  2385. {
  2386. foreach (var url in image.Path.Split('|'))
  2387. {
  2388. try
  2389. {
  2390. _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2391. await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2392. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2393. return item.GetImageInfo(image.Type, imageIndex);
  2394. }
  2395. catch (HttpRequestException ex)
  2396. {
  2397. if (ex.StatusCode.HasValue
  2398. && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
  2399. {
  2400. _logger.LogDebug(ex, "Error downloading image {Url}", url);
  2401. continue;
  2402. }
  2403. throw;
  2404. }
  2405. }
  2406. if (removeOnFailure)
  2407. {
  2408. // Remove this image to prevent it from retrying over and over
  2409. item.RemoveImage(image);
  2410. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2411. }
  2412. throw new InvalidOperationException("Unable to convert any images to local");
  2413. }
  2414. public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary)
  2415. {
  2416. if (string.IsNullOrWhiteSpace(name))
  2417. {
  2418. throw new ArgumentNullException(nameof(name));
  2419. }
  2420. name = _fileSystem.GetValidFilename(name);
  2421. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2422. var existingNameCount = 1; // first numbered name will be 2
  2423. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2424. var originalName = name;
  2425. while (Directory.Exists(virtualFolderPath))
  2426. {
  2427. existingNameCount++;
  2428. name = originalName + existingNameCount;
  2429. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2430. }
  2431. var mediaPathInfos = options.PathInfos;
  2432. if (mediaPathInfos is not null)
  2433. {
  2434. var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
  2435. if (invalidpath is not null)
  2436. {
  2437. throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
  2438. }
  2439. }
  2440. LibraryMonitor.Stop();
  2441. try
  2442. {
  2443. Directory.CreateDirectory(virtualFolderPath);
  2444. if (collectionType is not null)
  2445. {
  2446. var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collection"); // Can't be null with legal values?
  2447. await File.WriteAllBytesAsync(path, Array.Empty<byte>()).ConfigureAwait(false);
  2448. }
  2449. CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
  2450. if (mediaPathInfos is not null)
  2451. {
  2452. foreach (var path in mediaPathInfos)
  2453. {
  2454. AddMediaPathInternal(name, path, false);
  2455. }
  2456. }
  2457. }
  2458. finally
  2459. {
  2460. if (refreshLibrary)
  2461. {
  2462. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2463. StartScanInBackground();
  2464. }
  2465. else
  2466. {
  2467. // Need to add a delay here or directory watchers may still pick up the changes
  2468. await Task.Delay(1000).ConfigureAwait(false);
  2469. LibraryMonitor.Start();
  2470. }
  2471. }
  2472. }
  2473. private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
  2474. {
  2475. foreach (var person in people)
  2476. {
  2477. cancellationToken.ThrowIfCancellationRequested();
  2478. var itemUpdateType = ItemUpdateType.MetadataDownload;
  2479. var saveEntity = false;
  2480. var createEntity = false;
  2481. var personEntity = GetPerson(person.Name);
  2482. if (personEntity is null)
  2483. {
  2484. var path = Person.GetPath(person.Name);
  2485. personEntity = new Person()
  2486. {
  2487. Name = person.Name,
  2488. Id = GetItemByNameId<Person>(path),
  2489. DateCreated = DateTime.UtcNow,
  2490. DateModified = DateTime.UtcNow,
  2491. Path = path
  2492. };
  2493. personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
  2494. saveEntity = true;
  2495. createEntity = true;
  2496. }
  2497. foreach (var id in person.ProviderIds)
  2498. {
  2499. if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase))
  2500. {
  2501. personEntity.SetProviderId(id.Key, id.Value);
  2502. saveEntity = true;
  2503. }
  2504. }
  2505. if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
  2506. {
  2507. personEntity.SetImage(
  2508. new ItemImageInfo
  2509. {
  2510. Path = person.ImageUrl,
  2511. Type = ImageType.Primary
  2512. },
  2513. 0);
  2514. saveEntity = true;
  2515. itemUpdateType = ItemUpdateType.ImageUpdate;
  2516. }
  2517. if (saveEntity)
  2518. {
  2519. if (createEntity)
  2520. {
  2521. CreateOrUpdateItems([personEntity], null, CancellationToken.None);
  2522. }
  2523. await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
  2524. CreateOrUpdateItems([personEntity], null, CancellationToken.None);
  2525. }
  2526. }
  2527. }
  2528. private void StartScanInBackground()
  2529. {
  2530. Task.Run(() =>
  2531. {
  2532. // No need to start if scanning the library because it will handle it
  2533. ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  2534. });
  2535. }
  2536. public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2537. {
  2538. AddMediaPathInternal(virtualFolderName, mediaPath, true);
  2539. }
  2540. private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
  2541. {
  2542. ArgumentNullException.ThrowIfNull(pathInfo);
  2543. var path = pathInfo.Path;
  2544. if (string.IsNullOrWhiteSpace(path))
  2545. {
  2546. throw new ArgumentException(nameof(path));
  2547. }
  2548. if (!Directory.Exists(path))
  2549. {
  2550. throw new FileNotFoundException("The path does not exist.");
  2551. }
  2552. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2553. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2554. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  2555. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2556. while (File.Exists(lnk))
  2557. {
  2558. shortcutFilename += "1";
  2559. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2560. }
  2561. _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
  2562. RemoveContentTypeOverrides(path);
  2563. if (saveLibraryOptions)
  2564. {
  2565. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2566. libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
  2567. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2568. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2569. }
  2570. }
  2571. public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2572. {
  2573. ArgumentNullException.ThrowIfNull(mediaPath);
  2574. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2575. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2576. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2577. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2578. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2579. }
  2580. private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
  2581. {
  2582. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  2583. var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
  2584. if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
  2585. {
  2586. var list = options.PathInfos.ToList();
  2587. foreach (var location in info.Locations)
  2588. {
  2589. if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
  2590. {
  2591. list.Add(new MediaPathInfo(location));
  2592. }
  2593. }
  2594. options.PathInfos = list.ToArray();
  2595. }
  2596. }
  2597. public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
  2598. {
  2599. if (string.IsNullOrWhiteSpace(name))
  2600. {
  2601. throw new ArgumentNullException(nameof(name));
  2602. }
  2603. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2604. var path = Path.Combine(rootFolderPath, name);
  2605. if (!Directory.Exists(path))
  2606. {
  2607. throw new FileNotFoundException("The media folder does not exist");
  2608. }
  2609. LibraryMonitor.Stop();
  2610. try
  2611. {
  2612. Directory.Delete(path, true);
  2613. }
  2614. finally
  2615. {
  2616. CollectionFolder.OnCollectionFolderChange();
  2617. if (refreshLibrary)
  2618. {
  2619. await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
  2620. StartScanInBackground();
  2621. }
  2622. else
  2623. {
  2624. // Need to add a delay here or directory watchers may still pick up the changes
  2625. await Task.Delay(1000).ConfigureAwait(false);
  2626. LibraryMonitor.Start();
  2627. }
  2628. }
  2629. }
  2630. private void RemoveContentTypeOverrides(string path)
  2631. {
  2632. if (string.IsNullOrWhiteSpace(path))
  2633. {
  2634. throw new ArgumentNullException(nameof(path));
  2635. }
  2636. List<NameValuePair>? removeList = null;
  2637. foreach (var contentType in _configurationManager.Configuration.ContentTypes)
  2638. {
  2639. if (string.IsNullOrWhiteSpace(contentType.Name)
  2640. || _fileSystem.AreEqual(path, contentType.Name)
  2641. || _fileSystem.ContainsSubPath(path, contentType.Name))
  2642. {
  2643. (removeList ??= new()).Add(contentType);
  2644. }
  2645. }
  2646. if (removeList is not null)
  2647. {
  2648. _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
  2649. .Except(removeList)
  2650. .ToArray();
  2651. _configurationManager.SaveConfiguration();
  2652. }
  2653. }
  2654. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2655. {
  2656. ArgumentException.ThrowIfNullOrEmpty(mediaPath);
  2657. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2658. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2659. if (!Directory.Exists(virtualFolderPath))
  2660. {
  2661. throw new FileNotFoundException(
  2662. string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolderName));
  2663. }
  2664. var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
  2665. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  2666. .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2667. if (!string.IsNullOrEmpty(shortcut))
  2668. {
  2669. _fileSystem.DeleteFile(shortcut);
  2670. }
  2671. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2672. libraryOptions.PathInfos = libraryOptions
  2673. .PathInfos
  2674. .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
  2675. .ToArray();
  2676. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2677. }
  2678. private static bool ItemIsVisible(BaseItem? item, User? user)
  2679. {
  2680. if (item is null)
  2681. {
  2682. return false;
  2683. }
  2684. if (user is null)
  2685. {
  2686. return true;
  2687. }
  2688. return item is UserRootFolder || item.IsVisibleStandalone(user);
  2689. }
  2690. }
  2691. }