LibraryManager.cs 112 KB

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