LibraryManager.cs 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  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 NamingOptions _namingOptions;
  71. private string[] _videoFileExtensions;
  72. private ILibraryMonitor LibraryMonitor => _libraryMonitorFactory.Value;
  73. private IProviderManager ProviderManager => _providerManagerFactory.Value;
  74. private IUserViewManager UserViewManager => _userviewManagerFactory.Value;
  75. /// <summary>
  76. /// Gets or sets the postscan tasks.
  77. /// </summary>
  78. /// <value>The postscan tasks.</value>
  79. private ILibraryPostScanTask[] PostscanTasks { get; set; }
  80. /// <summary>
  81. /// Gets or sets the intro providers.
  82. /// </summary>
  83. /// <value>The intro providers.</value>
  84. private IIntroProvider[] IntroProviders { get; set; }
  85. /// <summary>
  86. /// Gets or sets the list of entity resolution ignore rules
  87. /// </summary>
  88. /// <value>The entity resolution ignore rules.</value>
  89. private IResolverIgnoreRule[] EntityResolutionIgnoreRules { get; set; }
  90. /// <summary>
  91. /// Gets or sets the list of currently registered entity resolvers
  92. /// </summary>
  93. /// <value>The entity resolvers enumerable.</value>
  94. private IItemResolver[] EntityResolvers { get; set; }
  95. private IMultiItemResolver[] MultiItemResolvers { get; set; }
  96. /// <summary>
  97. /// Gets or sets the comparers.
  98. /// </summary>
  99. /// <value>The comparers.</value>
  100. private IBaseItemComparer[] Comparers { get; set; }
  101. /// <summary>
  102. /// Gets or sets the active item repository
  103. /// </summary>
  104. /// <value>The item repository.</value>
  105. public IItemRepository ItemRepository { get; set; }
  106. /// <summary>
  107. /// Gets or sets the active image processor
  108. /// </summary>
  109. /// <value>The image processor.</value>
  110. public IImageProcessor ImageProcessor { get; set; }
  111. /// <summary>
  112. /// Occurs when [item added].
  113. /// </summary>
  114. public event EventHandler<ItemChangeEventArgs> ItemAdded;
  115. /// <summary>
  116. /// Occurs when [item updated].
  117. /// </summary>
  118. public event EventHandler<ItemChangeEventArgs> ItemUpdated;
  119. /// <summary>
  120. /// Occurs when [item removed].
  121. /// </summary>
  122. public event EventHandler<ItemChangeEventArgs> ItemRemoved;
  123. public bool IsScanRunning { get; private set; }
  124. /// <summary>
  125. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  126. /// </summary>
  127. /// <param name="appHost">The application host</param>
  128. /// <param name="logger">The logger.</param>
  129. /// <param name="taskManager">The task manager.</param>
  130. /// <param name="userManager">The user manager.</param>
  131. /// <param name="configurationManager">The configuration manager.</param>
  132. /// <param name="userDataRepository">The user data repository.</param>
  133. public LibraryManager(
  134. IServerApplicationHost appHost,
  135. ILogger<LibraryManager> logger,
  136. ITaskManager taskManager,
  137. IUserManager userManager,
  138. IServerConfigurationManager configurationManager,
  139. IUserDataManager userDataRepository,
  140. Lazy<ILibraryMonitor> libraryMonitorFactory,
  141. IFileSystem fileSystem,
  142. Lazy<IProviderManager> providerManagerFactory,
  143. Lazy<IUserViewManager> userviewManagerFactory,
  144. IMediaEncoder mediaEncoder,
  145. IItemRepository itemRepository)
  146. {
  147. _appHost = appHost;
  148. _logger = logger;
  149. _taskManager = taskManager;
  150. _userManager = userManager;
  151. _configurationManager = configurationManager;
  152. _userDataRepository = userDataRepository;
  153. _libraryMonitorFactory = libraryMonitorFactory;
  154. _fileSystem = fileSystem;
  155. _providerManagerFactory = providerManagerFactory;
  156. _userviewManagerFactory = userviewManagerFactory;
  157. _mediaEncoder = mediaEncoder;
  158. _itemRepository = itemRepository;
  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. public void UpdateImages(BaseItem item)
  1546. {
  1547. item.ImageInfos
  1548. .Where(i => (i.Width == 0 || i.Height == 0))
  1549. .ToList()
  1550. .ForEach(x =>
  1551. {
  1552. string blurhash = ImageProcessor.GetImageHash(x.Path);
  1553. ImageDimensions size = ImageProcessor.GetImageDimensions(item, x, true);
  1554. x.Width = size.Width;
  1555. x.Height = size.Height;
  1556. x.Hash = blurhash;
  1557. });
  1558. ItemRepository.SaveImages(item);
  1559. RegisterItem(item);
  1560. }
  1561. /// <summary>
  1562. /// Updates the item.
  1563. /// </summary>
  1564. public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1565. {
  1566. // Don't iterate multiple times
  1567. var itemsList = items.ToList();
  1568. foreach (var item in itemsList)
  1569. {
  1570. if (item.IsFileProtocol)
  1571. {
  1572. ProviderManager.SaveMetadata(item, updateReason);
  1573. }
  1574. item.DateLastSaved = DateTime.UtcNow;
  1575. UpdateImages(item);
  1576. }
  1577. _itemRepository.SaveItems(itemsList, cancellationToken);
  1578. if (ItemUpdated != null)
  1579. {
  1580. foreach (var item in itemsList)
  1581. {
  1582. // With the live tv guide this just creates too much noise
  1583. if (item.SourceType != SourceType.Library)
  1584. {
  1585. continue;
  1586. }
  1587. try
  1588. {
  1589. ItemUpdated(
  1590. this,
  1591. new ItemChangeEventArgs
  1592. {
  1593. Item = item,
  1594. Parent = parent,
  1595. UpdateReason = updateReason
  1596. });
  1597. }
  1598. catch (Exception ex)
  1599. {
  1600. _logger.LogError(ex, "Error in ItemUpdated event handler");
  1601. }
  1602. }
  1603. }
  1604. }
  1605. /// <summary>
  1606. /// Updates the item.
  1607. /// </summary>
  1608. /// <param name="item">The item.</param>
  1609. /// <param name="parent">The parent item.</param>
  1610. /// <param name="updateReason">The update reason.</param>
  1611. /// <param name="cancellationToken">The cancellation token.</param>
  1612. public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1613. {
  1614. UpdateItems(new[] { item }, parent, updateReason, cancellationToken);
  1615. }
  1616. /// <summary>
  1617. /// Reports the item removed.
  1618. /// </summary>
  1619. /// <param name="item">The item.</param>
  1620. /// <param name="parent">The parent item.</param>
  1621. public void ReportItemRemoved(BaseItem item, BaseItem parent)
  1622. {
  1623. if (ItemRemoved != null)
  1624. {
  1625. try
  1626. {
  1627. ItemRemoved(
  1628. this,
  1629. new ItemChangeEventArgs
  1630. {
  1631. Item = item,
  1632. Parent = parent
  1633. });
  1634. }
  1635. catch (Exception ex)
  1636. {
  1637. _logger.LogError(ex, "Error in ItemRemoved event handler");
  1638. }
  1639. }
  1640. }
  1641. /// <summary>
  1642. /// Retrieves the item.
  1643. /// </summary>
  1644. /// <param name="id">The id.</param>
  1645. /// <returns>BaseItem.</returns>
  1646. public BaseItem RetrieveItem(Guid id)
  1647. {
  1648. return _itemRepository.RetrieveItem(id);
  1649. }
  1650. public List<Folder> GetCollectionFolders(BaseItem item)
  1651. {
  1652. while (item != null)
  1653. {
  1654. var parent = item.GetParent();
  1655. if (parent == null || parent is AggregateFolder)
  1656. {
  1657. break;
  1658. }
  1659. item = parent;
  1660. }
  1661. if (item == null)
  1662. {
  1663. return new List<Folder>();
  1664. }
  1665. return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType<Folder>().ToList());
  1666. }
  1667. public List<Folder> GetCollectionFolders(BaseItem item, List<Folder> allUserRootChildren)
  1668. {
  1669. while (item != null)
  1670. {
  1671. var parent = item.GetParent();
  1672. if (parent == null || parent is AggregateFolder)
  1673. {
  1674. break;
  1675. }
  1676. item = parent;
  1677. }
  1678. if (item == null)
  1679. {
  1680. return new List<Folder>();
  1681. }
  1682. return GetCollectionFoldersInternal(item, allUserRootChildren);
  1683. }
  1684. private static List<Folder> GetCollectionFoldersInternal(BaseItem item, List<Folder> allUserRootChildren)
  1685. {
  1686. return allUserRootChildren
  1687. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase))
  1688. .ToList();
  1689. }
  1690. public LibraryOptions GetLibraryOptions(BaseItem item)
  1691. {
  1692. if (!(item is CollectionFolder collectionFolder))
  1693. {
  1694. collectionFolder = GetCollectionFolders(item)
  1695. .OfType<CollectionFolder>()
  1696. .FirstOrDefault();
  1697. }
  1698. return collectionFolder == null ? new LibraryOptions() : collectionFolder.GetLibraryOptions();
  1699. }
  1700. public string GetContentType(BaseItem item)
  1701. {
  1702. string configuredContentType = GetConfiguredContentType(item, false);
  1703. if (!string.IsNullOrEmpty(configuredContentType))
  1704. {
  1705. return configuredContentType;
  1706. }
  1707. configuredContentType = GetConfiguredContentType(item, true);
  1708. if (!string.IsNullOrEmpty(configuredContentType))
  1709. {
  1710. return configuredContentType;
  1711. }
  1712. return GetInheritedContentType(item);
  1713. }
  1714. public string GetInheritedContentType(BaseItem item)
  1715. {
  1716. var type = GetTopFolderContentType(item);
  1717. if (!string.IsNullOrEmpty(type))
  1718. {
  1719. return type;
  1720. }
  1721. return item.GetParents()
  1722. .Select(GetConfiguredContentType)
  1723. .LastOrDefault(i => !string.IsNullOrEmpty(i));
  1724. }
  1725. public string GetConfiguredContentType(BaseItem item)
  1726. {
  1727. return GetConfiguredContentType(item, false);
  1728. }
  1729. public string GetConfiguredContentType(string path)
  1730. {
  1731. return GetContentTypeOverride(path, false);
  1732. }
  1733. public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1734. {
  1735. if (item is ICollectionFolder collectionFolder)
  1736. {
  1737. return collectionFolder.CollectionType;
  1738. }
  1739. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1740. }
  1741. private string GetContentTypeOverride(string path, bool inherit)
  1742. {
  1743. var nameValuePair = _configurationManager.Configuration.ContentTypes
  1744. .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
  1745. || (inherit && !string.IsNullOrEmpty(i.Name)
  1746. && _fileSystem.ContainsSubPath(i.Name, path)));
  1747. return nameValuePair?.Value;
  1748. }
  1749. private string GetTopFolderContentType(BaseItem item)
  1750. {
  1751. if (item == null)
  1752. {
  1753. return null;
  1754. }
  1755. while (!item.ParentId.Equals(Guid.Empty))
  1756. {
  1757. var parent = item.GetParent();
  1758. if (parent == null || parent is AggregateFolder)
  1759. {
  1760. break;
  1761. }
  1762. item = parent;
  1763. }
  1764. return GetUserRootFolder().Children
  1765. .OfType<ICollectionFolder>()
  1766. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1767. .Select(i => i.CollectionType)
  1768. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1769. }
  1770. private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
  1771. public UserView GetNamedView(
  1772. User user,
  1773. string name,
  1774. string viewType,
  1775. string sortName)
  1776. {
  1777. return GetNamedView(user, name, Guid.Empty, viewType, sortName);
  1778. }
  1779. public UserView GetNamedView(
  1780. string name,
  1781. string viewType,
  1782. string sortName)
  1783. {
  1784. var path = Path.Combine(
  1785. _configurationManager.ApplicationPaths.InternalMetadataPath,
  1786. "views",
  1787. _fileSystem.GetValidFilename(viewType));
  1788. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1789. var item = GetItemById(id) as UserView;
  1790. var refresh = false;
  1791. if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1792. {
  1793. Directory.CreateDirectory(path);
  1794. item = new UserView
  1795. {
  1796. Path = path,
  1797. Id = id,
  1798. DateCreated = DateTime.UtcNow,
  1799. Name = name,
  1800. ViewType = viewType,
  1801. ForcedSortName = sortName
  1802. };
  1803. CreateItem(item, null);
  1804. refresh = true;
  1805. }
  1806. if (refresh)
  1807. {
  1808. item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None);
  1809. ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
  1810. }
  1811. return item;
  1812. }
  1813. public UserView GetNamedView(
  1814. User user,
  1815. string name,
  1816. Guid parentId,
  1817. string viewType,
  1818. string sortName)
  1819. {
  1820. var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
  1821. var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
  1822. var id = GetNewItemId(idValues, typeof(UserView));
  1823. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1824. var item = GetItemById(id) as UserView;
  1825. var isNew = false;
  1826. if (item == null)
  1827. {
  1828. Directory.CreateDirectory(path);
  1829. item = new UserView
  1830. {
  1831. Path = path,
  1832. Id = id,
  1833. DateCreated = DateTime.UtcNow,
  1834. Name = name,
  1835. ViewType = viewType,
  1836. ForcedSortName = sortName,
  1837. UserId = user.Id,
  1838. DisplayParentId = parentId
  1839. };
  1840. CreateItem(item, null);
  1841. isNew = true;
  1842. }
  1843. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1844. if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
  1845. {
  1846. var displayParent = GetItemById(item.DisplayParentId);
  1847. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1848. }
  1849. if (refresh)
  1850. {
  1851. ProviderManager.QueueRefresh(
  1852. item.Id,
  1853. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1854. {
  1855. // Need to force save to increment DateLastSaved
  1856. ForceSave = true
  1857. },
  1858. RefreshPriority.Normal);
  1859. }
  1860. return item;
  1861. }
  1862. public UserView GetShadowView(
  1863. BaseItem parent,
  1864. string viewType,
  1865. string sortName)
  1866. {
  1867. if (parent == null)
  1868. {
  1869. throw new ArgumentNullException(nameof(parent));
  1870. }
  1871. var name = parent.Name;
  1872. var parentId = parent.Id;
  1873. var idValues = "38_namedview_" + name + parentId + (viewType ?? string.Empty);
  1874. var id = GetNewItemId(idValues, typeof(UserView));
  1875. var path = parent.Path;
  1876. var item = GetItemById(id) as UserView;
  1877. var isNew = false;
  1878. if (item == null)
  1879. {
  1880. Directory.CreateDirectory(path);
  1881. item = new UserView
  1882. {
  1883. Path = path,
  1884. Id = id,
  1885. DateCreated = DateTime.UtcNow,
  1886. Name = name,
  1887. ViewType = viewType,
  1888. ForcedSortName = sortName
  1889. };
  1890. item.DisplayParentId = parentId;
  1891. CreateItem(item, null);
  1892. isNew = true;
  1893. }
  1894. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1895. if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
  1896. {
  1897. var displayParent = GetItemById(item.DisplayParentId);
  1898. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1899. }
  1900. if (refresh)
  1901. {
  1902. ProviderManager.QueueRefresh(
  1903. item.Id,
  1904. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1905. {
  1906. // Need to force save to increment DateLastSaved
  1907. ForceSave = true
  1908. },
  1909. RefreshPriority.Normal);
  1910. }
  1911. return item;
  1912. }
  1913. public UserView GetNamedView(
  1914. string name,
  1915. Guid parentId,
  1916. string viewType,
  1917. string sortName,
  1918. string uniqueId)
  1919. {
  1920. if (string.IsNullOrEmpty(name))
  1921. {
  1922. throw new ArgumentNullException(nameof(name));
  1923. }
  1924. var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
  1925. var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
  1926. if (!string.IsNullOrEmpty(uniqueId))
  1927. {
  1928. idValues += uniqueId;
  1929. }
  1930. var id = GetNewItemId(idValues, typeof(UserView));
  1931. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1932. var item = GetItemById(id) as UserView;
  1933. var isNew = false;
  1934. if (item == null)
  1935. {
  1936. Directory.CreateDirectory(path);
  1937. item = new UserView
  1938. {
  1939. Path = path,
  1940. Id = id,
  1941. DateCreated = DateTime.UtcNow,
  1942. Name = name,
  1943. ViewType = viewType,
  1944. ForcedSortName = sortName
  1945. };
  1946. item.DisplayParentId = parentId;
  1947. CreateItem(item, null);
  1948. isNew = true;
  1949. }
  1950. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1951. {
  1952. item.ViewType = viewType;
  1953. item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  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 void AddExternalSubtitleStreams(
  1975. List<MediaStream> streams,
  1976. string videoPath,
  1977. string[] files)
  1978. {
  1979. new SubtitleResolver(BaseItem.LocalizationManager).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files);
  1980. }
  1981. /// <inheritdoc />
  1982. public bool IsVideoFile(string path)
  1983. {
  1984. var resolver = new VideoResolver(GetNamingOptions());
  1985. return resolver.IsVideoFile(path);
  1986. }
  1987. /// <inheritdoc />
  1988. public bool IsAudioFile(string path)
  1989. => AudioFileParser.IsAudioFile(path, GetNamingOptions());
  1990. /// <inheritdoc />
  1991. public int? GetSeasonNumberFromPath(string path)
  1992. => SeasonPathParser.Parse(path, true, true).SeasonNumber;
  1993. /// <inheritdoc />
  1994. public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
  1995. {
  1996. var series = episode.Series;
  1997. bool? isAbsoluteNaming = series == null ? false : string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
  1998. if (!isAbsoluteNaming.Value)
  1999. {
  2000. // In other words, no filter applied
  2001. isAbsoluteNaming = null;
  2002. }
  2003. var resolver = new EpisodeResolver(GetNamingOptions());
  2004. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
  2005. var episodeInfo = episode.IsFileProtocol ?
  2006. resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) :
  2007. new Naming.TV.EpisodeInfo();
  2008. if (episodeInfo == null)
  2009. {
  2010. episodeInfo = new Naming.TV.EpisodeInfo();
  2011. }
  2012. try
  2013. {
  2014. var libraryOptions = GetLibraryOptions(episode);
  2015. if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(episodeInfo.Container, "mp4", StringComparison.OrdinalIgnoreCase))
  2016. {
  2017. // Read from metadata
  2018. var mediaInfo = _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  2019. {
  2020. MediaSource = episode.GetMediaSources(false)[0],
  2021. MediaType = DlnaProfileType.Video
  2022. }, CancellationToken.None).GetAwaiter().GetResult();
  2023. if (mediaInfo.ParentIndexNumber > 0)
  2024. {
  2025. episodeInfo.SeasonNumber = mediaInfo.ParentIndexNumber;
  2026. }
  2027. if (mediaInfo.IndexNumber > 0)
  2028. {
  2029. episodeInfo.EpisodeNumber = mediaInfo.IndexNumber;
  2030. }
  2031. if (!string.IsNullOrEmpty(mediaInfo.ShowName))
  2032. {
  2033. episodeInfo.SeriesName = mediaInfo.ShowName;
  2034. }
  2035. }
  2036. }
  2037. catch (Exception ex)
  2038. {
  2039. _logger.LogError(ex, "Error reading the episode informations with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
  2040. }
  2041. var changed = false;
  2042. if (episodeInfo.IsByDate)
  2043. {
  2044. if (episode.IndexNumber.HasValue)
  2045. {
  2046. episode.IndexNumber = null;
  2047. changed = true;
  2048. }
  2049. if (episode.IndexNumberEnd.HasValue)
  2050. {
  2051. episode.IndexNumberEnd = null;
  2052. changed = true;
  2053. }
  2054. if (!episode.PremiereDate.HasValue)
  2055. {
  2056. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  2057. {
  2058. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  2059. }
  2060. if (episode.PremiereDate.HasValue)
  2061. {
  2062. changed = true;
  2063. }
  2064. }
  2065. if (!episode.ProductionYear.HasValue)
  2066. {
  2067. episode.ProductionYear = episodeInfo.Year;
  2068. if (episode.ProductionYear.HasValue)
  2069. {
  2070. changed = true;
  2071. }
  2072. }
  2073. }
  2074. else
  2075. {
  2076. if (!episode.IndexNumber.HasValue || forceRefresh)
  2077. {
  2078. if (episode.IndexNumber != episodeInfo.EpisodeNumber)
  2079. {
  2080. changed = true;
  2081. }
  2082. episode.IndexNumber = episodeInfo.EpisodeNumber;
  2083. }
  2084. if (!episode.IndexNumberEnd.HasValue || forceRefresh)
  2085. {
  2086. if (episode.IndexNumberEnd != episodeInfo.EndingEpsiodeNumber)
  2087. {
  2088. changed = true;
  2089. }
  2090. episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
  2091. }
  2092. if (!episode.ParentIndexNumber.HasValue || forceRefresh)
  2093. {
  2094. if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
  2095. {
  2096. changed = true;
  2097. }
  2098. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  2099. }
  2100. }
  2101. if (!episode.ParentIndexNumber.HasValue)
  2102. {
  2103. var season = episode.Season;
  2104. if (season != null)
  2105. {
  2106. episode.ParentIndexNumber = season.IndexNumber;
  2107. }
  2108. else
  2109. {
  2110. /*
  2111. Anime series don't generally have a season in their file name, however,
  2112. tvdb needs a season to correctly get the metadata.
  2113. Hence, a null season needs to be filled with something. */
  2114. //FIXME perhaps this would be better for tvdb parser to ask for season 1 if no season is specified
  2115. episode.ParentIndexNumber = 1;
  2116. }
  2117. if (episode.ParentIndexNumber.HasValue)
  2118. {
  2119. changed = true;
  2120. }
  2121. }
  2122. return changed;
  2123. }
  2124. public NamingOptions GetNamingOptions()
  2125. {
  2126. if (_namingOptions == null)
  2127. {
  2128. _namingOptions = new NamingOptions();
  2129. _videoFileExtensions = _namingOptions.VideoFileExtensions;
  2130. }
  2131. return _namingOptions;
  2132. }
  2133. public ItemLookupInfo ParseName(string name)
  2134. {
  2135. var resolver = new VideoResolver(GetNamingOptions());
  2136. var result = resolver.CleanDateTime(name);
  2137. return new ItemLookupInfo
  2138. {
  2139. Name = resolver.TryCleanString(result.Name, out var newName) ? newName.ToString() : result.Name,
  2140. Year = result.Year
  2141. };
  2142. }
  2143. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2144. {
  2145. var namingOptions = GetNamingOptions();
  2146. var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
  2147. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  2148. .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
  2149. .ToList();
  2150. var videoListResolver = new VideoListResolver(namingOptions);
  2151. var videos = videoListResolver.Resolve(fileSystemChildren);
  2152. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  2153. if (currentVideo != null)
  2154. {
  2155. files.AddRange(currentVideo.Extras.Where(i => i.ExtraType == ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
  2156. }
  2157. var resolvers = new IItemResolver[]
  2158. {
  2159. new GenericVideoResolver<Trailer>(this)
  2160. };
  2161. return ResolvePaths(files, directoryService, null, new LibraryOptions(), null, resolvers)
  2162. .OfType<Trailer>()
  2163. .Select(video =>
  2164. {
  2165. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2166. var dbItem = GetItemById(video.Id) as Trailer;
  2167. if (dbItem != null)
  2168. {
  2169. video = dbItem;
  2170. }
  2171. video.ParentId = Guid.Empty;
  2172. video.OwnerId = owner.Id;
  2173. video.ExtraType = ExtraType.Trailer;
  2174. video.TrailerTypes = new[] { TrailerType.LocalTrailer };
  2175. return video;
  2176. // Sort them so that the list can be easily compared for changes
  2177. }).OrderBy(i => i.Path);
  2178. }
  2179. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2180. {
  2181. var namingOptions = GetNamingOptions();
  2182. var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
  2183. .Where(i => BaseItem.AllExtrasTypesFolderNames.Contains(i.Name ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  2184. .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
  2185. .ToList();
  2186. var videoListResolver = new VideoListResolver(namingOptions);
  2187. var videos = videoListResolver.Resolve(fileSystemChildren);
  2188. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  2189. if (currentVideo != null)
  2190. {
  2191. files.AddRange(currentVideo.Extras.Where(i => i.ExtraType != ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
  2192. }
  2193. return ResolvePaths(files, directoryService, null, new LibraryOptions(), null)
  2194. .OfType<Video>()
  2195. .Select(video =>
  2196. {
  2197. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2198. var dbItem = GetItemById(video.Id) as Video;
  2199. if (dbItem != null)
  2200. {
  2201. video = dbItem;
  2202. }
  2203. video.ParentId = Guid.Empty;
  2204. video.OwnerId = owner.Id;
  2205. SetExtraTypeFromFilename(video);
  2206. return video;
  2207. // Sort them so that the list can be easily compared for changes
  2208. }).OrderBy(i => i.Path);
  2209. }
  2210. public string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem)
  2211. {
  2212. if (ownerItem != null)
  2213. {
  2214. var libraryOptions = GetLibraryOptions(ownerItem);
  2215. if (libraryOptions != null)
  2216. {
  2217. foreach (var pathInfo in libraryOptions.PathInfos)
  2218. {
  2219. if (string.IsNullOrWhiteSpace(pathInfo.Path) || string.IsNullOrWhiteSpace(pathInfo.NetworkPath))
  2220. {
  2221. continue;
  2222. }
  2223. var substitutionResult = SubstitutePathInternal(path, pathInfo.Path, pathInfo.NetworkPath);
  2224. if (substitutionResult.Item2)
  2225. {
  2226. return substitutionResult.Item1;
  2227. }
  2228. }
  2229. }
  2230. }
  2231. var metadataPath = _configurationManager.Configuration.MetadataPath;
  2232. var metadataNetworkPath = _configurationManager.Configuration.MetadataNetworkPath;
  2233. if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath))
  2234. {
  2235. var metadataSubstitutionResult = SubstitutePathInternal(path, metadataPath, metadataNetworkPath);
  2236. if (metadataSubstitutionResult.Item2)
  2237. {
  2238. return metadataSubstitutionResult.Item1;
  2239. }
  2240. }
  2241. foreach (var map in _configurationManager.Configuration.PathSubstitutions)
  2242. {
  2243. if (!string.IsNullOrWhiteSpace(map.From))
  2244. {
  2245. var substitutionResult = SubstitutePathInternal(path, map.From, map.To);
  2246. if (substitutionResult.Item2)
  2247. {
  2248. return substitutionResult.Item1;
  2249. }
  2250. }
  2251. }
  2252. return path;
  2253. }
  2254. public string SubstitutePath(string path, string from, string to)
  2255. {
  2256. return SubstitutePathInternal(path, from, to).Item1;
  2257. }
  2258. private Tuple<string, bool> SubstitutePathInternal(string path, string from, string to)
  2259. {
  2260. if (string.IsNullOrWhiteSpace(path))
  2261. {
  2262. throw new ArgumentNullException(nameof(path));
  2263. }
  2264. if (string.IsNullOrWhiteSpace(from))
  2265. {
  2266. throw new ArgumentNullException(nameof(from));
  2267. }
  2268. if (string.IsNullOrWhiteSpace(to))
  2269. {
  2270. throw new ArgumentNullException(nameof(to));
  2271. }
  2272. from = from.Trim();
  2273. to = to.Trim();
  2274. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  2275. var changed = false;
  2276. if (!string.Equals(newPath, path, StringComparison.Ordinal))
  2277. {
  2278. if (to.IndexOf('/', StringComparison.Ordinal) != -1)
  2279. {
  2280. newPath = newPath.Replace('\\', '/');
  2281. }
  2282. else
  2283. {
  2284. newPath = newPath.Replace('/', '\\');
  2285. }
  2286. changed = true;
  2287. }
  2288. return new Tuple<string, bool>(newPath, changed);
  2289. }
  2290. private void SetExtraTypeFromFilename(Video item)
  2291. {
  2292. var resolver = new ExtraResolver(GetNamingOptions());
  2293. var result = resolver.GetExtraInfo(item.Path);
  2294. item.ExtraType = result.ExtraType;
  2295. }
  2296. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  2297. {
  2298. return _itemRepository.GetPeople(query);
  2299. }
  2300. public List<PersonInfo> GetPeople(BaseItem item)
  2301. {
  2302. if (item.SupportsPeople)
  2303. {
  2304. var people = GetPeople(new InternalPeopleQuery
  2305. {
  2306. ItemId = item.Id
  2307. });
  2308. if (people.Count > 0)
  2309. {
  2310. return people;
  2311. }
  2312. }
  2313. return new List<PersonInfo>();
  2314. }
  2315. public List<Person> GetPeopleItems(InternalPeopleQuery query)
  2316. {
  2317. return _itemRepository.GetPeopleNames(query).Select(i =>
  2318. {
  2319. try
  2320. {
  2321. return GetPerson(i);
  2322. }
  2323. catch (Exception ex)
  2324. {
  2325. _logger.LogError(ex, "Error getting person");
  2326. return null;
  2327. }
  2328. }).Where(i => i != null).ToList();
  2329. }
  2330. public List<string> GetPeopleNames(InternalPeopleQuery query)
  2331. {
  2332. return _itemRepository.GetPeopleNames(query);
  2333. }
  2334. public void UpdatePeople(BaseItem item, List<PersonInfo> people)
  2335. {
  2336. if (!item.SupportsPeople)
  2337. {
  2338. return;
  2339. }
  2340. _itemRepository.UpdatePeople(item.Id, people);
  2341. }
  2342. public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex)
  2343. {
  2344. foreach (var url in image.Path.Split('|'))
  2345. {
  2346. try
  2347. {
  2348. _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2349. await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2350. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2351. return item.GetImageInfo(image.Type, imageIndex);
  2352. }
  2353. catch (HttpException ex)
  2354. {
  2355. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  2356. {
  2357. continue;
  2358. }
  2359. throw;
  2360. }
  2361. }
  2362. // Remove this image to prevent it from retrying over and over
  2363. item.RemoveImage(image);
  2364. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2365. throw new InvalidOperationException();
  2366. }
  2367. public async Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary)
  2368. {
  2369. if (string.IsNullOrWhiteSpace(name))
  2370. {
  2371. throw new ArgumentNullException(nameof(name));
  2372. }
  2373. name = _fileSystem.GetValidFilename(name);
  2374. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2375. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2376. while (Directory.Exists(virtualFolderPath))
  2377. {
  2378. name += "1";
  2379. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2380. }
  2381. var mediaPathInfos = options.PathInfos;
  2382. if (mediaPathInfos != null)
  2383. {
  2384. var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
  2385. if (invalidpath != null)
  2386. {
  2387. throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
  2388. }
  2389. }
  2390. LibraryMonitor.Stop();
  2391. try
  2392. {
  2393. Directory.CreateDirectory(virtualFolderPath);
  2394. if (!string.IsNullOrEmpty(collectionType))
  2395. {
  2396. var path = Path.Combine(virtualFolderPath, collectionType + ".collection");
  2397. File.WriteAllBytes(path, Array.Empty<byte>());
  2398. }
  2399. CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
  2400. if (mediaPathInfos != null)
  2401. {
  2402. foreach (var path in mediaPathInfos)
  2403. {
  2404. AddMediaPathInternal(name, path, false);
  2405. }
  2406. }
  2407. }
  2408. finally
  2409. {
  2410. if (refreshLibrary)
  2411. {
  2412. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2413. StartScanInBackground();
  2414. }
  2415. else
  2416. {
  2417. // Need to add a delay here or directory watchers may still pick up the changes
  2418. await Task.Delay(1000).ConfigureAwait(false);
  2419. LibraryMonitor.Start();
  2420. }
  2421. }
  2422. }
  2423. private void StartScanInBackground()
  2424. {
  2425. Task.Run(() =>
  2426. {
  2427. // No need to start if scanning the library because it will handle it
  2428. ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
  2429. });
  2430. }
  2431. private static bool ValidateNetworkPath(string path)
  2432. {
  2433. //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  2434. //{
  2435. // // We can't validate protocol-based paths, so just allow them
  2436. // if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
  2437. // {
  2438. // return Directory.Exists(path);
  2439. // }
  2440. //}
  2441. // Without native support for unc, we cannot validate this when running under mono
  2442. return true;
  2443. }
  2444. private const string ShortcutFileExtension = ".mblink";
  2445. public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
  2446. {
  2447. AddMediaPathInternal(virtualFolderName, pathInfo, true);
  2448. }
  2449. private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
  2450. {
  2451. if (pathInfo == null)
  2452. {
  2453. throw new ArgumentNullException(nameof(pathInfo));
  2454. }
  2455. var path = pathInfo.Path;
  2456. if (string.IsNullOrWhiteSpace(path))
  2457. {
  2458. throw new ArgumentException(nameof(path));
  2459. }
  2460. if (!Directory.Exists(path))
  2461. {
  2462. throw new FileNotFoundException("The path does not exist.");
  2463. }
  2464. if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
  2465. {
  2466. throw new FileNotFoundException("The network path does not exist.");
  2467. }
  2468. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2469. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2470. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  2471. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2472. while (File.Exists(lnk))
  2473. {
  2474. shortcutFilename += "1";
  2475. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2476. }
  2477. _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
  2478. RemoveContentTypeOverrides(path);
  2479. if (saveLibraryOptions)
  2480. {
  2481. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2482. var list = libraryOptions.PathInfos.ToList();
  2483. list.Add(pathInfo);
  2484. libraryOptions.PathInfos = list.ToArray();
  2485. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2486. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2487. }
  2488. }
  2489. public void UpdateMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
  2490. {
  2491. if (pathInfo == null)
  2492. {
  2493. throw new ArgumentNullException(nameof(pathInfo));
  2494. }
  2495. if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
  2496. {
  2497. throw new FileNotFoundException("The network path does not exist.");
  2498. }
  2499. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2500. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2501. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2502. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2503. var list = libraryOptions.PathInfos.ToList();
  2504. foreach (var originalPathInfo in list)
  2505. {
  2506. if (string.Equals(pathInfo.Path, originalPathInfo.Path, StringComparison.Ordinal))
  2507. {
  2508. originalPathInfo.NetworkPath = pathInfo.NetworkPath;
  2509. break;
  2510. }
  2511. }
  2512. libraryOptions.PathInfos = list.ToArray();
  2513. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2514. }
  2515. private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
  2516. {
  2517. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  2518. var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
  2519. if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
  2520. {
  2521. var list = options.PathInfos.ToList();
  2522. foreach (var location in info.Locations)
  2523. {
  2524. if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
  2525. {
  2526. list.Add(new MediaPathInfo
  2527. {
  2528. Path = location
  2529. });
  2530. }
  2531. }
  2532. options.PathInfos = list.ToArray();
  2533. }
  2534. }
  2535. public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
  2536. {
  2537. if (string.IsNullOrWhiteSpace(name))
  2538. {
  2539. throw new ArgumentNullException(nameof(name));
  2540. }
  2541. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2542. var path = Path.Combine(rootFolderPath, name);
  2543. if (!Directory.Exists(path))
  2544. {
  2545. throw new FileNotFoundException("The media folder does not exist");
  2546. }
  2547. LibraryMonitor.Stop();
  2548. try
  2549. {
  2550. Directory.Delete(path, true);
  2551. }
  2552. finally
  2553. {
  2554. CollectionFolder.OnCollectionFolderChange();
  2555. if (refreshLibrary)
  2556. {
  2557. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2558. StartScanInBackground();
  2559. }
  2560. else
  2561. {
  2562. // Need to add a delay here or directory watchers may still pick up the changes
  2563. await Task.Delay(1000).ConfigureAwait(false);
  2564. LibraryMonitor.Start();
  2565. }
  2566. }
  2567. }
  2568. private void RemoveContentTypeOverrides(string path)
  2569. {
  2570. if (string.IsNullOrWhiteSpace(path))
  2571. {
  2572. throw new ArgumentNullException(nameof(path));
  2573. }
  2574. var removeList = new List<NameValuePair>();
  2575. foreach (var contentType in _configurationManager.Configuration.ContentTypes)
  2576. {
  2577. if (string.IsNullOrWhiteSpace(contentType.Name))
  2578. {
  2579. removeList.Add(contentType);
  2580. }
  2581. else if (_fileSystem.AreEqual(path, contentType.Name)
  2582. || _fileSystem.ContainsSubPath(path, contentType.Name))
  2583. {
  2584. removeList.Add(contentType);
  2585. }
  2586. }
  2587. if (removeList.Count > 0)
  2588. {
  2589. _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
  2590. .Except(removeList)
  2591. .ToArray();
  2592. _configurationManager.SaveConfiguration();
  2593. }
  2594. }
  2595. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2596. {
  2597. if (string.IsNullOrEmpty(mediaPath))
  2598. {
  2599. throw new ArgumentNullException(nameof(mediaPath));
  2600. }
  2601. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2602. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2603. if (!Directory.Exists(virtualFolderPath))
  2604. {
  2605. throw new FileNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
  2606. }
  2607. var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
  2608. .Where(i => string.Equals(ShortcutFileExtension, Path.GetExtension(i), StringComparison.OrdinalIgnoreCase))
  2609. .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2610. if (!string.IsNullOrEmpty(shortcut))
  2611. {
  2612. _fileSystem.DeleteFile(shortcut);
  2613. }
  2614. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2615. libraryOptions.PathInfos = libraryOptions
  2616. .PathInfos
  2617. .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
  2618. .ToArray();
  2619. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2620. }
  2621. }
  2622. }