LibraryManager.cs 111 KB

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