LibraryManager.cs 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258
  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. Directory.CreateDirectory(rootFolderPath);
  668. var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ??
  669. (ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)) as Folder ?? throw new InvalidOperationException("Something went very wong"))
  670. .DeepCopy<Folder, AggregateFolder>();
  671. // In case program data folder was moved
  672. if (!string.Equals(rootFolder.Path, rootFolderPath, StringComparison.Ordinal))
  673. {
  674. _logger.LogInformation("Resetting root folder path to {0}", rootFolderPath);
  675. rootFolder.Path = rootFolderPath;
  676. }
  677. // Add in the plug-in folders
  678. var path = Path.Combine(_configurationManager.ApplicationPaths.DataPath, "playlists");
  679. Directory.CreateDirectory(path);
  680. Folder folder = new PlaylistsFolder
  681. {
  682. Path = path
  683. };
  684. if (folder.Id.IsEmpty())
  685. {
  686. folder.Id = GetNewItemId(folder.Path, folder.GetType());
  687. }
  688. var dbItem = GetItemById(folder.Id) as BasePluginFolder;
  689. if (dbItem is not null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
  690. {
  691. folder = dbItem;
  692. }
  693. if (!folder.ParentId.Equals(rootFolder.Id))
  694. {
  695. folder.ParentId = rootFolder.Id;
  696. folder.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
  697. }
  698. rootFolder.AddVirtualChild(folder);
  699. RegisterItem(folder);
  700. return rootFolder;
  701. }
  702. public Folder GetUserRootFolder()
  703. {
  704. if (_userRootFolder is null)
  705. {
  706. lock (_userRootFolderSyncLock)
  707. {
  708. if (_userRootFolder is null)
  709. {
  710. var userRootPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  711. _logger.LogDebug("Creating userRootPath at {Path}", userRootPath);
  712. Directory.CreateDirectory(userRootPath);
  713. var newItemId = GetNewItemId(userRootPath, typeof(UserRootFolder));
  714. UserRootFolder? tmpItem = null;
  715. try
  716. {
  717. tmpItem = GetItemById(newItemId) as UserRootFolder;
  718. }
  719. catch (Exception ex)
  720. {
  721. _logger.LogError(ex, "Error creating UserRootFolder {Path}", newItemId);
  722. }
  723. if (tmpItem is null)
  724. {
  725. _logger.LogDebug("Creating new userRootFolder with DeepCopy");
  726. tmpItem = (ResolvePath(_fileSystem.GetDirectoryInfo(userRootPath)) as Folder ?? throw new InvalidOperationException("Failed to get user root path"))
  727. .DeepCopy<Folder, UserRootFolder>();
  728. }
  729. // In case program data folder was moved
  730. if (!string.Equals(tmpItem.Path, userRootPath, StringComparison.Ordinal))
  731. {
  732. _logger.LogInformation("Resetting user root folder path to {0}", userRootPath);
  733. tmpItem.Path = userRootPath;
  734. }
  735. _userRootFolder = tmpItem;
  736. _logger.LogDebug("Setting userRootFolder: {Folder}", _userRootFolder);
  737. }
  738. }
  739. }
  740. return _userRootFolder;
  741. }
  742. /// <inheritdoc />
  743. public BaseItem? FindByPath(string path, bool? isFolder)
  744. {
  745. // If this returns multiple items it could be tricky figuring out which one is correct.
  746. // In most cases, the newest one will be and the others obsolete but not yet cleaned up
  747. ArgumentException.ThrowIfNullOrEmpty(path);
  748. var query = new InternalItemsQuery
  749. {
  750. Path = path,
  751. IsFolder = isFolder,
  752. OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
  753. Limit = 1,
  754. DtoOptions = new DtoOptions(true)
  755. };
  756. return GetItemList(query)
  757. .FirstOrDefault();
  758. }
  759. /// <inheritdoc />
  760. public Person? GetPerson(string name)
  761. {
  762. var path = Person.GetPath(name);
  763. var id = GetItemByNameId<Person>(path);
  764. if (GetItemById(id) is Person item)
  765. {
  766. return item;
  767. }
  768. return null;
  769. }
  770. /// <summary>
  771. /// Gets the studio.
  772. /// </summary>
  773. /// <param name="name">The name.</param>
  774. /// <returns>Task{Studio}.</returns>
  775. public Studio GetStudio(string name)
  776. {
  777. return CreateItemByName<Studio>(Studio.GetPath, name, new DtoOptions(true));
  778. }
  779. public Guid GetStudioId(string name)
  780. {
  781. return GetItemByNameId<Studio>(Studio.GetPath(name));
  782. }
  783. public Guid GetGenreId(string name)
  784. {
  785. return GetItemByNameId<Genre>(Genre.GetPath(name));
  786. }
  787. public Guid GetMusicGenreId(string name)
  788. {
  789. return GetItemByNameId<MusicGenre>(MusicGenre.GetPath(name));
  790. }
  791. /// <summary>
  792. /// Gets the genre.
  793. /// </summary>
  794. /// <param name="name">The name.</param>
  795. /// <returns>Task{Genre}.</returns>
  796. public Genre GetGenre(string name)
  797. {
  798. return CreateItemByName<Genre>(Genre.GetPath, name, new DtoOptions(true));
  799. }
  800. /// <summary>
  801. /// Gets the music genre.
  802. /// </summary>
  803. /// <param name="name">The name.</param>
  804. /// <returns>Task{MusicGenre}.</returns>
  805. public MusicGenre GetMusicGenre(string name)
  806. {
  807. return CreateItemByName<MusicGenre>(MusicGenre.GetPath, name, new DtoOptions(true));
  808. }
  809. /// <summary>
  810. /// Gets the year.
  811. /// </summary>
  812. /// <param name="value">The value.</param>
  813. /// <returns>Task{Year}.</returns>
  814. public Year GetYear(int value)
  815. {
  816. if (value <= 0)
  817. {
  818. throw new ArgumentOutOfRangeException(nameof(value), "Years less than or equal to 0 are invalid.");
  819. }
  820. var name = value.ToString(CultureInfo.InvariantCulture);
  821. return CreateItemByName<Year>(Year.GetPath, name, new DtoOptions(true));
  822. }
  823. /// <summary>
  824. /// Gets a Genre.
  825. /// </summary>
  826. /// <param name="name">The name.</param>
  827. /// <returns>Task{Genre}.</returns>
  828. public MusicArtist GetArtist(string name)
  829. {
  830. return GetArtist(name, new DtoOptions(true));
  831. }
  832. public MusicArtist GetArtist(string name, DtoOptions options)
  833. {
  834. return CreateItemByName<MusicArtist>(MusicArtist.GetPath, name, options);
  835. }
  836. private T CreateItemByName<T>(Func<string, string> getPathFn, string name, DtoOptions options)
  837. where T : BaseItem, new()
  838. {
  839. if (typeof(T) == typeof(MusicArtist))
  840. {
  841. var existing = GetItemList(new InternalItemsQuery
  842. {
  843. IncludeItemTypes = new[] { BaseItemKind.MusicArtist },
  844. Name = name,
  845. DtoOptions = options
  846. }).Cast<MusicArtist>()
  847. .OrderBy(i => i.IsAccessedByName ? 1 : 0)
  848. .Cast<T>()
  849. .FirstOrDefault();
  850. if (existing is not null)
  851. {
  852. return existing;
  853. }
  854. }
  855. var path = getPathFn(name);
  856. var id = GetItemByNameId<T>(path);
  857. var item = GetItemById(id) as T;
  858. if (item is null)
  859. {
  860. item = new T
  861. {
  862. Name = name,
  863. Id = id,
  864. DateCreated = DateTime.UtcNow,
  865. DateModified = DateTime.UtcNow,
  866. Path = path
  867. };
  868. CreateItem(item, null);
  869. }
  870. return item;
  871. }
  872. private Guid GetItemByNameId<T>(string path)
  873. where T : BaseItem, new()
  874. {
  875. var forceCaseInsensitiveId = _configurationManager.Configuration.EnableNormalizedItemByNameIds;
  876. return GetNewItemIdInternal(path, typeof(T), forceCaseInsensitiveId);
  877. }
  878. /// <inheritdoc />
  879. public Task ValidatePeopleAsync(IProgress<double> progress, CancellationToken cancellationToken)
  880. {
  881. // Ensure the location is available.
  882. Directory.CreateDirectory(_configurationManager.ApplicationPaths.PeoplePath);
  883. return new PeopleValidator(this, _logger, _fileSystem).ValidatePeople(cancellationToken, progress);
  884. }
  885. /// <summary>
  886. /// Reloads the root media folder.
  887. /// </summary>
  888. /// <param name="progress">The progress.</param>
  889. /// <param name="cancellationToken">The cancellation token.</param>
  890. /// <returns>Task.</returns>
  891. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  892. {
  893. // Just run the scheduled task so that the user can see it
  894. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  895. return Task.CompletedTask;
  896. }
  897. /// <summary>
  898. /// Validates the media library internal.
  899. /// </summary>
  900. /// <param name="progress">The progress.</param>
  901. /// <param name="cancellationToken">The cancellation token.</param>
  902. /// <returns>Task.</returns>
  903. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  904. {
  905. IsScanRunning = true;
  906. LibraryMonitor.Stop();
  907. try
  908. {
  909. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  910. }
  911. finally
  912. {
  913. LibraryMonitor.Start();
  914. IsScanRunning = false;
  915. }
  916. }
  917. public async Task ValidateTopLibraryFolders(CancellationToken cancellationToken, bool removeRoot = false)
  918. {
  919. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  920. // Start by just validating the children of the root, but go no further
  921. await RootFolder.ValidateChildren(
  922. new Progress<double>(),
  923. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  924. recursive: false,
  925. allowRemoveRoot: removeRoot,
  926. cancellationToken: cancellationToken).ConfigureAwait(false);
  927. await GetUserRootFolder().RefreshMetadata(cancellationToken).ConfigureAwait(false);
  928. await GetUserRootFolder().ValidateChildren(
  929. new Progress<double>(),
  930. new MetadataRefreshOptions(new DirectoryService(_fileSystem)),
  931. recursive: false,
  932. allowRemoveRoot: removeRoot,
  933. cancellationToken: cancellationToken).ConfigureAwait(false);
  934. // Quickly scan CollectionFolders for changes
  935. foreach (var child in GetUserRootFolder().Children.OfType<Folder>())
  936. {
  937. // If the user has somehow deleted the collection directory, remove the metadata from the database.
  938. if (child is CollectionFolder collectionFolder && !Directory.Exists(collectionFolder.Path))
  939. {
  940. _itemRepository.DeleteItem(collectionFolder.Id);
  941. }
  942. else
  943. {
  944. await child.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  945. }
  946. }
  947. }
  948. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  949. {
  950. _logger.LogInformation("Validating media library");
  951. await ValidateTopLibraryFolders(cancellationToken).ConfigureAwait(false);
  952. var innerProgress = new Progress<double>(pct => progress.Report(pct * 0.96));
  953. // Validate the entire media library
  954. await RootFolder.ValidateChildren(innerProgress, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), recursive: true, cancellationToken: cancellationToken).ConfigureAwait(false);
  955. progress.Report(96);
  956. innerProgress = new Progress<double>(pct => progress.Report(96 + (pct * .04)));
  957. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  958. progress.Report(100);
  959. }
  960. /// <summary>
  961. /// Runs the post scan tasks.
  962. /// </summary>
  963. /// <param name="progress">The progress.</param>
  964. /// <param name="cancellationToken">The cancellation token.</param>
  965. /// <returns>Task.</returns>
  966. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  967. {
  968. var tasks = PostscanTasks.ToList();
  969. var numComplete = 0;
  970. var numTasks = tasks.Count;
  971. foreach (var task in tasks)
  972. {
  973. // Prevent access to modified closure
  974. var currentNumComplete = numComplete;
  975. var innerProgress = new Progress<double>(pct =>
  976. {
  977. double innerPercent = pct;
  978. innerPercent /= 100;
  979. innerPercent += currentNumComplete;
  980. innerPercent /= numTasks;
  981. innerPercent *= 100;
  982. progress.Report(innerPercent);
  983. });
  984. _logger.LogDebug("Running post-scan task {0}", task.GetType().Name);
  985. try
  986. {
  987. await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
  988. }
  989. catch (OperationCanceledException)
  990. {
  991. _logger.LogInformation("Post-scan task cancelled: {0}", task.GetType().Name);
  992. throw;
  993. }
  994. catch (Exception ex)
  995. {
  996. _logger.LogError(ex, "Error running post-scan task");
  997. }
  998. numComplete++;
  999. double percent = numComplete;
  1000. percent /= numTasks;
  1001. progress.Report(percent * 100);
  1002. }
  1003. _itemRepository.UpdateInheritedValues();
  1004. progress.Report(100);
  1005. }
  1006. /// <summary>
  1007. /// Gets the default view.
  1008. /// </summary>
  1009. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  1010. public List<VirtualFolderInfo> GetVirtualFolders()
  1011. {
  1012. return GetVirtualFolders(false);
  1013. }
  1014. public List<VirtualFolderInfo> GetVirtualFolders(bool includeRefreshState)
  1015. {
  1016. _logger.LogDebug("Getting topLibraryFolders");
  1017. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  1018. _logger.LogDebug("Getting refreshQueue");
  1019. var refreshQueue = includeRefreshState ? ProviderManager.GetRefreshQueue() : null;
  1020. return _fileSystem.GetDirectoryPaths(_configurationManager.ApplicationPaths.DefaultUserViewsPath)
  1021. .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders, refreshQueue))
  1022. .ToList();
  1023. }
  1024. private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> allCollectionFolders, HashSet<Guid>? refreshQueue)
  1025. {
  1026. var info = new VirtualFolderInfo
  1027. {
  1028. Name = Path.GetFileName(dir),
  1029. Locations = _fileSystem.GetFilePaths(dir, false)
  1030. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  1031. .Select(i =>
  1032. {
  1033. try
  1034. {
  1035. return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i));
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. _logger.LogError(ex, "Error resolving shortcut file {File}", i);
  1040. return null;
  1041. }
  1042. })
  1043. .Where(i => i is not null)
  1044. .Order()
  1045. .ToArray(),
  1046. CollectionType = GetCollectionType(dir)
  1047. };
  1048. var libraryFolder = allCollectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.OrdinalIgnoreCase));
  1049. if (libraryFolder is not null)
  1050. {
  1051. var libraryFolderId = libraryFolder.Id.ToString("N", CultureInfo.InvariantCulture);
  1052. info.ItemId = libraryFolderId;
  1053. if (libraryFolder.HasImage(ImageType.Primary))
  1054. {
  1055. info.PrimaryImageItemId = libraryFolderId;
  1056. }
  1057. info.LibraryOptions = GetLibraryOptions(libraryFolder);
  1058. if (refreshQueue is not null)
  1059. {
  1060. info.RefreshProgress = libraryFolder.GetRefreshProgress();
  1061. info.RefreshStatus = info.RefreshProgress.HasValue ? "Active" : refreshQueue.Contains(libraryFolder.Id) ? "Queued" : "Idle";
  1062. }
  1063. }
  1064. return info;
  1065. }
  1066. private CollectionTypeOptions? GetCollectionType(string path)
  1067. {
  1068. var files = _fileSystem.GetFilePaths(path, new[] { ".collection" }, true, false);
  1069. foreach (ReadOnlySpan<char> file in files)
  1070. {
  1071. if (Enum.TryParse<CollectionTypeOptions>(Path.GetFileNameWithoutExtension(file), true, out var res))
  1072. {
  1073. return res;
  1074. }
  1075. }
  1076. return null;
  1077. }
  1078. /// <inheritdoc />
  1079. public BaseItem? GetItemById(Guid id)
  1080. {
  1081. if (id.IsEmpty())
  1082. {
  1083. throw new ArgumentException("Guid can't be empty", nameof(id));
  1084. }
  1085. if (_cache.TryGet(id, out var item))
  1086. {
  1087. return item;
  1088. }
  1089. item = RetrieveItem(id);
  1090. if (item is not null)
  1091. {
  1092. RegisterItem(item);
  1093. }
  1094. return item;
  1095. }
  1096. /// <inheritdoc />
  1097. public T? GetItemById<T>(Guid id)
  1098. where T : BaseItem
  1099. {
  1100. var item = GetItemById(id);
  1101. if (item is T typedItem)
  1102. {
  1103. return typedItem;
  1104. }
  1105. return null;
  1106. }
  1107. /// <inheritdoc />
  1108. public T? GetItemById<T>(Guid id, Guid userId)
  1109. where T : BaseItem
  1110. {
  1111. var user = userId.IsEmpty() ? null : _userManager.GetUserById(userId);
  1112. return GetItemById<T>(id, user);
  1113. }
  1114. /// <inheritdoc />
  1115. public T? GetItemById<T>(Guid id, User? user)
  1116. where T : BaseItem
  1117. {
  1118. var item = GetItemById<T>(id);
  1119. return ItemIsVisible(item, user) ? item : null;
  1120. }
  1121. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
  1122. {
  1123. if (query.Recursive && !query.ParentId.IsEmpty())
  1124. {
  1125. var parent = GetItemById(query.ParentId);
  1126. if (parent is not null)
  1127. {
  1128. SetTopParentIdsOrAncestors(query, new[] { parent });
  1129. }
  1130. }
  1131. if (query.User is not null)
  1132. {
  1133. AddUserToQuery(query, query.User, allowExternalContent);
  1134. }
  1135. var itemList = _itemRepository.GetItemList(query);
  1136. var user = query.User;
  1137. if (user is not null)
  1138. {
  1139. return itemList.Where(i => i.IsVisible(user)).ToList();
  1140. }
  1141. return itemList;
  1142. }
  1143. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
  1144. {
  1145. return GetItemList(query, true);
  1146. }
  1147. public int GetCount(InternalItemsQuery query)
  1148. {
  1149. if (query.Recursive && !query.ParentId.IsEmpty())
  1150. {
  1151. var parent = GetItemById(query.ParentId);
  1152. if (parent is not null)
  1153. {
  1154. SetTopParentIdsOrAncestors(query, new[] { parent });
  1155. }
  1156. }
  1157. if (query.User is not null)
  1158. {
  1159. AddUserToQuery(query, query.User);
  1160. }
  1161. return _itemRepository.GetCount(query);
  1162. }
  1163. public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
  1164. {
  1165. SetTopParentIdsOrAncestors(query, parents);
  1166. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1167. {
  1168. if (query.User is not null)
  1169. {
  1170. AddUserToQuery(query, query.User);
  1171. }
  1172. }
  1173. return _itemRepository.GetItemList(query);
  1174. }
  1175. public IReadOnlyList<BaseItem> GetLatestItemList(InternalItemsQuery query, IReadOnlyList<BaseItem> parents, CollectionType collectionType)
  1176. {
  1177. SetTopParentIdsOrAncestors(query, parents);
  1178. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1179. {
  1180. if (query.User is not null)
  1181. {
  1182. AddUserToQuery(query, query.User);
  1183. }
  1184. }
  1185. return _itemRepository.GetLatestItemList(query, collectionType);
  1186. }
  1187. public IReadOnlyList<string> GetNextUpSeriesKeys(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents, DateTime dateCutoff)
  1188. {
  1189. SetTopParentIdsOrAncestors(query, parents);
  1190. if (query.AncestorIds.Length == 0 && query.TopParentIds.Length == 0)
  1191. {
  1192. if (query.User is not null)
  1193. {
  1194. AddUserToQuery(query, query.User);
  1195. }
  1196. }
  1197. return _itemRepository.GetNextUpSeriesKeys(query, dateCutoff);
  1198. }
  1199. public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
  1200. {
  1201. if (query.User is not null)
  1202. {
  1203. AddUserToQuery(query, query.User);
  1204. }
  1205. if (query.EnableTotalRecordCount)
  1206. {
  1207. return _itemRepository.GetItems(query);
  1208. }
  1209. return new QueryResult<BaseItem>(
  1210. query.StartIndex,
  1211. null,
  1212. _itemRepository.GetItemList(query));
  1213. }
  1214. public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
  1215. {
  1216. if (query.User is not null)
  1217. {
  1218. AddUserToQuery(query, query.User);
  1219. }
  1220. return _itemRepository.GetItemIdsList(query);
  1221. }
  1222. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetStudios(InternalItemsQuery query)
  1223. {
  1224. if (query.User is not null)
  1225. {
  1226. AddUserToQuery(query, query.User);
  1227. }
  1228. SetTopParentOrAncestorIds(query);
  1229. return _itemRepository.GetStudios(query);
  1230. }
  1231. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetGenres(InternalItemsQuery query)
  1232. {
  1233. if (query.User is not null)
  1234. {
  1235. AddUserToQuery(query, query.User);
  1236. }
  1237. SetTopParentOrAncestorIds(query);
  1238. return _itemRepository.GetGenres(query);
  1239. }
  1240. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetMusicGenres(InternalItemsQuery query)
  1241. {
  1242. if (query.User is not null)
  1243. {
  1244. AddUserToQuery(query, query.User);
  1245. }
  1246. SetTopParentOrAncestorIds(query);
  1247. return _itemRepository.GetMusicGenres(query);
  1248. }
  1249. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAllArtists(InternalItemsQuery query)
  1250. {
  1251. if (query.User is not null)
  1252. {
  1253. AddUserToQuery(query, query.User);
  1254. }
  1255. SetTopParentOrAncestorIds(query);
  1256. return _itemRepository.GetAllArtists(query);
  1257. }
  1258. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetArtists(InternalItemsQuery query)
  1259. {
  1260. if (query.User is not null)
  1261. {
  1262. AddUserToQuery(query, query.User);
  1263. }
  1264. SetTopParentOrAncestorIds(query);
  1265. return _itemRepository.GetArtists(query);
  1266. }
  1267. private void SetTopParentOrAncestorIds(InternalItemsQuery query)
  1268. {
  1269. var ancestorIds = query.AncestorIds;
  1270. int len = ancestorIds.Length;
  1271. if (len == 0)
  1272. {
  1273. return;
  1274. }
  1275. var parents = new BaseItem[len];
  1276. for (int i = 0; i < len; i++)
  1277. {
  1278. parents[i] = GetItemById(ancestorIds[i]) ?? throw new ArgumentException($"Failed to find parent with id: {ancestorIds[i]}");
  1279. if (parents[i] is not (ICollectionFolder or UserView))
  1280. {
  1281. return;
  1282. }
  1283. }
  1284. // Optimize by querying against top level views
  1285. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1286. query.AncestorIds = [];
  1287. // Prevent searching in all libraries due to empty filter
  1288. if (query.TopParentIds.Length == 0)
  1289. {
  1290. query.TopParentIds = [Guid.NewGuid()];
  1291. }
  1292. }
  1293. public QueryResult<(BaseItem Item, ItemCounts ItemCounts)> GetAlbumArtists(InternalItemsQuery query)
  1294. {
  1295. if (query.User is not null)
  1296. {
  1297. AddUserToQuery(query, query.User);
  1298. }
  1299. SetTopParentOrAncestorIds(query);
  1300. return _itemRepository.GetAlbumArtists(query);
  1301. }
  1302. public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
  1303. {
  1304. if (query.Recursive && !query.ParentId.IsEmpty())
  1305. {
  1306. var parent = GetItemById(query.ParentId);
  1307. if (parent is not null)
  1308. {
  1309. SetTopParentIdsOrAncestors(query, new[] { parent });
  1310. }
  1311. }
  1312. if (query.User is not null)
  1313. {
  1314. AddUserToQuery(query, query.User);
  1315. }
  1316. if (query.EnableTotalRecordCount)
  1317. {
  1318. return _itemRepository.GetItems(query);
  1319. }
  1320. return new QueryResult<BaseItem>(
  1321. query.StartIndex,
  1322. null,
  1323. _itemRepository.GetItemList(query));
  1324. }
  1325. private void SetTopParentIdsOrAncestors(InternalItemsQuery query, IReadOnlyCollection<BaseItem> parents)
  1326. {
  1327. if (parents.All(i => i is ICollectionFolder || i is UserView))
  1328. {
  1329. // Optimize by querying against top level views
  1330. query.TopParentIds = parents.SelectMany(i => GetTopParentIdsForQuery(i, query.User)).ToArray();
  1331. // Prevent searching in all libraries due to empty filter
  1332. if (query.TopParentIds.Length == 0)
  1333. {
  1334. query.TopParentIds = new[] { Guid.NewGuid() };
  1335. }
  1336. }
  1337. else
  1338. {
  1339. // We need to be able to query from any arbitrary ancestor up the tree
  1340. query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).ToArray();
  1341. // Prevent searching in all libraries due to empty filter
  1342. if (query.AncestorIds.Length == 0)
  1343. {
  1344. query.AncestorIds = new[] { Guid.NewGuid() };
  1345. }
  1346. }
  1347. query.Parent = null;
  1348. }
  1349. private void AddUserToQuery(InternalItemsQuery query, User user, bool allowExternalContent = true)
  1350. {
  1351. if (query.AncestorIds.Length == 0 &&
  1352. query.ParentId.IsEmpty() &&
  1353. query.ChannelIds.Count == 0 &&
  1354. query.TopParentIds.Length == 0 &&
  1355. string.IsNullOrEmpty(query.AncestorWithPresentationUniqueKey) &&
  1356. string.IsNullOrEmpty(query.SeriesPresentationUniqueKey) &&
  1357. query.ItemIds.Length == 0)
  1358. {
  1359. var userViews = UserViewManager.GetUserViews(new UserViewQuery
  1360. {
  1361. User = user,
  1362. IncludeHidden = true,
  1363. IncludeExternalContent = allowExternalContent
  1364. });
  1365. query.TopParentIds = userViews.SelectMany(i => GetTopParentIdsForQuery(i, user)).ToArray();
  1366. // Prevent searching in all libraries due to empty filter
  1367. if (query.TopParentIds.Length == 0)
  1368. {
  1369. query.TopParentIds = new[] { Guid.NewGuid() };
  1370. }
  1371. }
  1372. }
  1373. private IEnumerable<Guid> GetTopParentIdsForQuery(BaseItem item, User? user)
  1374. {
  1375. if (item is UserView view)
  1376. {
  1377. if (view.ViewType == CollectionType.livetv)
  1378. {
  1379. return new[] { view.Id };
  1380. }
  1381. // Translate view into folders
  1382. if (!view.DisplayParentId.IsEmpty())
  1383. {
  1384. var displayParent = GetItemById(view.DisplayParentId);
  1385. if (displayParent is not null)
  1386. {
  1387. return GetTopParentIdsForQuery(displayParent, user);
  1388. }
  1389. return [];
  1390. }
  1391. if (!view.ParentId.IsEmpty())
  1392. {
  1393. var displayParent = GetItemById(view.ParentId);
  1394. if (displayParent is not null)
  1395. {
  1396. return GetTopParentIdsForQuery(displayParent, user);
  1397. }
  1398. return [];
  1399. }
  1400. // Handle grouping
  1401. if (user is not null && view.ViewType != CollectionType.unknown && UserView.IsEligibleForGrouping(view.ViewType)
  1402. && user.GetPreference(PreferenceKind.GroupedFolders).Length > 0)
  1403. {
  1404. return GetUserRootFolder()
  1405. .GetChildren(user, true)
  1406. .OfType<CollectionFolder>()
  1407. .Where(i => i.CollectionType is null || i.CollectionType == view.ViewType)
  1408. .Where(i => user.IsFolderGrouped(i.Id))
  1409. .SelectMany(i => GetTopParentIdsForQuery(i, user));
  1410. }
  1411. return [];
  1412. }
  1413. if (item is CollectionFolder collectionFolder)
  1414. {
  1415. return collectionFolder.PhysicalFolderIds;
  1416. }
  1417. var topParent = item.GetTopParent();
  1418. if (topParent is not null)
  1419. {
  1420. return new[] { topParent.Id };
  1421. }
  1422. return [];
  1423. }
  1424. /// <summary>
  1425. /// Gets the intros.
  1426. /// </summary>
  1427. /// <param name="item">The item.</param>
  1428. /// <param name="user">The user.</param>
  1429. /// <returns>IEnumerable{System.String}.</returns>
  1430. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1431. {
  1432. if (IntroProviders.Length == 0)
  1433. {
  1434. return [];
  1435. }
  1436. var tasks = IntroProviders
  1437. .Select(i => GetIntros(i, item, user));
  1438. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1439. return items
  1440. .SelectMany(i => i)
  1441. .Select(ResolveIntro)
  1442. .Where(i => i is not null)!; // null values got filtered out
  1443. }
  1444. /// <summary>
  1445. /// Gets the intros.
  1446. /// </summary>
  1447. /// <param name="provider">The provider.</param>
  1448. /// <param name="item">The item.</param>
  1449. /// <param name="user">The user.</param>
  1450. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1451. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1452. {
  1453. try
  1454. {
  1455. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1456. }
  1457. catch (Exception ex)
  1458. {
  1459. _logger.LogError(ex, "Error getting intros");
  1460. return [];
  1461. }
  1462. }
  1463. /// <summary>
  1464. /// Resolves the intro.
  1465. /// </summary>
  1466. /// <param name="info">The info.</param>
  1467. /// <returns>Video.</returns>
  1468. private Video? ResolveIntro(IntroInfo info)
  1469. {
  1470. Video? video = null;
  1471. if (info.ItemId.HasValue)
  1472. {
  1473. // Get an existing item by Id
  1474. video = GetItemById(info.ItemId.Value) as Video;
  1475. if (video is null)
  1476. {
  1477. _logger.LogError("Unable to locate item with Id {ID}.", info.ItemId.Value);
  1478. }
  1479. }
  1480. else if (!string.IsNullOrEmpty(info.Path))
  1481. {
  1482. try
  1483. {
  1484. // Try to resolve the path into a video
  1485. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1486. if (video is null)
  1487. {
  1488. _logger.LogError("Intro resolver returned null for {Path}.", info.Path);
  1489. }
  1490. else
  1491. {
  1492. // Pull the saved db item that will include metadata
  1493. var dbItem = GetItemById(video.Id) as Video;
  1494. if (dbItem is not null)
  1495. {
  1496. video = dbItem;
  1497. }
  1498. else
  1499. {
  1500. return null;
  1501. }
  1502. }
  1503. }
  1504. catch (Exception ex)
  1505. {
  1506. _logger.LogError(ex, "Error resolving path {Path}.", info.Path);
  1507. }
  1508. }
  1509. else
  1510. {
  1511. _logger.LogError("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1512. }
  1513. return video;
  1514. }
  1515. /// <inheritdoc />
  1516. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<ItemSortBy> sortBy, SortOrder sortOrder)
  1517. {
  1518. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1519. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c is not null))
  1520. {
  1521. if (orderBy is RandomComparer)
  1522. {
  1523. var randomItems = items.ToArray();
  1524. Random.Shared.Shuffle(randomItems);
  1525. items = randomItems;
  1526. // Items are no longer ordered at this point, so set orderedItems back to null
  1527. orderedItems = null;
  1528. }
  1529. else if (orderedItems is null)
  1530. {
  1531. orderedItems = sortOrder == SortOrder.Descending
  1532. ? items.OrderByDescending(i => i, orderBy)
  1533. : items.OrderBy(i => i, orderBy);
  1534. }
  1535. else
  1536. {
  1537. orderedItems = sortOrder == SortOrder.Descending
  1538. ? orderedItems!.ThenByDescending(i => i, orderBy)
  1539. : orderedItems!.ThenBy(i => i, orderBy); // orderedItems is set during the first iteration
  1540. }
  1541. }
  1542. return orderedItems ?? items;
  1543. }
  1544. /// <inheritdoc />
  1545. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User? user, IEnumerable<(ItemSortBy OrderBy, SortOrder SortOrder)> orderBy)
  1546. {
  1547. IOrderedEnumerable<BaseItem>? orderedItems = null;
  1548. foreach (var (name, sortOrder) in orderBy)
  1549. {
  1550. var comparer = GetComparer(name, user);
  1551. if (comparer is null)
  1552. {
  1553. continue;
  1554. }
  1555. if (comparer is RandomComparer)
  1556. {
  1557. var randomItems = items.ToArray();
  1558. Random.Shared.Shuffle(randomItems);
  1559. items = randomItems;
  1560. // Items are no longer ordered at this point, so set orderedItems back to null
  1561. orderedItems = null;
  1562. }
  1563. else if (orderedItems is null)
  1564. {
  1565. orderedItems = sortOrder == SortOrder.Descending
  1566. ? items.OrderByDescending(i => i, comparer)
  1567. : items.OrderBy(i => i, comparer);
  1568. }
  1569. else
  1570. {
  1571. orderedItems = sortOrder == SortOrder.Descending
  1572. ? orderedItems!.ThenByDescending(i => i, comparer)
  1573. : orderedItems!.ThenBy(i => i, comparer); // orderedItems is set during the first iteration
  1574. }
  1575. }
  1576. return orderedItems ?? items;
  1577. }
  1578. /// <summary>
  1579. /// Gets the comparer.
  1580. /// </summary>
  1581. /// <param name="name">The name.</param>
  1582. /// <param name="user">The user.</param>
  1583. /// <returns>IBaseItemComparer.</returns>
  1584. private IBaseItemComparer? GetComparer(ItemSortBy name, User? user)
  1585. {
  1586. var comparer = Comparers.FirstOrDefault(c => name == c.Type);
  1587. // If it requires a user, create a new one, and assign the user
  1588. if (comparer is IUserBaseItemComparer)
  1589. {
  1590. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType())!; // only null for Nullable<T> instances
  1591. userComparer.User = user;
  1592. userComparer.UserManager = _userManager;
  1593. userComparer.UserDataRepository = _userDataRepository;
  1594. return userComparer;
  1595. }
  1596. return comparer;
  1597. }
  1598. /// <inheritdoc />
  1599. public void CreateItem(BaseItem item, BaseItem? parent)
  1600. {
  1601. CreateItems(new[] { item }, parent, CancellationToken.None);
  1602. }
  1603. /// <inheritdoc />
  1604. public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
  1605. {
  1606. _itemRepository.SaveItems(items, cancellationToken);
  1607. foreach (var item in items)
  1608. {
  1609. RegisterItem(item);
  1610. }
  1611. if (ItemAdded is not null)
  1612. {
  1613. foreach (var item in items)
  1614. {
  1615. // With the live tv guide this just creates too much noise
  1616. if (item.SourceType != SourceType.Library)
  1617. {
  1618. continue;
  1619. }
  1620. try
  1621. {
  1622. ItemAdded(
  1623. this,
  1624. new ItemChangeEventArgs
  1625. {
  1626. Item = item,
  1627. Parent = parent ?? item.GetParent()
  1628. });
  1629. }
  1630. catch (Exception ex)
  1631. {
  1632. _logger.LogError(ex, "Error in ItemAdded event handler");
  1633. }
  1634. }
  1635. }
  1636. }
  1637. private bool ImageNeedsRefresh(ItemImageInfo image)
  1638. {
  1639. if (image.Path is not null && image.IsLocalFile)
  1640. {
  1641. if (image.Width == 0 || image.Height == 0 || string.IsNullOrEmpty(image.BlurHash))
  1642. {
  1643. return true;
  1644. }
  1645. try
  1646. {
  1647. return _fileSystem.GetLastWriteTimeUtc(image.Path) != image.DateModified;
  1648. }
  1649. catch (Exception ex)
  1650. {
  1651. _logger.LogError(ex, "Cannot get file info for {0}", image.Path);
  1652. return false;
  1653. }
  1654. }
  1655. return image.Path is not null && !image.IsLocalFile;
  1656. }
  1657. /// <inheritdoc />
  1658. public async Task UpdateImagesAsync(BaseItem item, bool forceUpdate = false)
  1659. {
  1660. ArgumentNullException.ThrowIfNull(item);
  1661. var outdated = forceUpdate
  1662. ? item.ImageInfos.Where(i => i.Path is not null).ToArray()
  1663. : item.ImageInfos.Where(ImageNeedsRefresh).ToArray();
  1664. // Skip image processing if current or live tv source
  1665. if (outdated.Length == 0 || item.SourceType != SourceType.Library)
  1666. {
  1667. RegisterItem(item);
  1668. return;
  1669. }
  1670. foreach (var img in outdated)
  1671. {
  1672. var image = img;
  1673. if (!img.IsLocalFile)
  1674. {
  1675. try
  1676. {
  1677. var index = item.GetImageIndex(img);
  1678. image = await ConvertImageToLocal(item, img, index, true).ConfigureAwait(false);
  1679. }
  1680. catch (ArgumentException)
  1681. {
  1682. _logger.LogWarning("Cannot get image index for {ImagePath}", img.Path);
  1683. continue;
  1684. }
  1685. catch (Exception ex) when (ex is InvalidOperationException or IOException)
  1686. {
  1687. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}", img.Path);
  1688. continue;
  1689. }
  1690. catch (HttpRequestException ex)
  1691. {
  1692. _logger.LogWarning(ex, "Cannot fetch image from {ImagePath}. Http status code: {HttpStatus}", img.Path, ex.StatusCode);
  1693. continue;
  1694. }
  1695. }
  1696. ImageDimensions size;
  1697. try
  1698. {
  1699. size = _imageProcessor.GetImageDimensions(item, image);
  1700. image.Width = size.Width;
  1701. image.Height = size.Height;
  1702. }
  1703. catch (Exception ex)
  1704. {
  1705. _logger.LogError(ex, "Cannot get image dimensions for {ImagePath}", image.Path);
  1706. size = default;
  1707. image.Width = 0;
  1708. image.Height = 0;
  1709. }
  1710. try
  1711. {
  1712. image.BlurHash = _imageProcessor.GetImageBlurHash(image.Path, size);
  1713. }
  1714. catch (Exception ex)
  1715. {
  1716. _logger.LogError(ex, "Cannot compute blurhash for {ImagePath}", image.Path);
  1717. image.BlurHash = string.Empty;
  1718. }
  1719. try
  1720. {
  1721. image.DateModified = _fileSystem.GetLastWriteTimeUtc(image.Path);
  1722. }
  1723. catch (Exception ex)
  1724. {
  1725. _logger.LogError(ex, "Cannot update DateModified for {ImagePath}", image.Path);
  1726. }
  1727. }
  1728. _itemRepository.SaveImages(item);
  1729. RegisterItem(item);
  1730. }
  1731. /// <inheritdoc />
  1732. public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1733. {
  1734. _itemRepository.SaveItems(items, cancellationToken);
  1735. foreach (var item in items)
  1736. {
  1737. await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
  1738. }
  1739. if (ItemUpdated is not null)
  1740. {
  1741. foreach (var item in items)
  1742. {
  1743. // With the live tv guide this just creates too much noise
  1744. if (item.SourceType != SourceType.Library)
  1745. {
  1746. continue;
  1747. }
  1748. try
  1749. {
  1750. ItemUpdated(
  1751. this,
  1752. new ItemChangeEventArgs
  1753. {
  1754. Item = item,
  1755. Parent = parent,
  1756. UpdateReason = updateReason
  1757. });
  1758. }
  1759. catch (Exception ex)
  1760. {
  1761. _logger.LogError(ex, "Error in ItemUpdated event handler");
  1762. }
  1763. }
  1764. }
  1765. }
  1766. /// <inheritdoc />
  1767. public Task UpdateItemAsync(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1768. => UpdateItemsAsync(new[] { item }, parent, updateReason, cancellationToken);
  1769. public async Task RunMetadataSavers(BaseItem item, ItemUpdateType updateReason)
  1770. {
  1771. if (item.IsFileProtocol)
  1772. {
  1773. await ProviderManager.SaveMetadataAsync(item, updateReason).ConfigureAwait(false);
  1774. }
  1775. item.DateLastSaved = DateTime.UtcNow;
  1776. await UpdateImagesAsync(item, updateReason >= ItemUpdateType.ImageUpdate).ConfigureAwait(false);
  1777. }
  1778. /// <summary>
  1779. /// Reports the item removed.
  1780. /// </summary>
  1781. /// <param name="item">The item.</param>
  1782. /// <param name="parent">The parent item.</param>
  1783. public void ReportItemRemoved(BaseItem item, BaseItem parent)
  1784. {
  1785. if (ItemRemoved is not null)
  1786. {
  1787. try
  1788. {
  1789. ItemRemoved(
  1790. this,
  1791. new ItemChangeEventArgs
  1792. {
  1793. Item = item,
  1794. Parent = parent
  1795. });
  1796. }
  1797. catch (Exception ex)
  1798. {
  1799. _logger.LogError(ex, "Error in ItemRemoved event handler");
  1800. }
  1801. }
  1802. }
  1803. /// <summary>
  1804. /// Retrieves the item.
  1805. /// </summary>
  1806. /// <param name="id">The id.</param>
  1807. /// <returns>BaseItem.</returns>
  1808. public BaseItem RetrieveItem(Guid id)
  1809. {
  1810. return _itemRepository.RetrieveItem(id);
  1811. }
  1812. public List<Folder> GetCollectionFolders(BaseItem item)
  1813. {
  1814. return GetCollectionFolders(item, GetUserRootFolder().Children.OfType<Folder>());
  1815. }
  1816. public List<Folder> GetCollectionFolders(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1817. {
  1818. while (item is not null)
  1819. {
  1820. var parent = item.GetParent();
  1821. if (parent is AggregateFolder)
  1822. {
  1823. break;
  1824. }
  1825. if (parent is null)
  1826. {
  1827. var owner = item.GetOwner();
  1828. if (owner is null)
  1829. {
  1830. break;
  1831. }
  1832. item = owner;
  1833. }
  1834. else
  1835. {
  1836. item = parent;
  1837. }
  1838. }
  1839. if (item is null)
  1840. {
  1841. return new List<Folder>();
  1842. }
  1843. return GetCollectionFoldersInternal(item, allUserRootChildren);
  1844. }
  1845. private static List<Folder> GetCollectionFoldersInternal(BaseItem item, IEnumerable<Folder> allUserRootChildren)
  1846. {
  1847. return allUserRootChildren
  1848. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path.AsSpan(), StringComparison.OrdinalIgnoreCase))
  1849. .ToList();
  1850. }
  1851. public LibraryOptions GetLibraryOptions(BaseItem item)
  1852. {
  1853. if (item is CollectionFolder collectionFolder)
  1854. {
  1855. return collectionFolder.GetLibraryOptions();
  1856. }
  1857. // List.Find is more performant than FirstOrDefault due to enumerator allocation
  1858. return GetCollectionFolders(item)
  1859. .Find(folder => folder is CollectionFolder) is CollectionFolder collectionFolder2
  1860. ? collectionFolder2.GetLibraryOptions()
  1861. : new LibraryOptions();
  1862. }
  1863. public CollectionType? GetContentType(BaseItem item)
  1864. {
  1865. var configuredContentType = GetConfiguredContentType(item, false);
  1866. if (configuredContentType is not null)
  1867. {
  1868. return configuredContentType;
  1869. }
  1870. configuredContentType = GetConfiguredContentType(item, true);
  1871. if (configuredContentType is not null)
  1872. {
  1873. return configuredContentType;
  1874. }
  1875. return GetInheritedContentType(item);
  1876. }
  1877. public CollectionType? GetInheritedContentType(BaseItem item)
  1878. {
  1879. var type = GetTopFolderContentType(item);
  1880. if (type is not null)
  1881. {
  1882. return type;
  1883. }
  1884. return item.GetParents()
  1885. .Select(GetConfiguredContentType)
  1886. .LastOrDefault(i => i is not null);
  1887. }
  1888. public CollectionType? GetConfiguredContentType(BaseItem item)
  1889. {
  1890. return GetConfiguredContentType(item, false);
  1891. }
  1892. public CollectionType? GetConfiguredContentType(string path)
  1893. {
  1894. return GetContentTypeOverride(path, false);
  1895. }
  1896. public CollectionType? GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1897. {
  1898. if (item is ICollectionFolder collectionFolder)
  1899. {
  1900. return collectionFolder.CollectionType;
  1901. }
  1902. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1903. }
  1904. private CollectionType? GetContentTypeOverride(string path, bool inherit)
  1905. {
  1906. var nameValuePair = _configurationManager.Configuration.ContentTypes
  1907. .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
  1908. || (inherit && !string.IsNullOrEmpty(i.Name)
  1909. && _fileSystem.ContainsSubPath(i.Name, path)));
  1910. if (Enum.TryParse<CollectionType>(nameValuePair?.Value, out var collectionType))
  1911. {
  1912. return collectionType;
  1913. }
  1914. return null;
  1915. }
  1916. private CollectionType? GetTopFolderContentType(BaseItem item)
  1917. {
  1918. if (item is null)
  1919. {
  1920. return null;
  1921. }
  1922. while (!item.ParentId.IsEmpty())
  1923. {
  1924. var parent = item.GetParent();
  1925. if (parent is null || parent is AggregateFolder)
  1926. {
  1927. break;
  1928. }
  1929. item = parent;
  1930. }
  1931. return GetUserRootFolder().Children
  1932. .OfType<ICollectionFolder>()
  1933. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1934. .Select(i => i.CollectionType)
  1935. .FirstOrDefault(i => i is not null);
  1936. }
  1937. public UserView GetNamedView(
  1938. User user,
  1939. string name,
  1940. CollectionType? viewType,
  1941. string sortName)
  1942. {
  1943. return GetNamedView(user, name, Guid.Empty, viewType, sortName);
  1944. }
  1945. public UserView GetNamedView(
  1946. string name,
  1947. CollectionType viewType,
  1948. string sortName)
  1949. {
  1950. var path = Path.Combine(
  1951. _configurationManager.ApplicationPaths.InternalMetadataPath,
  1952. "views",
  1953. _fileSystem.GetValidFilename(viewType.ToString()));
  1954. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1955. var item = GetItemById(id) as UserView;
  1956. var refresh = false;
  1957. if (item is null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1958. {
  1959. Directory.CreateDirectory(path);
  1960. item = new UserView
  1961. {
  1962. Path = path,
  1963. Id = id,
  1964. DateCreated = DateTime.UtcNow,
  1965. Name = name,
  1966. ViewType = viewType,
  1967. ForcedSortName = sortName
  1968. };
  1969. CreateItem(item, null);
  1970. refresh = true;
  1971. }
  1972. if (refresh)
  1973. {
  1974. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataImport, CancellationToken.None).GetAwaiter().GetResult();
  1975. ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
  1976. }
  1977. return item;
  1978. }
  1979. public UserView GetNamedView(
  1980. User user,
  1981. string name,
  1982. Guid parentId,
  1983. CollectionType? viewType,
  1984. string sortName)
  1985. {
  1986. var parentIdString = parentId.IsEmpty()
  1987. ? null
  1988. : parentId.ToString("N", CultureInfo.InvariantCulture);
  1989. var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  1990. var id = GetNewItemId(idValues, typeof(UserView));
  1991. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1992. var item = GetItemById(id) as UserView;
  1993. var isNew = false;
  1994. if (item is null)
  1995. {
  1996. Directory.CreateDirectory(path);
  1997. item = new UserView
  1998. {
  1999. Path = path,
  2000. Id = id,
  2001. DateCreated = DateTime.UtcNow,
  2002. Name = name,
  2003. ViewType = viewType,
  2004. ForcedSortName = sortName,
  2005. UserId = user.Id,
  2006. DisplayParentId = parentId
  2007. };
  2008. CreateItem(item, null);
  2009. isNew = true;
  2010. }
  2011. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  2012. if (!refresh && !item.DisplayParentId.IsEmpty())
  2013. {
  2014. var displayParent = GetItemById(item.DisplayParentId);
  2015. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  2016. }
  2017. if (refresh)
  2018. {
  2019. ProviderManager.QueueRefresh(
  2020. item.Id,
  2021. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2022. {
  2023. // Need to force save to increment DateLastSaved
  2024. ForceSave = true
  2025. },
  2026. RefreshPriority.Normal);
  2027. }
  2028. return item;
  2029. }
  2030. public UserView GetShadowView(
  2031. BaseItem parent,
  2032. CollectionType? viewType,
  2033. string sortName)
  2034. {
  2035. ArgumentNullException.ThrowIfNull(parent);
  2036. var name = parent.Name;
  2037. var parentId = parent.Id;
  2038. var idValues = "38_namedview_" + name + parentId + (viewType?.ToString() ?? string.Empty);
  2039. var id = GetNewItemId(idValues, typeof(UserView));
  2040. var path = parent.Path;
  2041. var item = GetItemById(id) as UserView;
  2042. var isNew = false;
  2043. if (item is null)
  2044. {
  2045. Directory.CreateDirectory(path);
  2046. item = new UserView
  2047. {
  2048. Path = path,
  2049. Id = id,
  2050. DateCreated = DateTime.UtcNow,
  2051. Name = name,
  2052. ViewType = viewType,
  2053. ForcedSortName = sortName
  2054. };
  2055. item.DisplayParentId = parentId;
  2056. CreateItem(item, null);
  2057. isNew = true;
  2058. }
  2059. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  2060. if (!refresh && !item.DisplayParentId.IsEmpty())
  2061. {
  2062. var displayParent = GetItemById(item.DisplayParentId);
  2063. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  2064. }
  2065. if (refresh)
  2066. {
  2067. ProviderManager.QueueRefresh(
  2068. item.Id,
  2069. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2070. {
  2071. // Need to force save to increment DateLastSaved
  2072. ForceSave = true
  2073. },
  2074. RefreshPriority.Normal);
  2075. }
  2076. return item;
  2077. }
  2078. public UserView GetNamedView(
  2079. string name,
  2080. Guid parentId,
  2081. CollectionType? viewType,
  2082. string sortName,
  2083. string uniqueId)
  2084. {
  2085. ArgumentException.ThrowIfNullOrEmpty(name);
  2086. var parentIdString = parentId.IsEmpty()
  2087. ? null
  2088. : parentId.ToString("N", CultureInfo.InvariantCulture);
  2089. var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType?.ToString() ?? string.Empty);
  2090. if (!string.IsNullOrEmpty(uniqueId))
  2091. {
  2092. idValues += uniqueId;
  2093. }
  2094. var id = GetNewItemId(idValues, typeof(UserView));
  2095. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  2096. var item = GetItemById(id) as UserView;
  2097. var isNew = false;
  2098. if (item is null)
  2099. {
  2100. Directory.CreateDirectory(path);
  2101. item = new UserView
  2102. {
  2103. Path = path,
  2104. Id = id,
  2105. DateCreated = DateTime.UtcNow,
  2106. Name = name,
  2107. ViewType = viewType,
  2108. ForcedSortName = sortName
  2109. };
  2110. item.DisplayParentId = parentId;
  2111. CreateItem(item, null);
  2112. isNew = true;
  2113. }
  2114. if (viewType != item.ViewType)
  2115. {
  2116. item.ViewType = viewType;
  2117. item.UpdateToRepositoryAsync(ItemUpdateType.MetadataEdit, CancellationToken.None).GetAwaiter().GetResult();
  2118. }
  2119. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  2120. if (!refresh && !item.DisplayParentId.IsEmpty())
  2121. {
  2122. var displayParent = GetItemById(item.DisplayParentId);
  2123. refresh = displayParent is not null && displayParent.DateLastSaved > item.DateLastRefreshed;
  2124. }
  2125. if (refresh)
  2126. {
  2127. ProviderManager.QueueRefresh(
  2128. item.Id,
  2129. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  2130. {
  2131. // Need to force save to increment DateLastSaved
  2132. ForceSave = true
  2133. },
  2134. RefreshPriority.Normal);
  2135. }
  2136. return item;
  2137. }
  2138. public BaseItem GetParentItem(Guid? parentId, Guid? userId)
  2139. {
  2140. if (parentId.HasValue)
  2141. {
  2142. return GetItemById(parentId.Value) ?? throw new ArgumentException($"Invalid parent id: {parentId.Value}");
  2143. }
  2144. if (!userId.IsNullOrEmpty())
  2145. {
  2146. return GetUserRootFolder();
  2147. }
  2148. return RootFolder;
  2149. }
  2150. /// <inheritdoc />
  2151. public void QueueLibraryScan()
  2152. {
  2153. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  2154. }
  2155. /// <inheritdoc />
  2156. public int? GetSeasonNumberFromPath(string path, Guid? parentId)
  2157. {
  2158. var parentPath = parentId.HasValue ? GetItemById(parentId.Value)?.ContainingFolderPath : null;
  2159. return SeasonPathParser.Parse(path, parentPath, true, true).SeasonNumber;
  2160. }
  2161. /// <inheritdoc />
  2162. public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
  2163. {
  2164. var series = episode.Series;
  2165. bool? isAbsoluteNaming = series is not null && string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
  2166. if (!isAbsoluteNaming.Value)
  2167. {
  2168. // In other words, no filter applied
  2169. isAbsoluteNaming = null;
  2170. }
  2171. var resolver = new EpisodeResolver(_namingOptions);
  2172. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
  2173. // TODO nullable - what are we trying to do there with empty episodeInfo?
  2174. EpisodeInfo? episodeInfo = null;
  2175. if (episode.IsFileProtocol)
  2176. {
  2177. episodeInfo = resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming);
  2178. // Resolve from parent folder if it's not the Season folder
  2179. var parent = episode.GetParent();
  2180. if (episodeInfo is null && parent.GetType() == typeof(Folder))
  2181. {
  2182. episodeInfo = resolver.Resolve(parent.Path, true, null, null, isAbsoluteNaming);
  2183. if (episodeInfo is not null)
  2184. {
  2185. // add the container
  2186. episodeInfo.Container = Path.GetExtension(episode.Path)?.TrimStart('.');
  2187. }
  2188. }
  2189. }
  2190. episodeInfo ??= new EpisodeInfo(episode.Path);
  2191. try
  2192. {
  2193. var libraryOptions = GetLibraryOptions(episode);
  2194. if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(episodeInfo.Container, "mp4", StringComparison.OrdinalIgnoreCase))
  2195. {
  2196. // Read from metadata
  2197. var mediaInfo = _mediaEncoder.GetMediaInfo(
  2198. new MediaInfoRequest
  2199. {
  2200. MediaSource = episode.GetMediaSources(false)[0],
  2201. MediaType = DlnaProfileType.Video
  2202. },
  2203. CancellationToken.None).GetAwaiter().GetResult();
  2204. if (mediaInfo.ParentIndexNumber > 0)
  2205. {
  2206. episodeInfo.SeasonNumber = mediaInfo.ParentIndexNumber;
  2207. }
  2208. if (mediaInfo.IndexNumber > 0)
  2209. {
  2210. episodeInfo.EpisodeNumber = mediaInfo.IndexNumber;
  2211. }
  2212. if (!string.IsNullOrEmpty(mediaInfo.ShowName))
  2213. {
  2214. episodeInfo.SeriesName = mediaInfo.ShowName;
  2215. }
  2216. }
  2217. }
  2218. catch (Exception ex)
  2219. {
  2220. _logger.LogError(ex, "Error reading the episode information with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
  2221. }
  2222. var changed = false;
  2223. if (episodeInfo.IsByDate)
  2224. {
  2225. if (episode.IndexNumber.HasValue)
  2226. {
  2227. episode.IndexNumber = null;
  2228. changed = true;
  2229. }
  2230. if (episode.IndexNumberEnd.HasValue)
  2231. {
  2232. episode.IndexNumberEnd = null;
  2233. changed = true;
  2234. }
  2235. if (!episode.PremiereDate.HasValue)
  2236. {
  2237. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  2238. {
  2239. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  2240. }
  2241. if (episode.PremiereDate.HasValue)
  2242. {
  2243. changed = true;
  2244. }
  2245. }
  2246. if (!episode.ProductionYear.HasValue)
  2247. {
  2248. episode.ProductionYear = episodeInfo.Year;
  2249. if (episode.ProductionYear.HasValue)
  2250. {
  2251. changed = true;
  2252. }
  2253. }
  2254. }
  2255. else
  2256. {
  2257. if (!episode.IndexNumber.HasValue || forceRefresh)
  2258. {
  2259. if (episode.IndexNumber != episodeInfo.EpisodeNumber)
  2260. {
  2261. changed = true;
  2262. }
  2263. episode.IndexNumber = episodeInfo.EpisodeNumber;
  2264. }
  2265. if (!episode.IndexNumberEnd.HasValue || forceRefresh)
  2266. {
  2267. if (episode.IndexNumberEnd != episodeInfo.EndingEpisodeNumber)
  2268. {
  2269. changed = true;
  2270. }
  2271. episode.IndexNumberEnd = episodeInfo.EndingEpisodeNumber;
  2272. }
  2273. if (!episode.ParentIndexNumber.HasValue || forceRefresh)
  2274. {
  2275. if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
  2276. {
  2277. changed = true;
  2278. }
  2279. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  2280. }
  2281. }
  2282. if (!episode.ParentIndexNumber.HasValue)
  2283. {
  2284. var season = episode.Season;
  2285. if (season is not null)
  2286. {
  2287. episode.ParentIndexNumber = season.IndexNumber;
  2288. }
  2289. if (episode.ParentIndexNumber.HasValue)
  2290. {
  2291. changed = true;
  2292. }
  2293. }
  2294. return changed;
  2295. }
  2296. public ItemLookupInfo ParseName(string name)
  2297. {
  2298. var namingOptions = _namingOptions;
  2299. var result = VideoResolver.CleanDateTime(name, namingOptions);
  2300. return new ItemLookupInfo
  2301. {
  2302. Name = VideoResolver.TryCleanString(result.Name, namingOptions, out var newName) ? newName : result.Name,
  2303. Year = result.Year
  2304. };
  2305. }
  2306. public IEnumerable<BaseItem> FindExtras(BaseItem owner, IReadOnlyList<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2307. {
  2308. var ownerVideoInfo = VideoResolver.Resolve(owner.Path, owner.IsFolder, _namingOptions, libraryRoot: owner.ContainingFolderPath);
  2309. if (ownerVideoInfo is null)
  2310. {
  2311. yield break;
  2312. }
  2313. var count = fileSystemChildren.Count;
  2314. for (var i = 0; i < count; i++)
  2315. {
  2316. var current = fileSystemChildren[i];
  2317. if (current.IsDirectory && _namingOptions.AllExtrasTypesFolderNames.ContainsKey(current.Name))
  2318. {
  2319. var filesInSubFolder = _fileSystem.GetFiles(current.FullName, null, false, false);
  2320. foreach (var file in filesInSubFolder)
  2321. {
  2322. if (!_extraResolver.TryGetExtraTypeForOwner(file.FullName, ownerVideoInfo, out var extraType))
  2323. {
  2324. continue;
  2325. }
  2326. var extra = GetExtra(file, extraType.Value);
  2327. if (extra is not null)
  2328. {
  2329. yield return extra;
  2330. }
  2331. }
  2332. }
  2333. else if (!current.IsDirectory && _extraResolver.TryGetExtraTypeForOwner(current.FullName, ownerVideoInfo, out var extraType))
  2334. {
  2335. var extra = GetExtra(current, extraType.Value);
  2336. if (extra is not null)
  2337. {
  2338. yield return extra;
  2339. }
  2340. }
  2341. }
  2342. BaseItem? GetExtra(FileSystemMetadata file, ExtraType extraType)
  2343. {
  2344. var extra = ResolvePath(_fileSystem.GetFileInfo(file.FullName), directoryService, _extraResolver.GetResolversForExtraType(extraType));
  2345. if (extra is not Video && extra is not Audio)
  2346. {
  2347. return null;
  2348. }
  2349. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2350. var itemById = GetItemById(extra.Id);
  2351. if (itemById is not null)
  2352. {
  2353. extra = itemById;
  2354. }
  2355. // Only update extra type if it is more specific then the currently known extra type
  2356. if (extra.ExtraType is null or ExtraType.Unknown || extraType != ExtraType.Unknown)
  2357. {
  2358. extra.ExtraType = extraType;
  2359. }
  2360. extra.ParentId = Guid.Empty;
  2361. extra.OwnerId = owner.Id;
  2362. return extra;
  2363. }
  2364. }
  2365. public string GetPathAfterNetworkSubstitution(string path, BaseItem? ownerItem)
  2366. {
  2367. foreach (var map in _configurationManager.Configuration.PathSubstitutions)
  2368. {
  2369. if (path.TryReplaceSubPath(map.From, map.To, out var newPath))
  2370. {
  2371. return newPath;
  2372. }
  2373. }
  2374. return path;
  2375. }
  2376. public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
  2377. {
  2378. return _peopleRepository.GetPeople(query);
  2379. }
  2380. public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
  2381. {
  2382. if (item.SupportsPeople)
  2383. {
  2384. var people = GetPeople(new InternalPeopleQuery
  2385. {
  2386. ItemId = item.Id
  2387. });
  2388. if (people.Count > 0)
  2389. {
  2390. return people;
  2391. }
  2392. }
  2393. return [];
  2394. }
  2395. public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
  2396. {
  2397. return _peopleRepository.GetPeopleNames(query)
  2398. .Select(i =>
  2399. {
  2400. try
  2401. {
  2402. return GetPerson(i);
  2403. }
  2404. catch (Exception ex)
  2405. {
  2406. _logger.LogError(ex, "Error getting person");
  2407. return null;
  2408. }
  2409. })
  2410. .Where(i => i is not null)
  2411. .Where(i => query.User is null || i!.IsVisible(query.User))
  2412. .ToList()!; // null values are filtered out
  2413. }
  2414. public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
  2415. {
  2416. return _peopleRepository.GetPeopleNames(query);
  2417. }
  2418. public void UpdatePeople(BaseItem item, List<PersonInfo> people)
  2419. {
  2420. UpdatePeopleAsync(item, people, CancellationToken.None).GetAwaiter().GetResult();
  2421. }
  2422. /// <inheritdoc />
  2423. public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellationToken)
  2424. {
  2425. if (!item.SupportsPeople)
  2426. {
  2427. return;
  2428. }
  2429. if (people is not null)
  2430. {
  2431. people = people.Where(e => e is not null).ToArray();
  2432. _peopleRepository.UpdatePeople(item.Id, people);
  2433. await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
  2434. }
  2435. }
  2436. public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure)
  2437. {
  2438. foreach (var url in image.Path.Split('|'))
  2439. {
  2440. try
  2441. {
  2442. _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2443. await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2444. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2445. return item.GetImageInfo(image.Type, imageIndex);
  2446. }
  2447. catch (HttpRequestException ex)
  2448. {
  2449. if (ex.StatusCode.HasValue
  2450. && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden))
  2451. {
  2452. _logger.LogDebug(ex, "Error downloading image {Url}", url);
  2453. continue;
  2454. }
  2455. throw;
  2456. }
  2457. }
  2458. if (removeOnFailure)
  2459. {
  2460. // Remove this image to prevent it from retrying over and over
  2461. item.RemoveImage(image);
  2462. await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2463. }
  2464. throw new InvalidOperationException("Unable to convert any images to local");
  2465. }
  2466. public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary)
  2467. {
  2468. if (string.IsNullOrWhiteSpace(name))
  2469. {
  2470. throw new ArgumentNullException(nameof(name));
  2471. }
  2472. name = _fileSystem.GetValidFilename(name.Trim());
  2473. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2474. var existingNameCount = 1; // first numbered name will be 2
  2475. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2476. var originalName = name;
  2477. while (Directory.Exists(virtualFolderPath))
  2478. {
  2479. existingNameCount++;
  2480. name = originalName + existingNameCount;
  2481. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2482. }
  2483. var mediaPathInfos = options.PathInfos;
  2484. if (mediaPathInfos is not null)
  2485. {
  2486. var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
  2487. if (invalidpath is not null)
  2488. {
  2489. throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
  2490. }
  2491. }
  2492. LibraryMonitor.Stop();
  2493. try
  2494. {
  2495. Directory.CreateDirectory(virtualFolderPath);
  2496. if (collectionType is not null)
  2497. {
  2498. var path = Path.Combine(virtualFolderPath, collectionType.ToString()!.ToLowerInvariant() + ".collection"); // Can't be null with legal values?
  2499. await File.WriteAllBytesAsync(path, []).ConfigureAwait(false);
  2500. }
  2501. CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
  2502. if (mediaPathInfos is not null)
  2503. {
  2504. foreach (var path in mediaPathInfos)
  2505. {
  2506. AddMediaPathInternal(name, path, false);
  2507. }
  2508. }
  2509. }
  2510. finally
  2511. {
  2512. if (refreshLibrary)
  2513. {
  2514. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2515. StartScanInBackground();
  2516. }
  2517. else
  2518. {
  2519. // Need to add a delay here or directory watchers may still pick up the changes
  2520. await Task.Delay(1000).ConfigureAwait(false);
  2521. LibraryMonitor.Start();
  2522. }
  2523. }
  2524. }
  2525. private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
  2526. {
  2527. foreach (var person in people)
  2528. {
  2529. cancellationToken.ThrowIfCancellationRequested();
  2530. var itemUpdateType = ItemUpdateType.MetadataDownload;
  2531. var saveEntity = false;
  2532. var createEntity = false;
  2533. var personEntity = GetPerson(person.Name);
  2534. if (personEntity is null)
  2535. {
  2536. var path = Person.GetPath(person.Name);
  2537. personEntity = new Person()
  2538. {
  2539. Name = person.Name,
  2540. Id = GetItemByNameId<Person>(path),
  2541. DateCreated = DateTime.UtcNow,
  2542. DateModified = DateTime.UtcNow,
  2543. Path = path
  2544. };
  2545. personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
  2546. saveEntity = true;
  2547. createEntity = true;
  2548. }
  2549. foreach (var id in person.ProviderIds)
  2550. {
  2551. if (!string.Equals(personEntity.GetProviderId(id.Key), id.Value, StringComparison.OrdinalIgnoreCase))
  2552. {
  2553. personEntity.SetProviderId(id.Key, id.Value);
  2554. saveEntity = true;
  2555. }
  2556. }
  2557. if (!string.IsNullOrWhiteSpace(person.ImageUrl) && !personEntity.HasImage(ImageType.Primary))
  2558. {
  2559. personEntity.SetImage(
  2560. new ItemImageInfo
  2561. {
  2562. Path = person.ImageUrl,
  2563. Type = ImageType.Primary
  2564. },
  2565. 0);
  2566. saveEntity = true;
  2567. itemUpdateType = ItemUpdateType.ImageUpdate;
  2568. }
  2569. if (saveEntity)
  2570. {
  2571. if (createEntity)
  2572. {
  2573. CreateItems([personEntity], null, CancellationToken.None);
  2574. }
  2575. await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
  2576. CreateItems([personEntity], null, CancellationToken.None);
  2577. }
  2578. }
  2579. }
  2580. private void StartScanInBackground()
  2581. {
  2582. Task.Run(() =>
  2583. {
  2584. // No need to start if scanning the library because it will handle it
  2585. ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  2586. });
  2587. }
  2588. public void AddMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2589. {
  2590. AddMediaPathInternal(virtualFolderName, mediaPath, true);
  2591. }
  2592. private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
  2593. {
  2594. ArgumentNullException.ThrowIfNull(pathInfo);
  2595. var path = pathInfo.Path;
  2596. if (string.IsNullOrWhiteSpace(path))
  2597. {
  2598. throw new ArgumentException(nameof(path));
  2599. }
  2600. if (!Directory.Exists(path))
  2601. {
  2602. throw new FileNotFoundException("The path does not exist.");
  2603. }
  2604. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2605. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2606. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  2607. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2608. while (File.Exists(lnk))
  2609. {
  2610. shortcutFilename += "1";
  2611. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2612. }
  2613. _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
  2614. RemoveContentTypeOverrides(path);
  2615. if (saveLibraryOptions)
  2616. {
  2617. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2618. libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
  2619. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2620. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2621. }
  2622. }
  2623. public void UpdateMediaPath(string virtualFolderName, MediaPathInfo mediaPath)
  2624. {
  2625. ArgumentNullException.ThrowIfNull(mediaPath);
  2626. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2627. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2628. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2629. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2630. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2631. }
  2632. private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
  2633. {
  2634. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  2635. var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
  2636. if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
  2637. {
  2638. var list = options.PathInfos.ToList();
  2639. foreach (var location in info.Locations)
  2640. {
  2641. if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
  2642. {
  2643. list.Add(new MediaPathInfo(location));
  2644. }
  2645. }
  2646. options.PathInfos = list.ToArray();
  2647. }
  2648. }
  2649. public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
  2650. {
  2651. if (string.IsNullOrWhiteSpace(name))
  2652. {
  2653. throw new ArgumentNullException(nameof(name));
  2654. }
  2655. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2656. var path = Path.Combine(rootFolderPath, name);
  2657. if (!Directory.Exists(path))
  2658. {
  2659. throw new FileNotFoundException("The media folder does not exist");
  2660. }
  2661. LibraryMonitor.Stop();
  2662. try
  2663. {
  2664. Directory.Delete(path, true);
  2665. }
  2666. finally
  2667. {
  2668. CollectionFolder.OnCollectionFolderChange();
  2669. if (refreshLibrary)
  2670. {
  2671. await ValidateTopLibraryFolders(CancellationToken.None, true).ConfigureAwait(false);
  2672. StartScanInBackground();
  2673. }
  2674. else
  2675. {
  2676. // Need to add a delay here or directory watchers may still pick up the changes
  2677. await Task.Delay(1000).ConfigureAwait(false);
  2678. LibraryMonitor.Start();
  2679. }
  2680. }
  2681. }
  2682. private void RemoveContentTypeOverrides(string path)
  2683. {
  2684. if (string.IsNullOrWhiteSpace(path))
  2685. {
  2686. throw new ArgumentNullException(nameof(path));
  2687. }
  2688. List<NameValuePair>? removeList = null;
  2689. foreach (var contentType in _configurationManager.Configuration.ContentTypes)
  2690. {
  2691. if (string.IsNullOrWhiteSpace(contentType.Name)
  2692. || _fileSystem.AreEqual(path, contentType.Name)
  2693. || _fileSystem.ContainsSubPath(path, contentType.Name))
  2694. {
  2695. (removeList ??= new()).Add(contentType);
  2696. }
  2697. }
  2698. if (removeList is not null)
  2699. {
  2700. _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
  2701. .Except(removeList)
  2702. .ToArray();
  2703. _configurationManager.SaveConfiguration();
  2704. }
  2705. }
  2706. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2707. {
  2708. ArgumentException.ThrowIfNullOrEmpty(mediaPath);
  2709. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2710. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2711. if (!Directory.Exists(virtualFolderPath))
  2712. {
  2713. throw new FileNotFoundException(
  2714. string.Format(CultureInfo.InvariantCulture, "The media collection {0} does not exist", virtualFolderName));
  2715. }
  2716. var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
  2717. .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase))
  2718. .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2719. if (!string.IsNullOrEmpty(shortcut))
  2720. {
  2721. _fileSystem.DeleteFile(shortcut);
  2722. }
  2723. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2724. libraryOptions.PathInfos = libraryOptions
  2725. .PathInfos
  2726. .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
  2727. .ToArray();
  2728. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2729. }
  2730. private static bool ItemIsVisible(BaseItem? item, User? user)
  2731. {
  2732. if (item is null)
  2733. {
  2734. return false;
  2735. }
  2736. if (user is null)
  2737. {
  2738. return true;
  2739. }
  2740. return item is UserRootFolder || item.IsVisibleStandalone(user);
  2741. }
  2742. }
  2743. }