LibraryManager.cs 116 KB

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