LibraryManager.cs 113 KB

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