LibraryManager.cs 115 KB

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