LibraryManager.cs 111 KB

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