LibraryManager.cs 109 KB

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