LibraryManager.cs 115 KB

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