LibraryManager.cs 117 KB

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