LibraryManager.cs 95 KB

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