2
0

LibraryManager.cs 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376
  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. UseRawName = true,
  911. DtoOptions = options
  912. }).Cast<MusicArtist>()
  913. .OrderBy(i => i.IsAccessedByName ? 1 : 0)
  914. .Cast<T>()
  915. .FirstOrDefault();
  916. if (existing is not null)
  917. {
  918. return existing;
  919. }
  920. }
  921. var path = getPathFn(name);
  922. var id = GetItemByNameId<T>(path);
  923. var item = GetItemById(id) as T;
  924. if (item is null)
  925. {
  926. var info = Directory.CreateDirectory(path);
  927. item = new T
  928. {
  929. Name = name,
  930. Id = id,
  931. DateCreated = info.CreationTimeUtc,
  932. DateModified = info.LastWriteTimeUtc,
  933. Path = path
  934. };
  935. CreateItem(item, null);
  936. }
  937. return item;
  938. }
  939. private Guid GetItemByNameId<T>(string path)
  940. where T : BaseItem, new()
  941. {
  942. var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
  943. return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
  944. }
  945. /// <inheritdoc />
  946. public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
  947. {
  948. // Ensure the location is available.
  949. Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
  950. return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
  951. }
  952. /// <summary>
  953. /// Reloads the root media folder.
  954. /// </summary>
  955. /// <param name="progress">The progress.</param>
  956. /// <param name="cancellationToken">The cancellation token.</param>
  957. /// <returns>Task.</returns>
  958. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  959. {
  960. // Just run the scheduled task so that the user can see it
  961. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  962. return Task.CompletedTask;
  963. }
  964. /// <summary>
  965. /// Validates the media library internal.
  966. /// </summary>
  967. /// <param name="progress">The progress.</param>
  968. /// <param name="cancellationToken">The cancellation token.</param>
  969. /// <returns>Task.</returns>
  970. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  971. {
  972. IsScanRunning = true;
  973. LibraryMonitor.Stop();
  974. try
  975. {
  976. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  977. }
  978. finally
  979. {
  980. LibraryMonitor.Start();
  981. IsScanRunning = false;
  982. }
  983. }
  984. public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
  985. {
  986. RootFolder.Children = null;
  987. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  988. // Start by just validating the children of the root, but go no further
  989. await RootFolder.ValidateChildren(
  990. new Progress<double>(),
  991. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  992. recursive: false,
  993. allowRemoveRoot: removeRoot,
  994. cancellationToken: cancellationToken).ConfigureAwait(false);
  995. var rootFolder = GetUserRootFolder();
  996. rootFolder.Children = null;
  997. await rootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  998. await rootFolder.ValidateChildren(
  999. new Progress<double>(),
  1000. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  1001. recursive: false,
  1002. allowRemoveRoot: removeRoot,
  1003. cancellationToken: cancellationToken).ConfigureAwait(false);
  1004. // Quickly scan CollectionFolders for changes
  1005. var toDelete = new List<Guid>();
  1006. foreach (var child in rootFolder.Children!.OfType<Folder>())
  1007. {
  1008. // If the user has somehow deleted the collection directory, remove the metadata from the database.
  1009. if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
  1010. {
  1011. toDelete.Add(collectionFolder.Id);
  1012. }
  1013. else
  1014. {
  1015. await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  1016. }
  1017. }
  1018. if (toDelete.Count > 0)
  1019. {
  1020. _itemRepository.DeleteItem(toDelete.ToArray());
  1021. }
  1022. }
  1023. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  1024. {
  1025. _logger.LogInformation("Validating media library");
  1026. await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
  1027. var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
  1028. // Validate the entire media library
  1029. await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  1030. progress.Report(96);
  1031. innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
  1032. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  1033. progress.Report(100);
  1034. }
  1035. /// <summary>
  1036. /// Runs the post scan tasks.
  1037. /// </summary>
  1038. /// <param name="progress">The progress.</param>
  1039. /// <param name="cancellationToken">The cancellation token.</param>
  1040. /// <returns>Task.</returns>
  1041. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  1042. {
  1043. var tasks = PostScanTasks.ToList();
  1044. var numComplete = 0;
  1045. var numTasks = tasks.Count;
  1046. foreach (var task in tasks)
  1047. {
  1048. // Prevent access to modified closure
  1049. var currentNumComplete = numComplete;
  1050. var innerProgress = new Progress<double>(pct =>
  1051. {
  1052. double innerPercent = pct;
  1053. innerPercent /= 100;
  1054. innerPercent += currentNumComplete;
  1055. innerPercent /= numTasks;
  1056. innerPercent *= 100;
  1057. progress.Report(innerPercent);
  1058. });
  1059. _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
  1060. try
  1061. {
  1062. await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
  1063. }
  1064. catch (OperationCanceledException)
  1065. {
  1066. _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
  1067. throw;
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. _logger.LogError(ex, "Error running post-scan task");
  1072. }
  1073. numComplete++;
  1074. double percent = numComplete;
  1075. percent /= numTasks;
  1076. progress.Report(percent * 100);
  1077. }
  1078. _itemRepository.UpdateInheritedValues();
  1079. progress.Report(100);
  1080. }
  1081. /// <summary>
  1082. /// Gets the default view.
  1083. /// </summary>
  1084. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  1085. public List<VirtualFolderInfo> GetVirtualFolders()
  1086. {
  1087. return GetVirtualFolders(false);
  1088. }
  1089. public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
  1090. {
  1091. _logger.LogDebug("Getting topLibraryFolders");
  1092. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  1093. _logger.LogDebug("Getting refreshQueue");
  1094. var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
  1095. return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
  1096. .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
  1097. .ToList();
  1098. }
  1099. private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? refreshQueue)
  1100. {
  1101. var info = new VirtualFolderInfo
  1102. {
  1103. Name = Path.GetFileName(dir),
  1104. Locations = _fileSystem.GetFilePaths(dir, false)
  1105. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  1106. .Select(i =>
  1107. {
  1108. try
  1109. {
  1110. return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
  1111. }
  1112. catch (Exception ex)
  1113. {
  1114. _logger.LogError(ex, "Error resolving shortcut file {File}", i);
  1115. return null;
  1116. }
  1117. })
  1118. .Where(i => i is not null)
  1119. .Order()
  1120. .ToArray(),
  1121. CollectionType = GetCollectionType(dir)
  1122. };
  1123. var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.OrdinalIgnoreCase));
  1124. if (libraryFolder is not null)
  1125. {
  1126. var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
  1127. info.ItemId = libraryFolderId;
  1128. if (libraryFolder.HasImage(ImageType.Primary))
  1129. {
  1130. info.PrimaryImageItemId = libraryFolderId;
  1131. }
  1132. info.LibraryOptions = GetLibraryOptions(libraryFolder);
  1133. if (refreshQueue is not null)
  1134. {
  1135. info.RefreshProgress = libraryFolder.GetRefreshProgress();
  1136. info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.Id) ? "Queued" : "Idle";
  1137. }
  1138. }
  1139. return info;
  1140. }
  1141. private CollectionTypeOptions? GetCollectionType(string path)
  1142. {
  1143. var files = _fileSystem.GetFilePaths(path, [".collection"], true, false);
  1144. foreach (ReadOnlySpan<char> file in files)
  1145. {
  1146. if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
  1147. {
  1148. return res;
  1149. }
  1150. }
  1151. return null;
  1152. }
  1153. /// <inheritdoc />
  1154. public BaseItem? GetItemById(Guid id)
  1155. {
  1156. if (id.IsEmpty())
  1157. {
  1158. throw new ArgumentException("Guid can't be empty", nameof(id));
  1159. }
  1160. if (_cache.TryGet(id, out var item))
  1161. {
  1162. return item;
  1163. }
  1164. item = RetrieveItem(id);
  1165. if (item is not null)
  1166. {
  1167. RegisterItem(item);
  1168. }
  1169. return item;
  1170. }
  1171. /// <inheritdoc />
  1172. public T? GetItemById<T>(Guid id)
  1173. where T : BaseItem
  1174. {
  1175. var item = GetItemById(id);
  1176. if (item is T typedItem)
  1177. {
  1178. return typedItem;
  1179. }
  1180. return null;
  1181. }
  1182. /// <inheritdoc />
  1183. public T? GetItemById<T>(Guid id, Guid userId)
  1184. where T : BaseItem
  1185. {
  1186. var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
  1187. return GetItemById<T>(id, user);
  1188. }
  1189. /// <inheritdoc />
  1190. public T? GetItemById<T>(Guid id, User? user)
  1191. where T : BaseItem
  1192. {
  1193. var item = GetItemById<T>(id);
  1194. return ItemIsVisible(item, user) ? item : null;
  1195. }
  1196. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
  1197. {
  1198. if (query.Recursive && !query.ParentId.IsEmpty())
  1199. {
  1200. var parent = GetItemById(query.ParentId);
  1201. if (parent is not null)
  1202. {
  1203. SetTopParentIdsOrAncestors(query, [parent]);
  1204. }
  1205. }
  1206. if (query.User is not null)
  1207. {
  1208. AddUserToQuery(query, query.User, allowExternalContent);
  1209. }
  1210. var itemList = _itemRepository.GetItemList(query);
  1211. var user = query.User;
  1212. if (user is not null)
  1213. {
  1214. return itemList.Where(i => i.IsVisible(user)).ToList();
  1215. }
  1216. return itemList;
  1217. }
  1218. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  1219. {
  1220. return GetItemList(query, true);
  1221. }
  1222. public int GetCount(InternalItemsQuery query)
  1223. {
  1224. if (query.Recursive && !query.ParentId.IsEmpty())
  1225. {
  1226. var parent = GetItemById(query.ParentId);
  1227. if (parent is not null)
  1228. {
  1229. SetTopParentIdsOrAncestors(query, [parent]);
  1230. }
  1231. }
  1232. if (query.User is not null)
  1233. {
  1234. AddUserToQuery(query, query.User);
  1235. }
  1236. return _itemRepository.GetCount(query);
  1237. }
  1238. public ItemCounts GetItemCounts(InternalItemsQuery query)
  1239. {
  1240. if (query.Recursive && !query.ParentId.IsEmpty())
  1241. {
  1242. var parent = GetItemById(query.ParentId);
  1243. if (parent is not null)
  1244. {
  1245. SetTopParentIdsOrAncestors(query, [parent]);
  1246. }
  1247. }
  1248. if (query.User is not null)
  1249. {
  1250. AddUserToQuery(query, query.User);
  1251. }
  1252. return _itemRepository.GetItemCounts(query);
  1253. }
  1254. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
  1255. {
  1256. SetTopParentIdsOrAncestors(query, parents);
  1257. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1258. {
  1259. if (query.User is not null)
  1260. {
  1261. AddUserToQuery(query, query.User);
  1262. }
  1263. }
  1264. return _itemRepository.GetItemList(query);
  1265. }
  1266. public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, CollectionType collectionType)
  1267. {
  1268. SetTopParentIdsOrAncestors(query, parents);
  1269. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1270. {
  1271. if (query.User is not null)
  1272. {
  1273. AddUserToQuery(query, query.User);
  1274. }
  1275. }
  1276. return _itemRepository.GetLatestItemList(query, collectionType);
  1277. }
  1278. public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents, DateTime dateCutoff)
  1279. {
  1280. SetTopParentIdsOrAncestors(query, parents);
  1281. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1282. {
  1283. if (query.User is not null)
  1284. {
  1285. AddUserToQuery(query, query.User);
  1286. }
  1287. }
  1288. return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
  1289. }
  1290. public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
  1291. {
  1292. if (query.User is not null)
  1293. {
  1294. AddUserToQuery(query, query.User);
  1295. }
  1296. if (query.EnableTotalRecordCount)
  1297. {
  1298. return _itemRepository.GetItems(query);
  1299. }
  1300. return new QueryResult<BaseItem>(
  1301. query.StartIndex,
  1302. null,
  1303. _itemRepository.GetItemList(query));
  1304. }
  1305. public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
  1306. {
  1307. if (query.User is not null)
  1308. {
  1309. AddUserToQuery(query, query.User);
  1310. }
  1311. return _itemRepository.GetItemIdsList(query);
  1312. }
  1313. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
  1314. {
  1315. if (query.User is not null)
  1316. {
  1317. AddUserToQuery(query, query.User);
  1318. }
  1319. SetTopParentOrAncestorIds(query);
  1320. return _itemRepository.GetStudios(query);
  1321. }
  1322. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
  1323. {
  1324. if (query.User is not null)
  1325. {
  1326. AddUserToQuery(query, query.User);
  1327. }
  1328. SetTopParentOrAncestorIds(query);
  1329. return _itemRepository.GetGenres(query);
  1330. }
  1331. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
  1332. {
  1333. if (query.User is not null)
  1334. {
  1335. AddUserToQuery(query, query.User);
  1336. }
  1337. SetTopParentOrAncestorIds(query);
  1338. return _itemRepository.GetMusicGenres(query);
  1339. }
  1340. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
  1341. {
  1342. if (query.User is not null)
  1343. {
  1344. AddUserToQuery(query, query.User);
  1345. }
  1346. SetTopParentOrAncestorIds(query);
  1347. return _itemRepository.GetAllArtists(query);
  1348. }
  1349. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
  1350. {
  1351. if (query.User is not null)
  1352. {
  1353. AddUserToQuery(query, query.User);
  1354. }
  1355. SetTopParentOrAncestorIds(query);
  1356. return _itemRepository.GetArtists(query);
  1357. }
  1358. private void SetTopParentOrAncestorIds(InternalItemsQuery query)
  1359. {
  1360. var ancestorIds = query.AncestorIds;
  1361. int len = ancestorIds.Length;
  1362. if (len == 0)
  1363. {
  1364. return;
  1365. }
  1366. var parents = new BaseItem[len];
  1367. for (int i = 0; i < len; i++)
  1368. {
  1369. parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id: {ancestorIds[i]}");
  1370. if (parents[i] is not (ICollectionFolder or UserView))
  1371. {
  1372. return;
  1373. }
  1374. }
  1375. // Optimize by querying against top level views
  1376. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1377. query.AncestorIds = [];
  1378. // Prevent searching in all libraries due to empty filter
  1379. if (query.TopParentIds.Length == 0)
  1380. {
  1381. query.TopParentIds = [Guid.NewGuid()];
  1382. }
  1383. }
  1384. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
  1385. {
  1386. if (query.User is not null)
  1387. {
  1388. AddUserToQuery(query, query.User);
  1389. }
  1390. SetTopParentOrAncestorIds(query);
  1391. return _itemRepository.GetAlbumArtists(query);
  1392. }
  1393. public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
  1394. {
  1395. if (query.Recursive && !query.ParentId.IsEmpty())
  1396. {
  1397. var parent = GetItemById(query.ParentId);
  1398. if (parent is not null)
  1399. {
  1400. SetTopParentIdsOrAncestors(query, [parent]);
  1401. }
  1402. }
  1403. if (query.User is not null)
  1404. {
  1405. AddUserToQuery(query, query.User);
  1406. }
  1407. if (query.EnableTotalRecordCount)
  1408. {
  1409. return _itemRepository.GetItems(query);
  1410. }
  1411. return new QueryResult<BaseItem>(
  1412. query.StartIndex,
  1413. null,
  1414. _itemRepository.GetItemList(query));
  1415. }
  1416. private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
  1417. {
  1418. if (parents.All(i => i is ICollectionFolder || i is UserView))
  1419. {
  1420. // Optimize by querying against top level views
  1421. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1422. // Prevent searching in all libraries due to empty filter
  1423. if (query.TopParentIds.Length == 0)
  1424. {
  1425. query.TopParentIds = [Guid.NewGuid()];
  1426. }
  1427. }
  1428. else
  1429. {
  1430. // We need to be able to query from any arbitrary ancestor up the tree
  1431. query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
  1432. // Prevent searching in all libraries due to empty filter
  1433. if (query.AncestorIds.Length == 0)
  1434. {
  1435. query.AncestorIds = [Guid.NewGuid()];
  1436. }
  1437. }
  1438. query.Parent = null;
  1439. }
  1440. private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
  1441. {
  1442. if (query.AncestorIds.Length == 0 &&
  1443. query.ParentId.IsEmpty() &&
  1444. query.ChannelIds.Count == 0 &&
  1445. query.TopParentIds.Length == 0 &&
  1446. string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
  1447. string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
  1448. query.ItemIds.Length == 0)
  1449. {
  1450. var userViews = UserViewManager.GetUserViews(new UserViewQuery
  1451. {
  1452. User = user,
  1453. IncludeHidden = true,
  1454. IncludeExternalContent = allowExternalContent
  1455. });
  1456. query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
  1457. // Prevent searching in all libraries due to empty filter
  1458. if (query.TopParentIds.Length == 0)
  1459. {
  1460. query.TopParentIds = [Guid.NewGuid()];
  1461. }
  1462. }
  1463. }
  1464. private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
  1465. {
  1466. if (item is UserView view)
  1467. {
  1468. if (view.ViewType == CollectionType.livetv)
  1469. {
  1470. return [view.Id];
  1471. }
  1472. // Translate view into folders
  1473. if (!view.DisplayParentId.IsEmpty())
  1474. {
  1475. var displayParent = GetItemById(view.DisplayParentId);
  1476. if (displayParent is not null)
  1477. {
  1478. return GetTopParentIdsForQuery(displayParent, user);
  1479. }
  1480. return [];
  1481. }
  1482. if (!view.ParentId.IsEmpty())
  1483. {
  1484. var displayParent = GetItemById(view.ParentId);
  1485. if (displayParent is not null)
  1486. {
  1487. return GetTopParentIdsForQuery(displayParent, user);
  1488. }
  1489. return [];
  1490. }
  1491. // Handle grouping
  1492. if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.ViewType)
  1493. && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
  1494. {
  1495. return GetUserRootFolder()
  1496. .GetChildren(user, true)
  1497. .OfType<CollectionFolder>()
  1498. .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
  1499. .Where(i => user.IsFolderGrouped(i.Id))
  1500. .SelectMany(i => GetTopParentIdsForQuery(i, user));
  1501. }
  1502. return [];
  1503. }
  1504. if (item is CollectionFolder collectionFolder)
  1505. {
  1506. return collectionFolder.PhysicalFolderIds;
  1507. }
  1508. var topParent = item.GetTopParent();
  1509. if (topParent is not null)
  1510. {
  1511. return [topParent.Id];
  1512. }
  1513. return [];
  1514. }
  1515. /// <summary>
  1516. /// Gets the intros.
  1517. /// </summary>
  1518. /// <param name="item">The item.</param>
  1519. /// <param name="user">The user.</param>
  1520. /// <returns>IEnumerable{System.String}.</returns>
  1521. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1522. {
  1523. if (IntroProviders.Length == 0)
  1524. {
  1525. return [];
  1526. }
  1527. var tasks = IntroProviders
  1528. .Select(i => GetIntros(i, item, user));
  1529. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1530. return items
  1531. .SelectMany(i => i)
  1532. .Select(ResolveIntro)
  1533. .Where(i => i is not null)!; // null values got filtered out
  1534. }
  1535. /// <summary>
  1536. /// Gets the intros.
  1537. /// </summary>
  1538. /// <param name="provider">The provider.</param>
  1539. /// <param name="item">The item.</param>
  1540. /// <param name="user">The user.</param>
  1541. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1542. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1543. {
  1544. try
  1545. {
  1546. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1547. }
  1548. catch (Exception ex)
  1549. {
  1550. _logger.LogError(ex, "Error getting intros");
  1551. return [];
  1552. }
  1553. }
  1554. /// <summary>
  1555. /// Resolves the intro.
  1556. /// </summary>
  1557. /// <param name="info">The info.</param>
  1558. /// <returns>Video.</returns>
  1559. private Video? ResolveIntro(IntroInfo info)
  1560. {
  1561. Video? video = null;
  1562. if (info.ItemId.HasValue)
  1563. {
  1564. // Get an existing item by Id
  1565. video = GetItemById(info.ItemId.Value) as Video;
  1566. if (video is null)
  1567. {
  1568. _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
  1569. }
  1570. }
  1571. else if (!string.IsNullOrEmpty(info.Path))
  1572. {
  1573. try
  1574. {
  1575. // Try to resolve the path into a video
  1576. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1577. if (video is null)
  1578. {
  1579. _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
  1580. }
  1581. else
  1582. {
  1583. // Pull the saved db item that will include metadata
  1584. var dbItem = GetItemById(video.Id) as Video;
  1585. if (dbItem is not null)
  1586. {
  1587. video = dbItem;
  1588. }
  1589. else
  1590. {
  1591. return null;
  1592. }
  1593. }
  1594. }
  1595. catch (Exception ex)
  1596. {
  1597. _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
  1598. }
  1599. }
  1600. else
  1601. {
  1602. _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1603. }
  1604. return video;
  1605. }
  1606. /// <inheritdoc />
  1607. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortOrder sortOrder)
  1608. {
  1609. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1610. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
  1611. {
  1612. if (orderBy is RandomComparer)
  1613. {
  1614. var randomItems = items.ToArray();
  1615. Random.Shared.Shuffle(randomItems);
  1616. items = randomItems;
  1617. // Items are no longer ordered at this point, so set orderedItems back to null
  1618. orderedItems = null;
  1619. }
  1620. else if (orderedItems is null)
  1621. {
  1622. orderedItems = sortOrder == SortOrder.Descending
  1623. ? items.OrderByDescending(i => i, orderBy)
  1624. : items.OrderBy(i => i, orderBy);
  1625. }
  1626. else
  1627. {
  1628. orderedItems = sortOrder == SortOrder.Descending
  1629. ? orderedItems!.ThenByDescending(i => i, orderBy)
  1630. : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
  1631. }
  1632. }
  1633. return orderedItems ?? items;
  1634. }
  1635. /// <inheritdoc />
  1636. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, SortOrder SortOrder)> orderBy)
  1637. {
  1638. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1639. foreach (var (name, sortOrder) in orderBy)
  1640. {
  1641. var comparer = GetComparer(name, user);
  1642. if (comparer is null)
  1643. {
  1644. continue;
  1645. }
  1646. if (comparer is RandomComparer)
  1647. {
  1648. var randomItems = items.ToArray();
  1649. Random.Shared.Shuffle(randomItems);
  1650. items = randomItems;
  1651. // Items are no longer ordered at this point, so set orderedItems back to null
  1652. orderedItems = null;
  1653. }
  1654. else if (orderedItems is null)
  1655. {
  1656. orderedItems = sortOrder == SortOrder.Descending
  1657. ? items.OrderByDescending(i => i, comparer)
  1658. : items.OrderBy(i => i, comparer);
  1659. }
  1660. else
  1661. {
  1662. orderedItems = sortOrder == SortOrder.Descending
  1663. ? orderedItems!.ThenByDescending(i => i, comparer)
  1664. : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
  1665. }
  1666. }
  1667. return orderedItems ?? items;
  1668. }
  1669. /// <summary>
  1670. /// Gets the comparer.
  1671. /// </summary>
  1672. /// <param name="name">The name.</param>
  1673. /// <param name="user">The user.</param>
  1674. /// <returns>IBaseItemComparer.</returns>
  1675. private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
  1676. {
  1677. var comparer = Comparers.FirstOrDefault(c => name == c.Type);
  1678. // If it requires a user, create a new one, and assign the user
  1679. if (comparer is IUserBaseItemComparer)
  1680. {
  1681. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null for Nullable<T> instances
  1682. userComparer.User = user;
  1683. userComparer.UserManager = _userManager;
  1684. userComparer.UserDataManager = _userDataManager;
  1685. return userComparer;
  1686. }
  1687. return comparer;
  1688. }
  1689. /// <inheritdoc />
  1690. public void CreateItem(BaseItem item, BaseItem? parent)
  1691. {
  1692. CreateItems([item], parent, CancellationToken.None);
  1693. }
  1694. /// <inheritdoc />
  1695. public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
  1696. {
  1697. _itemRepository.SaveItems(items, cancellationToken);
  1698. foreach (var item in items)
  1699. {
  1700. RegisterItem(item);
  1701. }
  1702. if (parent is Folder folder)
  1703. {
  1704. folder.Children = null;
  1705. folder.UserData = null;
  1706. }
  1707. if (ItemAdded is not null)
  1708. {
  1709. foreach (var item in items)
  1710. {
  1711. // With the live tv guide this just creates too much noise
  1712. if (item.SourceType != SourceType.Library)
  1713. {
  1714. continue;
  1715. }
  1716. try
  1717. {
  1718. ItemAdded(
  1719. this,
  1720. new ItemChangeEventArgs
  1721. {
  1722. Item = item,
  1723. Parent = parent ?? item.GetParent()
  1724. });
  1725. }
  1726. catch (Exception ex)
  1727. {
  1728. _logger.LogError(ex, "Error in ItemAdded event handler");
  1729. }
  1730. }
  1731. }
  1732. }
  1733. private bool ImageNeedsRefresh(ItemImageInfo image)
  1734. {
  1735. if (image.Path is not null && image.IsLocalFile)
  1736. {
  1737. if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
  1738. {
  1739. return true;
  1740. }
  1741. try
  1742. {
  1743. return image.DateModified.Subtract(_fileSystem.GetLastWriteTimeUtc(image.Path)).Duration().TotalSeconds > 1;
  1744. }
  1745. catch (Exception ex)
  1746. {
  1747. _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
  1748. return false;
  1749. }
  1750. }
  1751. return image.Path is not null && !image.IsLocalFile;
  1752. }
  1753. /// <inheritdoc />
  1754. public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
  1755. {
  1756. ArgumentNullException.ThrowIfNull(item);
  1757. var outdated = forceUpdate
  1758. ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
  1759. : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
  1760. // Skip image processing if current or live tv source
  1761. if (outdated.Length == 0 || item.SourceType != SourceType.Library)
  1762. {
  1763. RegisterItem(item);
  1764. return;
  1765. }
  1766. foreach (var img in outdated)
  1767. {
  1768. var image = img;
  1769. if (!img.IsLocalFile)
  1770. {
  1771. try
  1772. {
  1773. var index = item.GetImageIndex(img);
  1774. image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
  1775. }
  1776. catch (ArgumentException)
  1777. {
  1778. _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
  1779. continue;
  1780. }
  1781. catch (Exception ex) when (ex is InvalidOperationException or IOException)
  1782. {
  1783. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
  1784. continue;
  1785. }
  1786. catch (HttpRequestException ex)
  1787. {
  1788. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode);
  1789. continue;
  1790. }
  1791. }
  1792. if (!File.Exists(image.Path))
  1793. {
  1794. _logger.LogWarning("Image not found at {ImagePath}", image.Path);
  1795. continue;
  1796. }
  1797. ImageDimensions size;
  1798. try
  1799. {
  1800. size = _imageProcessor.GetImageDimensions(item, image);
  1801. image.Width = size.Width;
  1802. image.Height = size.Height;
  1803. }
  1804. catch (Exception ex)
  1805. {
  1806. _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
  1807. size = default;
  1808. image.Width = 0;
  1809. image.Height = 0;
  1810. }
  1811. try
  1812. {
  1813. var blurhash = _imageProcessor.GetImageBlurHash(image.Path, size);
  1814. image.BlurHash = blurhash;
  1815. }
  1816. catch (Exception ex)
  1817. {
  1818. _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
  1819. image.BlurHash = string.Empty;
  1820. }
  1821. try
  1822. {
  1823. var modifiedDate = _fileSystem.GetLastWriteTimeUtc(image.Path);
  1824. image.DateModified = modifiedDate;
  1825. }
  1826. catch (Exception ex)
  1827. {
  1828. _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
  1829. }
  1830. }
  1831. item.ValidateImages();
  1832. await _itemRepository.SaveImagesAsync(item).ConfigureAwait(false);
  1833. RegisterItem(item);
  1834. }
  1835. /// <inheritdoc />
  1836. public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1837. {
  1838. foreach (var item in items)
  1839. {
  1840. item.DateLastSaved = DateTime.UtcNow;
  1841. await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
  1842. // Modify again, so saved value is after write time of externally saved metadata
  1843. item.DateLastSaved = DateTime.UtcNow;
  1844. }
  1845. _itemRepository.SaveItems(items, cancellationToken);
  1846. if (parent is Folder folder)
  1847. {
  1848. folder.Children = null;
  1849. folder.UserData = null;
  1850. }
  1851. if (ItemUpdated is not null)
  1852. {
  1853. foreach (var item in items)
  1854. {
  1855. // With the live tv guide this just creates too much noise
  1856. if (item.SourceType != SourceType.Library)
  1857. {
  1858. continue;
  1859. }
  1860. try
  1861. {
  1862. ItemUpdated(
  1863. this,
  1864. new ItemChangeEventArgs
  1865. {
  1866. Item = item,
  1867. Parent = parent,
  1868. UpdateReason = updateReason
  1869. });
  1870. }
  1871. catch (Exception ex)
  1872. {
  1873. _logger.LogError(ex, "Error in ItemUpdated event handler");
  1874. }
  1875. }
  1876. }
  1877. }
  1878. /// <inheritdoc />
  1879. public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1880. => UpdateItemsAsync([item], parent, updateReason, cancellationToken);
  1881. public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
  1882. {
  1883. if (item.IsFileProtocol)
  1884. {
  1885. await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
  1886. }
  1887. await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
  1888. }
  1889. /// <summary>
  1890. /// Reports the item removed.
  1891. /// </summary>
  1892. /// <param name="item">The item.</param>
  1893. /// <param name="parent">The parent item.</param>
  1894. public void ReportItemRemoved(BaseItem item, BaseItem parent)
  1895. {
  1896. if (ItemRemoved is not null)
  1897. {
  1898. try
  1899. {
  1900. ItemRemoved(
  1901. this,
  1902. new ItemChangeEventArgs
  1903. {
  1904. Item = item,
  1905. Parent = parent
  1906. });
  1907. }
  1908. catch (Exception ex)
  1909. {
  1910. _logger.LogError(ex, "Error in ItemRemoved event handler");
  1911. }
  1912. }
  1913. }
  1914. /// <summary>
  1915. /// Retrieves the item.
  1916. /// </summary>
  1917. /// <param name="id">The id.</param>
  1918. /// <returns>BaseItem.</returns>
  1919. public BaseItem RetrieveItem(Guid id)
  1920. {
  1921. return _itemRepository.RetrieveItem(id);
  1922. }
  1923. public List<Folder> GetCollectionFolders(BaseItem item)
  1924. {
  1925. return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
  1926. }
  1927. public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1928. {
  1929. while (item is not null)
  1930. {
  1931. var parent = item.GetParent();
  1932. if (parent is AggregateFolder)
  1933. {
  1934. break;
  1935. }
  1936. if (parent is null)
  1937. {
  1938. var owner = item.GetOwner();
  1939. if (owner is null)
  1940. {
  1941. break;
  1942. }
  1943. item = owner;
  1944. }
  1945. else
  1946. {
  1947. item = parent;
  1948. }
  1949. }
  1950. if (item is null)
  1951. {
  1952. return new List<Folder>();
  1953. }
  1954. return GetCollectionFoldersInternal(item, allUserRootChildren);
  1955. }
  1956. private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1957. {
  1958. return allUserRootChildren
  1959. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path.AsSpan(), StringComparison.OrdinalIgnoreCase))
  1960. .ToList();
  1961. }
  1962. public LibraryOptions GetLibraryOptions(BaseItem item)
  1963. {
  1964. if (item is CollectionFolder collectionFolder)
  1965. {
  1966. return collectionFolder.GetLibraryOptions();
  1967. }
  1968. // List.Find is more performant than FirstOrDefault due to enumerator allocation
  1969. return GetCollectionFolders(item)
  1970. .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
  1971. ? collectionFolder2.GetLibraryOptions()
  1972. : new LibraryOptions();
  1973. }
  1974. public CollectionType? GetContentType(BaseItem item)
  1975. {
  1976. var configuredContentType = GetConfiguredContentType(item, false);
  1977. if (configuredContentType is not null)
  1978. {
  1979. return configuredContentType;
  1980. }
  1981. configuredContentType = GetConfiguredContentType(item, true);
  1982. if (configuredContentType is not null)
  1983. {
  1984. return configuredContentType;
  1985. }
  1986. return GetInheritedContentType(item);
  1987. }
  1988. public CollectionType? GetInheritedContentType(BaseItem item)
  1989. {
  1990. var type = GetTopFolderContentType(item);
  1991. if (type is not null)
  1992. {
  1993. return type;
  1994. }
  1995. return item.GetParents()
  1996. .Select(GetConfiguredContentType)
  1997. .LastOrDefault(i => i is not null);
  1998. }
  1999. public CollectionType? GetConfiguredContentType(BaseItem item)
  2000. {
  2001. return GetConfiguredContentType(item, false);
  2002. }
  2003. public CollectionType? GetConfiguredContentType(string path)
  2004. {
  2005. return GetContentTypeOverride(path, false);
  2006. }
  2007. public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  2008. {
  2009. if (item is ICollectionFolder collectionFolder)
  2010. {
  2011. return collectionFolder.CollectionType;
  2012. }
  2013. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  2014. }
  2015. private CollectionType? GetContentTypeOverride(string path, bool inherit)
  2016. {
  2017. var nameValuePair = _configurationManager.Configuration.ContentTypes
  2018. .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
  2019. || (inherit && !string.IsNullOrEmpty(i.Name)
  2020. && _fileSystem.ContainsSubPath(i.Name, path)));
  2021. if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
  2022. {
  2023. return collectionType;
  2024. }
  2025. return null;
  2026. }
  2027. private CollectionType? GetTopFolderContentType(BaseItem item)
  2028. {
  2029. if (item is null)
  2030. {
  2031. return null;
  2032. }
  2033. while (!item.ParentId.IsEmpty())
  2034. {
  2035. var parent = item.GetParent();
  2036. if (parent is null || parent is AggregateFolder)
  2037. {
  2038. break;
  2039. }
  2040. item = parent;
  2041. }
  2042. return GetUserRootFolder().Children
  2043. .OfType<ICollectionFolder>()
  2044. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  2045. .Select(i => i.CollectionType)
  2046. .FirstOrDefault(i => i is not null);
  2047. }
  2048. public UserView GetNamedView(
  2049. User user,
  2050. string name,
  2051. CollectionType? viewType,
  2052. string sortName)
  2053. {
  2054. return GetNamedView(user, name, Guid.Empty, viewType, sortName);
  2055. }
  2056. public UserView GetNamedView(
  2057. string name,
  2058. CollectionType viewType,
  2059. string sortName)
  2060. {
  2061. var path = Path.Combine(
  2062. _configurationManager.ApplicationPaths.InternalMetadataPath,
  2063. "views",
  2064. _fileSystem.GetValidFilename(viewType.ToString()));
  2065. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  2066. var item = GetItemById(id) as UserView;
  2067. var refresh = false;
  2068. if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  2069. {
  2070. var info = Directory.CreateDirectory(path);
  2071. item = new UserView
  2072. {
  2073. Path = path,
  2074. Id = id,
  2075. DateCreated = info.CreationTimeUtc,
  2076. DateModified = info.LastWriteTimeUtc,
  2077. Name = name,
  2078. ViewType = viewType,
  2079. ForcedSortName = sortName
  2080. };
  2081. CreateItem(item, null);
  2082. refresh = true;
  2083. }
  2084. if (refresh)
  2085. {
  2086. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
  2087. ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
  2088. }
  2089. return item;
  2090. }
  2091. public UserView GetNamedView(
  2092. User user,
  2093. string name,
  2094. Guid parentId,
  2095. CollectionType? viewType,
  2096. string sortName)
  2097. {
  2098. var parentIdString = parentId.IsEmpty()
  2099. ? null
  2100. : parentId.ToString("N", CultureInfo.InvariantCulture);
  2101. var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  2102. var id = GetNewItemId(idValues, typeof(UserView));
  2103. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  2104. var item = GetItemById(id) as UserView;
  2105. var isNew = false;
  2106. if (item is null)
  2107. {
  2108. var info = Directory.CreateDirectory(path);
  2109. item = new UserView
  2110. {
  2111. Path = path,
  2112. Id = id,
  2113. DateCreated = info.CreationTimeUtc,
  2114. DateModified = info.LastWriteTimeUtc,
  2115. Name = name,
  2116. ViewType = viewType,
  2117. ForcedSortName = sortName,
  2118. UserId = user.Id,
  2119. DisplayParentId = parentId
  2120. };
  2121. CreateItem(item, null);
  2122. isNew = true;
  2123. }
  2124. var lastRefreshedUtc = item.DateLastRefreshed;
  2125. var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
  2126. if (!refresh && !item.DisplayParentId.IsEmpty())
  2127. {
  2128. var displayParent = GetItemById(item.DisplayParentId);
  2129. refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
  2130. }
  2131. if (refresh)
  2132. {
  2133. ProviderManager.QueueRefresh(
  2134. item.Id,
  2135. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2136. {
  2137. // Need to force save to increment DateLastSaved
  2138. ForceSave = true
  2139. },
  2140. RefreshPriority.Normal);
  2141. }
  2142. return item;
  2143. }
  2144. public UserView GetShadowView(
  2145. BaseItem parent,
  2146. CollectionType? viewType,
  2147. string sortName)
  2148. {
  2149. ArgumentNullException.ThrowIfNull(parent);
  2150. var name = parent.Name;
  2151. var parentId = parent.Id;
  2152. var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
  2153. var id = GetNewItemId(idValues, typeof(UserView));
  2154. var path = parent.Path;
  2155. var item = GetItemById(id) as UserView;
  2156. var isNew = false;
  2157. if (item is null)
  2158. {
  2159. var info = Directory.CreateDirectory(path);
  2160. item = new UserView
  2161. {
  2162. Path = path,
  2163. Id = id,
  2164. DateCreated = info.CreationTimeUtc,
  2165. DateModified = info.LastWriteTimeUtc,
  2166. Name = name,
  2167. ViewType = viewType,
  2168. ForcedSortName = sortName,
  2169. DisplayParentId = parentId
  2170. };
  2171. CreateItem(item, null);
  2172. isNew = true;
  2173. }
  2174. var lastRefreshedUtc = item.DateLastRefreshed;
  2175. var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
  2176. if (!refresh && !item.DisplayParentId.IsEmpty())
  2177. {
  2178. var displayParent = GetItemById(item.DisplayParentId);
  2179. refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
  2180. }
  2181. if (refresh)
  2182. {
  2183. ProviderManager.QueueRefresh(
  2184. item.Id,
  2185. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2186. {
  2187. // Need to force save to increment DateLastSaved
  2188. ForceSave = true
  2189. },
  2190. RefreshPriority.Normal);
  2191. }
  2192. return item;
  2193. }
  2194. public UserView GetNamedView(
  2195. string name,
  2196. Guid parentId,
  2197. CollectionType? viewType,
  2198. string sortName,
  2199. string uniqueId)
  2200. {
  2201. ArgumentException.ThrowIfNullOrEmpty(name);
  2202. var parentIdString = parentId.IsEmpty()
  2203. ? null
  2204. : parentId.ToString("N", CultureInfo.InvariantCulture);
  2205. var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  2206. if (!string.IsNullOrEmpty(uniqueId))
  2207. {
  2208. idValues += uniqueId;
  2209. }
  2210. var id = GetNewItemId(idValues, typeof(UserView));
  2211. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  2212. var item = GetItemById(id) as UserView;
  2213. var isNew = false;
  2214. if (item is null)
  2215. {
  2216. var info = Directory.CreateDirectory(path);
  2217. item = new UserView
  2218. {
  2219. Path = path,
  2220. Id = id,
  2221. DateCreated = info.CreationTimeUtc,
  2222. DateModified = info.LastWriteTimeUtc,
  2223. Name = name,
  2224. ViewType = viewType,
  2225. ForcedSortName = sortName,
  2226. DisplayParentId = parentId
  2227. };
  2228. CreateItem(item, null);
  2229. isNew = true;
  2230. }
  2231. if (viewType != item.ViewType)
  2232. {
  2233. item.ViewType = viewType;
  2234. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult();
  2235. }
  2236. var lastRefreshedUtc = item.DateLastRefreshed;
  2237. var refresh = isNew || DateTime.UtcNow - lastRefreshedUtc >= _viewRefreshInterval;
  2238. if (!refresh && !item.DisplayParentId.IsEmpty())
  2239. {
  2240. var displayParent = GetItemById(item.DisplayParentId);
  2241. refresh = displayParent is not null && displayParent.DateLastSaved > lastRefreshedUtc;
  2242. }
  2243. if (refresh)
  2244. {
  2245. ProviderManager.QueueRefresh(
  2246. item.Id,
  2247. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2248. {
  2249. // Need to force save to increment DateLastSaved
  2250. ForceSave = true
  2251. },
  2252. RefreshPriority.Normal);
  2253. }
  2254. return item;
  2255. }
  2256. public BaseItem GetParentItem(Guid? parentId, Guid? userId)
  2257. {
  2258. if (parentId.HasValue)
  2259. {
  2260. return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}");
  2261. }
  2262. if (!userId.IsNullOrEmpty())
  2263. {
  2264. return GetUserRootFolder();
  2265. }
  2266. return RootFolder;
  2267. }
  2268. /// <inheritdoc />
  2269. public void QueueLibraryScan()
  2270. {
  2271. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  2272. }
  2273. /// <inheritdoc />
  2274. public int? GetSeasonNumberFromPath(string path, Guid? parentId)
  2275. {
  2276. var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
  2277. return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
  2278. }
  2279. /// <inheritdoc />
  2280. public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
  2281. {
  2282. var series = episode.Series;
  2283. bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
  2284. if (!isAbsoluteNaming.Value)
  2285. {
  2286. // In other words, no filter applied
  2287. isAbsoluteNaming = null;
  2288. }
  2289. var resolver = new EpisodeResolver(_namingOptions);
  2290. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
  2291. EpisodeInfo? episodeInfo = null;
  2292. if (episode.IsFileProtocol)
  2293. {
  2294. episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
  2295. // Resolve from parent folder if it's not the Season folder
  2296. var parent = episode.GetParent();
  2297. if (episodeInfo is null && parent.GetType() == typeof(Folder))
  2298. {
  2299. episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
  2300. if (episodeInfo is not null)
  2301. {
  2302. // add the container
  2303. episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
  2304. }
  2305. }
  2306. }
  2307. var changed = false;
  2308. if (episodeInfo is null)
  2309. {
  2310. return changed;
  2311. }
  2312. if (episodeInfo.IsByDate)
  2313. {
  2314. if (episode.IndexNumber.HasValue)
  2315. {
  2316. episode.IndexNumber = null;
  2317. changed = true;
  2318. }
  2319. if (episode.IndexNumberEnd.HasValue)
  2320. {
  2321. episode.IndexNumberEnd = null;
  2322. changed = true;
  2323. }
  2324. if (!episode.PremiereDate.HasValue)
  2325. {
  2326. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  2327. {
  2328. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  2329. }
  2330. if (episode.PremiereDate.HasValue)
  2331. {
  2332. changed = true;
  2333. }
  2334. }
  2335. if (!episode.ProductionYear.HasValue)
  2336. {
  2337. episode.ProductionYear = episodeInfo.Year;
  2338. if (episode.ProductionYear.HasValue)
  2339. {
  2340. changed = true;
  2341. }
  2342. }
  2343. }
  2344. else
  2345. {
  2346. if (!episode.IndexNumber.HasValue || forceRefresh)
  2347. {
  2348. if (episode.IndexNumber != episodeInfo.EpisodeNumber)
  2349. {
  2350. changed = true;
  2351. }
  2352. episode.IndexNumber = episodeInfo.EpisodeNumber;
  2353. }
  2354. if (!episode.IndexNumberEnd.HasValue || forceRefresh)
  2355. {
  2356. if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
  2357. {
  2358. changed = true;
  2359. }
  2360. episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
  2361. }
  2362. if (!episode.ParentIndexNumber.HasValue || forceRefresh)
  2363. {
  2364. if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
  2365. {
  2366. changed = true;
  2367. }
  2368. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  2369. }
  2370. }
  2371. if (!episode.ParentIndexNumber.HasValue)
  2372. {
  2373. var season = episode.Season;
  2374. if (season is not null)
  2375. {
  2376. episode.ParentIndexNumber = season.IndexNumber;
  2377. }
  2378. if (episode.ParentIndexNumber.HasValue)
  2379. {
  2380. changed = true;
  2381. }
  2382. }
  2383. return changed;
  2384. }
  2385. public ItemLookupInfo ParseName(string name)
  2386. {
  2387. var namingOptions = _namingOptions;
  2388. var result = VideoResolver.CleanDateTime(name, namingOptions);
  2389. return new ItemLookupInfo
  2390. {
  2391. Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name,
  2392. Year = result.Year
  2393. };
  2394. }
  2395. public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2396. {
  2397. // Apply .ignore rules
  2398. var filtered = fileSystemChildren.Where(c => !DotIgnoreIgnoreRule.IsIgnored(c, owner)).ToList();
  2399. var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.ContainingFolderPath);
  2400. if (ownerVideoInfo is null)
  2401. {
  2402. yield break;
  2403. }
  2404. var count = filtered.Count;
  2405. for (var i = 0; i < count; i++)
  2406. {
  2407. var current = filtered[i];
  2408. if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
  2409. {
  2410. var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
  2411. var filesInSubFolderList = filesInSubFolder.ToList();
  2412. bool subFolderIsMixedFolder = filesInSubFolderList.Count > 1;
  2413. foreach (var file in filesInSubFolderList)
  2414. {
  2415. if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
  2416. {
  2417. continue;
  2418. }
  2419. var extra = GetExtra(file, extraType.Value, subFolderIsMixedFolder);
  2420. if (extra is not null)
  2421. {
  2422. yield return extra;
  2423. }
  2424. }
  2425. }
  2426. else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo, out var extraType))
  2427. {
  2428. var extra = GetExtra(current, extraType.Value, false);
  2429. if (extra is not null)
  2430. {
  2431. yield return extra;
  2432. }
  2433. }
  2434. }
  2435. BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType, bool isInMixedFolder)
  2436. {
  2437. var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetResolversForExtraType(extraType));
  2438. if (extra is not Video && extra is not Audio)
  2439. {
  2440. return null;
  2441. }
  2442. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2443. var itemById = GetItemById(extra.Id);
  2444. if (itemById is not null)
  2445. {
  2446. extra = itemById;
  2447. }
  2448. // Only update extra type if it is more specific then the currently known extra type
  2449. if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
  2450. {
  2451. extra.ExtraType = extraType;
  2452. }
  2453. extra.ParentId = Guid.Empty;
  2454. extra.OwnerId = owner.Id;
  2455. extra.IsInMixedFolder = isInMixedFolder;
  2456. return extra;
  2457. }
  2458. }
  2459. public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
  2460. {
  2461. foreach (var map in _configurationManager.Configuration.PathSubstitutions)
  2462. {
  2463. if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
  2464. {
  2465. return newPath;
  2466. }
  2467. }
  2468. return path;
  2469. }
  2470. public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
  2471. {
  2472. return _peopleRepository.GetPeople(query);
  2473. }
  2474. public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
  2475. {
  2476. if (item.SupportsPeople)
  2477. {
  2478. var people = GetPeople(new InternalPeopleQuery
  2479. {
  2480. ItemId = item.Id
  2481. });
  2482. if (people.Count > 0)
  2483. {
  2484. return people;
  2485. }
  2486. }
  2487. return [];
  2488. }
  2489. public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
  2490. {
  2491. return _peopleRepository.GetPeopleNames(query)
  2492. .Select(i =>
  2493. {
  2494. try
  2495. {
  2496. return GetPerson(i);
  2497. }
  2498. catch (Exception ex)
  2499. {
  2500. _logger.LogError(ex, "Error getting person");
  2501. return null;
  2502. }
  2503. })
  2504. .Where(i => i is not null)
  2505. .Where(i => query.User is null || i!.IsVisible(query.User))
  2506. .ToList()!; // null values are filtered out
  2507. }
  2508. public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
  2509. {
  2510. return _peopleRepository.GetPeopleNames(query);
  2511. }
  2512. public void UpdatePeople(BaseItem item, List<PersonInfo> people)
  2513. {
  2514. UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
  2515. }
  2516. /// <inheritdoc />
  2517. public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellationToken)
  2518. {
  2519. if (!item.SupportsPeople)
  2520. {
  2521. return;
  2522. }
  2523. if (people is not null)
  2524. {
  2525. people = people.Where(e => e is not null).ToArray();
  2526. _peopleRepository.UpdatePeople(item.Id, people);
  2527. await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
  2528. }
  2529. }
  2530. public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure)
  2531. {
  2532. foreach (var url in image.Path.Split('|'))
  2533. {
  2534. try
  2535. {
  2536. _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2537. await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2538. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2539. return item.GetImageInfo(image.Type, imageIndex);
  2540. }
  2541. catch (HttpRequestException ex)
  2542. {
  2543. if (ex.StatusCode.HasValue
  2544. && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
  2545. {
  2546. _logger.LogDebug(ex, "Error downloading image {Url}", url);
  2547. continue;
  2548. }
  2549. throw;
  2550. }
  2551. }
  2552. if (removeOnFailure)
  2553. {
  2554. // Remove this image to prevent it from retrying over and over
  2555. item.RemoveImage(image);
  2556. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2557. }
  2558. throw new InvalidOperationException("Unable to convert any images to local");
  2559. }
  2560. public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary)
  2561. {
  2562. if (string.IsNullOrWhiteSpace(name))
  2563. {
  2564. throw new ArgumentNullException(nameof(name));
  2565. }
  2566. name = _fileSystem.GetValidFilename(name.Trim());
  2567. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2568. var existingNameCount = 1; // first numbered name will be 2
  2569. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2570. var originalName = name;
  2571. while (Directory.Exists(virtualFolderPath))
  2572. {
  2573. existingNameCount++;
  2574. name = originalName + existingNameCount;
  2575. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2576. }
  2577. var mediaPathInfos = options.PathInfos;
  2578. if (mediaPathInfos is not null)
  2579. {
  2580. var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
  2581. if (invalidpath is not null)
  2582. {
  2583. throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
  2584. }
  2585. }
  2586. LibraryMonitor.Stop();
  2587. try
  2588. {
  2589. Directory.CreateDirectory(virtualFolderPath);
  2590. if (collectionType is not null)
  2591. {
  2592. var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collection"); // Can't be null with legal values?
  2593. FileHelper.CreateEmpty(path);
  2594. }
  2595. CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
  2596. if (mediaPathInfos is not null)
  2597. {
  2598. foreach (var path in mediaPathInfos)
  2599. {
  2600. AddMediaPathInternal(name, path, false);
  2601. }
  2602. }
  2603. }
  2604. finally
  2605. {
  2606. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2607. if (refreshLibrary)
  2608. {
  2609. StartScanInBackground();
  2610. }
  2611. else
  2612. {
  2613. // Need to add a delay here or directory watchers may still pick up the changes
  2614. await Task.Delay(1000).ConfigureAwait(false);
  2615. LibraryMonitor.Start();
  2616. }
  2617. }
  2618. }
  2619. private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
  2620. {
  2621. foreach (var person in people)
  2622. {
  2623. cancellationToken.ThrowIfCancellationRequested();
  2624. var itemUpdateType = ItemUpdateType.MetadataDownload;
  2625. var saveEntity = false;
  2626. var createEntity = false;
  2627. var personEntity = GetPerson(person.Name);
  2628. if (personEntity is null)
  2629. {
  2630. try
  2631. {
  2632. var path = Person.GetPath(person.Name);
  2633. var info = Directory.CreateDirectory(path);
  2634. personEntity = new Person()
  2635. {
  2636. Name = person.Name,
  2637. Id = GetItemByNameId<Person>(path),
  2638. DateCreated = info.CreationTimeUtc,
  2639. DateModified = info.LastWriteTimeUtc,
  2640. Path = path
  2641. };
  2642. personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
  2643. saveEntity = true;
  2644. createEntity = true;
  2645. }
  2646. catch (Exception ex)
  2647. {
  2648. _logger.LogWarning(ex, "Failed to create person {Name}", person.Name);
  2649. continue;
  2650. }
  2651. }
  2652. foreach (var id in person.ProviderIds)
  2653. {
  2654. if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase))
  2655. {
  2656. personEntity.SetProviderId(id.Key, id.Value);
  2657. saveEntity = true;
  2658. }
  2659. }
  2660. if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
  2661. {
  2662. personEntity.SetImage(
  2663. new ItemImageInfo
  2664. {
  2665. Path = person.ImageUrl,
  2666. Type = ImageType.Primary
  2667. },
  2668. 0);
  2669. saveEntity = true;
  2670. itemUpdateType = ItemUpdateType.ImageUpdate;
  2671. }
  2672. if (saveEntity)
  2673. {
  2674. if (createEntity)
  2675. {
  2676. CreateItems([personEntity], null, CancellationToken.None);
  2677. }
  2678. await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
  2679. personEntity.DateLastSaved = DateTime.UtcNow;
  2680. CreateItems([personEntity], null, CancellationToken.None);
  2681. }
  2682. }
  2683. }
  2684. private void StartScanInBackground()
  2685. {
  2686. Task.Run(() =>
  2687. {
  2688. // No need to start if scanning the library because it will handle it
  2689. ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  2690. });
  2691. }
  2692. public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2693. {
  2694. AddMediaPathInternal(virtualFolderName, mediaPath, true);
  2695. }
  2696. private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
  2697. {
  2698. ArgumentNullException.ThrowIfNull(pathInfo);
  2699. var path = pathInfo.Path;
  2700. if (string.IsNullOrWhiteSpace(path))
  2701. {
  2702. throw new ArgumentException(nameof(path));
  2703. }
  2704. if (!Directory.Exists(path))
  2705. {
  2706. throw new FileNotFoundException("The path does not exist.");
  2707. }
  2708. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2709. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2710. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  2711. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2712. while (File.Exists(lnk))
  2713. {
  2714. shortcutFilename += "1";
  2715. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2716. }
  2717. _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
  2718. RemoveContentTypeOverrides(path);
  2719. if (saveLibraryOptions)
  2720. {
  2721. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2722. libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
  2723. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2724. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2725. }
  2726. }
  2727. public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2728. {
  2729. ArgumentNullException.ThrowIfNull(mediaPath);
  2730. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2731. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2732. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2733. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2734. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2735. }
  2736. private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
  2737. {
  2738. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  2739. var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
  2740. if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
  2741. {
  2742. var list = options.PathInfos.ToList();
  2743. foreach (var location in info.Locations)
  2744. {
  2745. if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
  2746. {
  2747. list.Add(new MediaPathInfo(location));
  2748. }
  2749. }
  2750. options.PathInfos = list.ToArray();
  2751. }
  2752. }
  2753. public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
  2754. {
  2755. if (string.IsNullOrWhiteSpace(name))
  2756. {
  2757. throw new ArgumentNullException(nameof(name));
  2758. }
  2759. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2760. var path = Path.Combine(rootFolderPath, name);
  2761. if (!Directory.Exists(path))
  2762. {
  2763. throw new FileNotFoundException("The media folder does not exist");
  2764. }
  2765. LibraryMonitor.Stop();
  2766. try
  2767. {
  2768. Directory.Delete(path, true);
  2769. }
  2770. finally
  2771. {
  2772. CollectionFolder.OnCollectionFolderChange();
  2773. if (refreshLibrary)
  2774. {
  2775. await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
  2776. StartScanInBackground();
  2777. }
  2778. else
  2779. {
  2780. // Need to add a delay here or directory watchers may still pick up the changes
  2781. await Task.Delay(1000).ConfigureAwait(false);
  2782. LibraryMonitor.Start();
  2783. }
  2784. }
  2785. }
  2786. private void RemoveContentTypeOverrides(string path)
  2787. {
  2788. if (string.IsNullOrWhiteSpace(path))
  2789. {
  2790. throw new ArgumentNullException(nameof(path));
  2791. }
  2792. List<NameValuePair>? removeList = null;
  2793. foreach (var contentType in _configurationManager.Configuration.ContentTypes)
  2794. {
  2795. if (string.IsNullOrWhiteSpace(contentType.Name)
  2796. || _fileSystem.AreEqual(path, contentType.Name)
  2797. || _fileSystem.ContainsSubPath(path, contentType.Name))
  2798. {
  2799. (removeList ??= new()).Add(contentType);
  2800. }
  2801. }
  2802. if (removeList is not null)
  2803. {
  2804. _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
  2805. .Except(removeList)
  2806. .ToArray();
  2807. _configurationManager.SaveConfiguration();
  2808. }
  2809. }
  2810. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2811. {
  2812. ArgumentException.ThrowIfNullOrEmpty(mediaPath);
  2813. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2814. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2815. if (!Directory.Exists(virtualFolderPath))
  2816. {
  2817. throw new FileNotFoundException(
  2818. string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolderName));
  2819. }
  2820. var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
  2821. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  2822. .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2823. if (!string.IsNullOrEmpty(shortcut))
  2824. {
  2825. _fileSystem.DeleteFile(shortcut);
  2826. }
  2827. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2828. libraryOptions.PathInfos = libraryOptions
  2829. .PathInfos
  2830. .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
  2831. .ToArray();
  2832. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2833. }
  2834. private static bool ItemIsVisible(BaseItem? item, User? user)
  2835. {
  2836. if (item is null)
  2837. {
  2838. return false;
  2839. }
  2840. if (user is null)
  2841. {
  2842. return true;
  2843. }
  2844. return item is UserRootFolder || item.IsVisibleStandalone(user);
  2845. }
  2846. }
  2847. }