LibraryManager.cs 115 KB

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