LibraryManager.cs 98 KB

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