LibraryManager.cs 114 KB

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