LibraryManager.cs 114 KB

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