2
0

LibraryManager.cs 113 KB

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