2
0

LibraryManager.cs 118 KB

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