LibraryManager.cs 111 KB

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