2
0

LibraryManager.cs 119 KB

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