LibraryManager.cs 113 KB

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