LibraryManager.cs 115 KB

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