LibraryManager.cs 110 KB

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