LibraryManager.cs 94 KB

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