LibraryManager.cs 113 KB

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