LibraryManager.cs 110 KB

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