LibraryManager.cs 109 KB

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