LibraryManager.cs 111 KB

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