LibraryManager.cs 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733
  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. return CreateItemByName<T>(fullPath, name);
  798. }
  799. private T CreateItemByName<T>(string path, string name)
  800. where T : BaseItem, new()
  801. {
  802. var isArtist = typeof(T) == typeof(MusicArtist);
  803. if (isArtist)
  804. {
  805. var existing = GetItemList(new InternalItemsQuery
  806. {
  807. IncludeItemTypes = new[] { typeof(T).Name },
  808. Name = name
  809. }).Cast<MusicArtist>()
  810. .OrderBy(i => i.IsAccessedByName ? 1 : 0)
  811. .Cast<T>()
  812. .FirstOrDefault();
  813. if (existing != null)
  814. {
  815. return existing;
  816. }
  817. }
  818. var id = GetNewItemId(path, typeof(T));
  819. var item = GetItemById(id) as T;
  820. if (item == null)
  821. {
  822. item = new T
  823. {
  824. Name = name,
  825. Id = id,
  826. DateCreated = DateTime.UtcNow,
  827. DateModified = DateTime.UtcNow,
  828. Path = path
  829. };
  830. var task = CreateItem(item, CancellationToken.None);
  831. Task.WaitAll(task);
  832. }
  833. return item;
  834. }
  835. public IEnumerable<MusicArtist> GetAlbumArtists(IEnumerable<IHasAlbumArtist> items)
  836. {
  837. var names = items
  838. .SelectMany(i => i.AlbumArtists)
  839. .DistinctNames()
  840. .Select(i =>
  841. {
  842. try
  843. {
  844. var artist = GetArtist(i);
  845. return artist;
  846. }
  847. catch
  848. {
  849. // Already logged at lower levels
  850. return null;
  851. }
  852. })
  853. .Where(i => i != null);
  854. return names;
  855. }
  856. public IEnumerable<MusicArtist> GetArtists(IEnumerable<IHasArtist> items)
  857. {
  858. var names = items
  859. .SelectMany(i => i.AllArtists)
  860. .DistinctNames()
  861. .Select(i =>
  862. {
  863. try
  864. {
  865. var artist = GetArtist(i);
  866. return artist;
  867. }
  868. catch
  869. {
  870. // Already logged at lower levels
  871. return null;
  872. }
  873. })
  874. .Where(i => i != null);
  875. return names;
  876. }
  877. /// <summary>
  878. /// Validate and refresh the People sub-set of the IBN.
  879. /// The items are stored in the db but not loaded into memory until actually requested by an operation.
  880. /// </summary>
  881. /// <param name="cancellationToken">The cancellation token.</param>
  882. /// <param name="progress">The progress.</param>
  883. /// <returns>Task.</returns>
  884. public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress)
  885. {
  886. // Ensure the location is available.
  887. _fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath);
  888. return new PeopleValidator(this, _logger, ConfigurationManager, _fileSystem).ValidatePeople(cancellationToken, progress);
  889. }
  890. /// <summary>
  891. /// Reloads the root media folder
  892. /// </summary>
  893. /// <param name="progress">The progress.</param>
  894. /// <param name="cancellationToken">The cancellation token.</param>
  895. /// <returns>Task.</returns>
  896. public Task ValidateMediaLibrary(IProgress<double> progress, CancellationToken cancellationToken)
  897. {
  898. // Just run the scheduled task so that the user can see it
  899. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  900. return Task.FromResult(true);
  901. }
  902. /// <summary>
  903. /// Queues the library scan.
  904. /// </summary>
  905. public void QueueLibraryScan()
  906. {
  907. // Just run the scheduled task so that the user can see it
  908. _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>();
  909. }
  910. /// <summary>
  911. /// Validates the media library internal.
  912. /// </summary>
  913. /// <param name="progress">The progress.</param>
  914. /// <param name="cancellationToken">The cancellation token.</param>
  915. /// <returns>Task.</returns>
  916. public async Task ValidateMediaLibraryInternal(IProgress<double> progress, CancellationToken cancellationToken)
  917. {
  918. IsScanRunning = true;
  919. _libraryMonitorFactory().Stop();
  920. try
  921. {
  922. await PerformLibraryValidation(progress, cancellationToken).ConfigureAwait(false);
  923. }
  924. finally
  925. {
  926. _libraryMonitorFactory().Start();
  927. IsScanRunning = false;
  928. }
  929. }
  930. private async Task PerformLibraryValidation(IProgress<double> progress, CancellationToken cancellationToken)
  931. {
  932. _logger.Info("Validating media library");
  933. await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  934. progress.Report(.5);
  935. // Start by just validating the children of the root, but go no further
  936. await RootFolder.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false);
  937. progress.Report(1);
  938. var userRoot = GetUserRootFolder();
  939. await userRoot.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  940. await userRoot.ValidateChildren(new Progress<double>(), cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: false).ConfigureAwait(false);
  941. progress.Report(2);
  942. var innerProgress = new ActionableProgress<double>();
  943. innerProgress.RegisterAction(pct => progress.Report(2 + pct * .73));
  944. // Now validate the entire media library
  945. await RootFolder.ValidateChildren(innerProgress, cancellationToken, new MetadataRefreshOptions(_fileSystem), recursive: true).ConfigureAwait(false);
  946. progress.Report(75);
  947. innerProgress = new ActionableProgress<double>();
  948. innerProgress.RegisterAction(pct => progress.Report(75 + pct * .25));
  949. // Run post-scan tasks
  950. await RunPostScanTasks(innerProgress, cancellationToken).ConfigureAwait(false);
  951. progress.Report(100);
  952. // Bad practice, i know. But we keep a lot in memory, unfortunately.
  953. GC.Collect(2, GCCollectionMode.Forced, true);
  954. GC.Collect(2, GCCollectionMode.Forced, true);
  955. }
  956. /// <summary>
  957. /// Runs the post scan tasks.
  958. /// </summary>
  959. /// <param name="progress">The progress.</param>
  960. /// <param name="cancellationToken">The cancellation token.</param>
  961. /// <returns>Task.</returns>
  962. private async Task RunPostScanTasks(IProgress<double> progress, CancellationToken cancellationToken)
  963. {
  964. var tasks = PostscanTasks.ToList();
  965. var numComplete = 0;
  966. var numTasks = tasks.Count;
  967. foreach (var task in tasks)
  968. {
  969. var innerProgress = new ActionableProgress<double>();
  970. // Prevent access to modified closure
  971. var currentNumComplete = numComplete;
  972. innerProgress.RegisterAction(pct =>
  973. {
  974. double innerPercent = currentNumComplete * 100 + pct;
  975. innerPercent /= numTasks;
  976. progress.Report(innerPercent);
  977. });
  978. _logger.Debug("Running post-scan task {0}", task.GetType().Name);
  979. try
  980. {
  981. await task.Run(innerProgress, cancellationToken).ConfigureAwait(false);
  982. }
  983. catch (OperationCanceledException)
  984. {
  985. _logger.Info("Post-scan task cancelled: {0}", task.GetType().Name);
  986. }
  987. catch (Exception ex)
  988. {
  989. _logger.ErrorException("Error running postscan task", ex);
  990. }
  991. numComplete++;
  992. double percent = numComplete;
  993. percent /= numTasks;
  994. progress.Report(percent * 100);
  995. }
  996. progress.Report(100);
  997. }
  998. /// <summary>
  999. /// Gets the default view.
  1000. /// </summary>
  1001. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  1002. public IEnumerable<VirtualFolderInfo> GetVirtualFolders()
  1003. {
  1004. return GetView(ConfigurationManager.ApplicationPaths.DefaultUserViewsPath);
  1005. }
  1006. /// <summary>
  1007. /// Gets the view.
  1008. /// </summary>
  1009. /// <param name="path">The path.</param>
  1010. /// <returns>IEnumerable{VirtualFolderInfo}.</returns>
  1011. private IEnumerable<VirtualFolderInfo> GetView(string path)
  1012. {
  1013. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  1014. return _fileSystem.GetDirectoryPaths(path)
  1015. .Select(dir => GetVirtualFolderInfo(dir, topLibraryFolders));
  1016. }
  1017. private VirtualFolderInfo GetVirtualFolderInfo(string dir, List<BaseItem> collectionFolders)
  1018. {
  1019. var info = new VirtualFolderInfo
  1020. {
  1021. Name = Path.GetFileName(dir),
  1022. Locations = Directory.EnumerateFiles(dir, "*.mblink", SearchOption.TopDirectoryOnly)
  1023. .Select(_fileSystem.ResolveShortcut)
  1024. .OrderBy(i => i)
  1025. .ToList(),
  1026. CollectionType = GetCollectionType(dir)
  1027. };
  1028. var libraryFolder = collectionFolders.FirstOrDefault(i => string.Equals(i.Path, dir, StringComparison.OrdinalIgnoreCase));
  1029. if (libraryFolder != null && libraryFolder.HasImage(ImageType.Primary))
  1030. {
  1031. info.PrimaryImageItemId = libraryFolder.Id.ToString("N");
  1032. }
  1033. if (libraryFolder != null)
  1034. {
  1035. info.ItemId = libraryFolder.Id.ToString("N");
  1036. }
  1037. return info;
  1038. }
  1039. private string GetCollectionType(string path)
  1040. {
  1041. return _fileSystem.GetFiles(path, false)
  1042. .Where(i => string.Equals(i.Extension, ".collection", StringComparison.OrdinalIgnoreCase))
  1043. .Select(i => _fileSystem.GetFileNameWithoutExtension(i))
  1044. .FirstOrDefault();
  1045. }
  1046. /// <summary>
  1047. /// Gets the item by id.
  1048. /// </summary>
  1049. /// <param name="id">The id.</param>
  1050. /// <returns>BaseItem.</returns>
  1051. /// <exception cref="System.ArgumentNullException">id</exception>
  1052. public BaseItem GetItemById(Guid id)
  1053. {
  1054. if (id == Guid.Empty)
  1055. {
  1056. throw new ArgumentNullException("id");
  1057. }
  1058. BaseItem item;
  1059. if (LibraryItemsCache.TryGetValue(id, out item))
  1060. {
  1061. return item;
  1062. }
  1063. item = RetrieveItem(id);
  1064. if (item != null)
  1065. {
  1066. RegisterItem(item);
  1067. }
  1068. return item;
  1069. }
  1070. public BaseItem GetMemoryItemById(Guid id)
  1071. {
  1072. if (id == Guid.Empty)
  1073. {
  1074. throw new ArgumentNullException("id");
  1075. }
  1076. BaseItem item;
  1077. LibraryItemsCache.TryGetValue(id, out item);
  1078. return item;
  1079. }
  1080. public IEnumerable<BaseItem> GetItemList(InternalItemsQuery query)
  1081. {
  1082. if (query.User != null)
  1083. {
  1084. AddUserToQuery(query, query.User);
  1085. }
  1086. var result = ItemRepository.GetItemIdsList(query);
  1087. return result.Select(GetItemById).Where(i => i != null);
  1088. }
  1089. public QueryResult<BaseItem> QueryItems(InternalItemsQuery query)
  1090. {
  1091. if (query.User != null)
  1092. {
  1093. AddUserToQuery(query, query.User);
  1094. }
  1095. return ItemRepository.GetItems(query);
  1096. }
  1097. public List<Guid> GetItemIds(InternalItemsQuery query)
  1098. {
  1099. if (query.User != null)
  1100. {
  1101. AddUserToQuery(query, query.User);
  1102. }
  1103. return ItemRepository.GetItemIdsList(query);
  1104. }
  1105. public IEnumerable<BaseItem> GetItemList(InternalItemsQuery query, IEnumerable<string> parentIds)
  1106. {
  1107. var parents = parentIds.Select(i => GetItemById(new Guid(i))).Where(i => i != null).ToList();
  1108. SetTopParentIdsOrAncestors(query, parents);
  1109. return GetItemIds(query).Select(GetItemById).Where(i => i != null);
  1110. }
  1111. public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query)
  1112. {
  1113. if (query.Recursive && query.ParentId.HasValue)
  1114. {
  1115. var parent = GetItemById(query.ParentId.Value);
  1116. if (parent != null)
  1117. {
  1118. SetTopParentIdsOrAncestors(query, new List<BaseItem> { parent });
  1119. query.ParentId = null;
  1120. }
  1121. }
  1122. if (query.User != null)
  1123. {
  1124. AddUserToQuery(query, query.User);
  1125. }
  1126. if (query.EnableTotalRecordCount)
  1127. {
  1128. var initialResult = ItemRepository.GetItemIds(query);
  1129. return new QueryResult<BaseItem>
  1130. {
  1131. TotalRecordCount = initialResult.TotalRecordCount,
  1132. Items = initialResult.Items.Select(GetItemById).Where(i => i != null).ToArray()
  1133. };
  1134. }
  1135. return new QueryResult<BaseItem>
  1136. {
  1137. Items = ItemRepository.GetItemIdsList(query).Select(GetItemById).Where(i => i != null).ToArray()
  1138. };
  1139. }
  1140. public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query, IEnumerable<string> parentIds)
  1141. {
  1142. var parents = parentIds.Select(i => GetItemById(new Guid(i))).Where(i => i != null).ToList();
  1143. SetTopParentIdsOrAncestors(query, parents);
  1144. return GetItemsResult(query);
  1145. }
  1146. private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents)
  1147. {
  1148. if (parents.All(i =>
  1149. {
  1150. if (i is ICollectionFolder || i is UserView)
  1151. {
  1152. return true;
  1153. }
  1154. _logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name);
  1155. return false;
  1156. }))
  1157. {
  1158. // Optimize by querying against top level views
  1159. query.TopParentIds = parents.SelectMany(i => GetTopParentsForQuery(i, query.User)).Select(i => i.Id.ToString("N")).ToArray();
  1160. }
  1161. else
  1162. {
  1163. // We need to be able to query from any arbitrary ancestor up the tree
  1164. query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).Select(i => i.ToString("N")).ToArray();
  1165. }
  1166. }
  1167. private void AddUserToQuery(InternalItemsQuery query, User user)
  1168. {
  1169. if (query.AncestorIds.Length == 0 && !query.ParentId.HasValue && query.ChannelIds.Length == 0 && query.TopParentIds.Length == 0 && string.IsNullOrWhiteSpace(query.AncestorWithPresentationUniqueKey))
  1170. {
  1171. var userViews = _userviewManager().GetUserViews(new UserViewQuery
  1172. {
  1173. UserId = user.Id.ToString("N"),
  1174. IncludeHidden = true
  1175. }, CancellationToken.None).Result.ToList();
  1176. query.TopParentIds = userViews.SelectMany(i => GetTopParentsForQuery(i, user)).Select(i => i.Id.ToString("N")).ToArray();
  1177. }
  1178. }
  1179. private IEnumerable<BaseItem> GetTopParentsForQuery(BaseItem item, User user)
  1180. {
  1181. var view = item as UserView;
  1182. if (view != null)
  1183. {
  1184. if (string.Equals(view.ViewType, CollectionType.LiveTv))
  1185. {
  1186. return new[] { view };
  1187. }
  1188. if (string.Equals(view.ViewType, CollectionType.Channels))
  1189. {
  1190. // TODO: Return channels
  1191. return new[] { view };
  1192. }
  1193. // Translate view into folders
  1194. if (view.DisplayParentId != Guid.Empty)
  1195. {
  1196. var displayParent = GetItemById(view.DisplayParentId);
  1197. if (displayParent != null)
  1198. {
  1199. return GetTopParentsForQuery(displayParent, user);
  1200. }
  1201. return new BaseItem[] { };
  1202. }
  1203. if (view.ParentId != Guid.Empty)
  1204. {
  1205. var displayParent = GetItemById(view.ParentId);
  1206. if (displayParent != null)
  1207. {
  1208. return GetTopParentsForQuery(displayParent, user);
  1209. }
  1210. return new BaseItem[] { };
  1211. }
  1212. // Handle grouping
  1213. if (user != null && !string.IsNullOrWhiteSpace(view.ViewType) && UserView.IsEligibleForGrouping(view.ViewType))
  1214. {
  1215. var collectionFolders = user.RootFolder.GetChildren(user, true).OfType<CollectionFolder>().Where(i => string.IsNullOrWhiteSpace(i.CollectionType) || string.Equals(i.CollectionType, view.ViewType, StringComparison.OrdinalIgnoreCase));
  1216. return collectionFolders.SelectMany(i => GetTopParentsForQuery(i, user));
  1217. }
  1218. return new BaseItem[] { };
  1219. }
  1220. var collectionFolder = item as CollectionFolder;
  1221. if (collectionFolder != null)
  1222. {
  1223. return collectionFolder.GetPhysicalParents();
  1224. }
  1225. var topParent = item.GetTopParent();
  1226. if (topParent != null)
  1227. {
  1228. return new[] { topParent };
  1229. }
  1230. return new BaseItem[] { };
  1231. }
  1232. /// <summary>
  1233. /// Gets the intros.
  1234. /// </summary>
  1235. /// <param name="item">The item.</param>
  1236. /// <param name="user">The user.</param>
  1237. /// <returns>IEnumerable{System.String}.</returns>
  1238. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1239. {
  1240. var tasks = IntroProviders
  1241. .OrderBy(i => i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1)
  1242. .Take(1)
  1243. .Select(i => GetIntros(i, item, user));
  1244. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1245. return items
  1246. .SelectMany(i => i.ToArray())
  1247. .Select(ResolveIntro)
  1248. .Where(i => i != null);
  1249. }
  1250. /// <summary>
  1251. /// Gets the intros.
  1252. /// </summary>
  1253. /// <param name="provider">The provider.</param>
  1254. /// <param name="item">The item.</param>
  1255. /// <param name="user">The user.</param>
  1256. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1257. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1258. {
  1259. try
  1260. {
  1261. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1262. }
  1263. catch (Exception ex)
  1264. {
  1265. _logger.ErrorException("Error getting intros", ex);
  1266. return new List<IntroInfo>();
  1267. }
  1268. }
  1269. /// <summary>
  1270. /// Gets all intro files.
  1271. /// </summary>
  1272. /// <returns>IEnumerable{System.String}.</returns>
  1273. public IEnumerable<string> GetAllIntroFiles()
  1274. {
  1275. return IntroProviders.SelectMany(i =>
  1276. {
  1277. try
  1278. {
  1279. return i.GetAllIntroFiles().ToList();
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. _logger.ErrorException("Error getting intro files", ex);
  1284. return new List<string>();
  1285. }
  1286. });
  1287. }
  1288. /// <summary>
  1289. /// Resolves the intro.
  1290. /// </summary>
  1291. /// <param name="info">The info.</param>
  1292. /// <returns>Video.</returns>
  1293. private Video ResolveIntro(IntroInfo info)
  1294. {
  1295. Video video = null;
  1296. if (info.ItemId.HasValue)
  1297. {
  1298. // Get an existing item by Id
  1299. video = GetItemById(info.ItemId.Value) as Video;
  1300. if (video == null)
  1301. {
  1302. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1303. }
  1304. }
  1305. else if (!string.IsNullOrEmpty(info.Path))
  1306. {
  1307. try
  1308. {
  1309. // Try to resolve the path into a video
  1310. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1311. if (video == null)
  1312. {
  1313. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1314. }
  1315. else
  1316. {
  1317. // Pull the saved db item that will include metadata
  1318. var dbItem = GetItemById(video.Id) as Video;
  1319. if (dbItem != null)
  1320. {
  1321. video = dbItem;
  1322. }
  1323. else
  1324. {
  1325. return null;
  1326. }
  1327. }
  1328. }
  1329. catch (Exception ex)
  1330. {
  1331. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1332. }
  1333. }
  1334. else
  1335. {
  1336. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1337. }
  1338. return video;
  1339. }
  1340. /// <summary>
  1341. /// Sorts the specified sort by.
  1342. /// </summary>
  1343. /// <param name="items">The items.</param>
  1344. /// <param name="user">The user.</param>
  1345. /// <param name="sortBy">The sort by.</param>
  1346. /// <param name="sortOrder">The sort order.</param>
  1347. /// <returns>IEnumerable{BaseItem}.</returns>
  1348. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1349. {
  1350. var isFirst = true;
  1351. IOrderedEnumerable<BaseItem> orderedItems = null;
  1352. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1353. {
  1354. if (isFirst)
  1355. {
  1356. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1357. }
  1358. else
  1359. {
  1360. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1361. }
  1362. isFirst = false;
  1363. }
  1364. return orderedItems ?? items;
  1365. }
  1366. /// <summary>
  1367. /// Gets the comparer.
  1368. /// </summary>
  1369. /// <param name="name">The name.</param>
  1370. /// <param name="user">The user.</param>
  1371. /// <returns>IBaseItemComparer.</returns>
  1372. private IBaseItemComparer GetComparer(string name, User user)
  1373. {
  1374. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1375. if (comparer != null)
  1376. {
  1377. // If it requires a user, create a new one, and assign the user
  1378. if (comparer is IUserBaseItemComparer)
  1379. {
  1380. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1381. userComparer.User = user;
  1382. userComparer.UserManager = _userManager;
  1383. userComparer.UserDataRepository = _userDataRepository;
  1384. return userComparer;
  1385. }
  1386. }
  1387. return comparer;
  1388. }
  1389. /// <summary>
  1390. /// Creates the item.
  1391. /// </summary>
  1392. /// <param name="item">The item.</param>
  1393. /// <param name="cancellationToken">The cancellation token.</param>
  1394. /// <returns>Task.</returns>
  1395. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1396. {
  1397. return CreateItems(new[] { item }, cancellationToken);
  1398. }
  1399. /// <summary>
  1400. /// Creates the items.
  1401. /// </summary>
  1402. /// <param name="items">The items.</param>
  1403. /// <param name="cancellationToken">The cancellation token.</param>
  1404. /// <returns>Task.</returns>
  1405. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1406. {
  1407. var list = items.ToList();
  1408. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1409. foreach (var item in list)
  1410. {
  1411. UpdateItemInLibraryCache(item);
  1412. }
  1413. if (ItemAdded != null)
  1414. {
  1415. foreach (var item in list)
  1416. {
  1417. try
  1418. {
  1419. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1420. }
  1421. catch (Exception ex)
  1422. {
  1423. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1424. }
  1425. }
  1426. }
  1427. }
  1428. /// <summary>
  1429. /// Updates the item.
  1430. /// </summary>
  1431. /// <param name="item">The item.</param>
  1432. /// <param name="updateReason">The update reason.</param>
  1433. /// <param name="cancellationToken">The cancellation token.</param>
  1434. /// <returns>Task.</returns>
  1435. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1436. {
  1437. var locationType = item.LocationType;
  1438. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1439. {
  1440. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1441. }
  1442. item.DateLastSaved = DateTime.UtcNow;
  1443. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1444. _logger.Debug("Saving {0} to database.", logName);
  1445. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1446. UpdateItemInLibraryCache(item);
  1447. if (ItemUpdated != null)
  1448. {
  1449. try
  1450. {
  1451. ItemUpdated(this, new ItemChangeEventArgs
  1452. {
  1453. Item = item,
  1454. UpdateReason = updateReason
  1455. });
  1456. }
  1457. catch (Exception ex)
  1458. {
  1459. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1460. }
  1461. }
  1462. }
  1463. /// <summary>
  1464. /// Reports the item removed.
  1465. /// </summary>
  1466. /// <param name="item">The item.</param>
  1467. public void ReportItemRemoved(BaseItem item)
  1468. {
  1469. if (ItemRemoved != null)
  1470. {
  1471. try
  1472. {
  1473. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1474. }
  1475. catch (Exception ex)
  1476. {
  1477. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1478. }
  1479. }
  1480. }
  1481. /// <summary>
  1482. /// Retrieves the item.
  1483. /// </summary>
  1484. /// <param name="id">The id.</param>
  1485. /// <returns>BaseItem.</returns>
  1486. public BaseItem RetrieveItem(Guid id)
  1487. {
  1488. return ItemRepository.RetrieveItem(id);
  1489. }
  1490. public IEnumerable<Folder> GetCollectionFolders(BaseItem item)
  1491. {
  1492. while (!(item.GetParent() is AggregateFolder) && item.GetParent() != null)
  1493. {
  1494. item = item.GetParent();
  1495. }
  1496. if (item == null)
  1497. {
  1498. return new List<Folder>();
  1499. }
  1500. return GetUserRootFolder().Children
  1501. .OfType<Folder>()
  1502. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase));
  1503. }
  1504. public string GetContentType(BaseItem item)
  1505. {
  1506. string configuredContentType = GetConfiguredContentType(item, false);
  1507. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1508. {
  1509. return configuredContentType;
  1510. }
  1511. configuredContentType = GetConfiguredContentType(item, true);
  1512. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1513. {
  1514. return configuredContentType;
  1515. }
  1516. return GetInheritedContentType(item);
  1517. }
  1518. public string GetInheritedContentType(BaseItem item)
  1519. {
  1520. var type = GetTopFolderContentType(item);
  1521. if (!string.IsNullOrWhiteSpace(type))
  1522. {
  1523. return type;
  1524. }
  1525. return item.GetParents()
  1526. .Select(GetConfiguredContentType)
  1527. .LastOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1528. }
  1529. public string GetConfiguredContentType(BaseItem item)
  1530. {
  1531. return GetConfiguredContentType(item, false);
  1532. }
  1533. public string GetConfiguredContentType(string path)
  1534. {
  1535. return GetContentTypeOverride(path, false);
  1536. }
  1537. public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1538. {
  1539. ICollectionFolder collectionFolder = item as ICollectionFolder;
  1540. if (collectionFolder != null)
  1541. {
  1542. return collectionFolder.CollectionType;
  1543. }
  1544. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1545. }
  1546. private string GetContentTypeOverride(string path, bool inherit)
  1547. {
  1548. var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase) || (inherit && _fileSystem.ContainsSubPath(i.Name, path)));
  1549. if (nameValuePair != null)
  1550. {
  1551. return nameValuePair.Value;
  1552. }
  1553. return null;
  1554. }
  1555. private string GetTopFolderContentType(BaseItem item)
  1556. {
  1557. if (item == null)
  1558. {
  1559. return null;
  1560. }
  1561. while (!(item.GetParent() is AggregateFolder) && item.GetParent() != null)
  1562. {
  1563. item = item.GetParent();
  1564. }
  1565. return GetUserRootFolder().Children
  1566. .OfType<ICollectionFolder>()
  1567. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1568. .Select(i => i.CollectionType)
  1569. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1570. }
  1571. private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
  1572. //private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromMinutes(1);
  1573. public Task<UserView> GetNamedView(User user,
  1574. string name,
  1575. string viewType,
  1576. string sortName,
  1577. CancellationToken cancellationToken)
  1578. {
  1579. return GetNamedView(user, name, null, viewType, sortName, cancellationToken);
  1580. }
  1581. public async Task<UserView> GetNamedView(string name,
  1582. string viewType,
  1583. string sortName,
  1584. CancellationToken cancellationToken)
  1585. {
  1586. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath, "views");
  1587. path = Path.Combine(path, _fileSystem.GetValidFilename(viewType));
  1588. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1589. var item = GetItemById(id) as UserView;
  1590. var refresh = false;
  1591. if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1592. {
  1593. _fileSystem.CreateDirectory(path);
  1594. item = new UserView
  1595. {
  1596. Path = path,
  1597. Id = id,
  1598. DateCreated = DateTime.UtcNow,
  1599. Name = name,
  1600. ViewType = viewType,
  1601. ForcedSortName = sortName
  1602. };
  1603. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1604. refresh = true;
  1605. }
  1606. if (!refresh)
  1607. {
  1608. refresh = DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1609. }
  1610. if (!refresh && item.DisplayParentId != Guid.Empty)
  1611. {
  1612. var displayParent = GetItemById(item.DisplayParentId);
  1613. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1614. }
  1615. if (refresh)
  1616. {
  1617. await item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None).ConfigureAwait(false);
  1618. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1619. {
  1620. // Not sure why this is necessary but need to figure it out
  1621. // View images are not getting utilized without this
  1622. ForceSave = true
  1623. });
  1624. }
  1625. return item;
  1626. }
  1627. public async Task<UserView> GetNamedView(User user,
  1628. string name,
  1629. string parentId,
  1630. string viewType,
  1631. string sortName,
  1632. CancellationToken cancellationToken)
  1633. {
  1634. var idValues = "38_namedview_" + name + user.Id.ToString("N") + (parentId ?? string.Empty) + (viewType ?? string.Empty);
  1635. var id = GetNewItemId(idValues, typeof(UserView));
  1636. var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
  1637. var item = GetItemById(id) as UserView;
  1638. var isNew = false;
  1639. if (item == null)
  1640. {
  1641. _fileSystem.CreateDirectory(path);
  1642. item = new UserView
  1643. {
  1644. Path = path,
  1645. Id = id,
  1646. DateCreated = DateTime.UtcNow,
  1647. Name = name,
  1648. ViewType = viewType,
  1649. ForcedSortName = sortName,
  1650. UserId = user.Id
  1651. };
  1652. if (!string.IsNullOrWhiteSpace(parentId))
  1653. {
  1654. item.DisplayParentId = new Guid(parentId);
  1655. }
  1656. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1657. isNew = true;
  1658. }
  1659. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1660. if (!refresh && item.DisplayParentId != Guid.Empty)
  1661. {
  1662. var displayParent = GetItemById(item.DisplayParentId);
  1663. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1664. }
  1665. if (refresh)
  1666. {
  1667. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1668. {
  1669. // Need to force save to increment DateLastSaved
  1670. ForceSave = true
  1671. });
  1672. }
  1673. return item;
  1674. }
  1675. public async Task<UserView> GetShadowView(BaseItem parent,
  1676. string viewType,
  1677. string sortName,
  1678. CancellationToken cancellationToken)
  1679. {
  1680. if (parent == null)
  1681. {
  1682. throw new ArgumentNullException("parent");
  1683. }
  1684. var name = parent.Name;
  1685. var parentId = parent.Id;
  1686. var idValues = "38_namedview_" + name + parentId + (viewType ?? string.Empty);
  1687. var id = GetNewItemId(idValues, typeof(UserView));
  1688. var path = parent.Path;
  1689. var item = GetItemById(id) as UserView;
  1690. var isNew = false;
  1691. if (item == null)
  1692. {
  1693. _fileSystem.CreateDirectory(path);
  1694. item = new UserView
  1695. {
  1696. Path = path,
  1697. Id = id,
  1698. DateCreated = DateTime.UtcNow,
  1699. Name = name,
  1700. ViewType = viewType,
  1701. ForcedSortName = sortName
  1702. };
  1703. item.DisplayParentId = parentId;
  1704. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1705. isNew = true;
  1706. }
  1707. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1708. if (!refresh && item.DisplayParentId != Guid.Empty)
  1709. {
  1710. var displayParent = GetItemById(item.DisplayParentId);
  1711. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1712. }
  1713. if (refresh)
  1714. {
  1715. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1716. {
  1717. // Need to force save to increment DateLastSaved
  1718. ForceSave = true
  1719. });
  1720. }
  1721. return item;
  1722. }
  1723. public async Task<UserView> GetNamedView(string name,
  1724. string parentId,
  1725. string viewType,
  1726. string sortName,
  1727. string uniqueId,
  1728. CancellationToken cancellationToken)
  1729. {
  1730. if (string.IsNullOrWhiteSpace(name))
  1731. {
  1732. throw new ArgumentNullException("name");
  1733. }
  1734. var idValues = "37_namedview_" + name + (parentId ?? string.Empty) + (viewType ?? string.Empty);
  1735. if (!string.IsNullOrWhiteSpace(uniqueId))
  1736. {
  1737. idValues += uniqueId;
  1738. }
  1739. var id = GetNewItemId(idValues, typeof(UserView));
  1740. var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
  1741. var item = GetItemById(id) as UserView;
  1742. var isNew = false;
  1743. if (item == null)
  1744. {
  1745. _fileSystem.CreateDirectory(path);
  1746. item = new UserView
  1747. {
  1748. Path = path,
  1749. Id = id,
  1750. DateCreated = DateTime.UtcNow,
  1751. Name = name,
  1752. ViewType = viewType,
  1753. ForcedSortName = sortName
  1754. };
  1755. if (!string.IsNullOrWhiteSpace(parentId))
  1756. {
  1757. item.DisplayParentId = new Guid(parentId);
  1758. }
  1759. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1760. isNew = true;
  1761. }
  1762. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1763. {
  1764. item.ViewType = viewType;
  1765. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1766. }
  1767. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1768. if (!refresh && item.DisplayParentId != Guid.Empty)
  1769. {
  1770. var displayParent = GetItemById(item.DisplayParentId);
  1771. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1772. }
  1773. if (refresh)
  1774. {
  1775. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1776. {
  1777. // Need to force save to increment DateLastSaved
  1778. ForceSave = true
  1779. });
  1780. }
  1781. return item;
  1782. }
  1783. public bool IsVideoFile(string path)
  1784. {
  1785. var resolver = new VideoResolver(GetNamingOptions(), new PatternsLogger());
  1786. return resolver.IsVideoFile(path);
  1787. }
  1788. public bool IsAudioFile(string path)
  1789. {
  1790. var parser = new AudioFileParser(GetNamingOptions());
  1791. return parser.IsAudioFile(path);
  1792. }
  1793. public int? GetSeasonNumberFromPath(string path)
  1794. {
  1795. return new SeasonPathParser(GetNamingOptions(), new RegexProvider()).Parse(path, true, true).SeasonNumber;
  1796. }
  1797. public bool FillMissingEpisodeNumbersFromPath(Episode episode)
  1798. {
  1799. var resolver = new EpisodeResolver(GetNamingOptions(),
  1800. new PatternsLogger());
  1801. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd ||
  1802. episode.VideoType == VideoType.HdDvd;
  1803. var locationType = episode.LocationType;
  1804. var episodeInfo = locationType == LocationType.FileSystem || locationType == LocationType.Offline ?
  1805. resolver.Resolve(episode.Path, isFolder) :
  1806. new Naming.TV.EpisodeInfo();
  1807. if (episodeInfo == null)
  1808. {
  1809. episodeInfo = new Naming.TV.EpisodeInfo();
  1810. }
  1811. var changed = false;
  1812. if (episodeInfo.IsByDate)
  1813. {
  1814. if (episode.IndexNumber.HasValue)
  1815. {
  1816. episode.IndexNumber = null;
  1817. changed = true;
  1818. }
  1819. if (episode.IndexNumberEnd.HasValue)
  1820. {
  1821. episode.IndexNumberEnd = null;
  1822. changed = true;
  1823. }
  1824. if (!episode.PremiereDate.HasValue)
  1825. {
  1826. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  1827. {
  1828. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  1829. }
  1830. if (episode.PremiereDate.HasValue)
  1831. {
  1832. changed = true;
  1833. }
  1834. }
  1835. if (!episode.ProductionYear.HasValue)
  1836. {
  1837. episode.ProductionYear = episodeInfo.Year;
  1838. if (episode.ProductionYear.HasValue)
  1839. {
  1840. changed = true;
  1841. }
  1842. }
  1843. if (!episode.ParentIndexNumber.HasValue)
  1844. {
  1845. var season = episode.Season;
  1846. if (season != null)
  1847. {
  1848. episode.ParentIndexNumber = season.IndexNumber;
  1849. }
  1850. if (episode.ParentIndexNumber.HasValue)
  1851. {
  1852. changed = true;
  1853. }
  1854. }
  1855. }
  1856. else
  1857. {
  1858. if (!episode.IndexNumber.HasValue)
  1859. {
  1860. episode.IndexNumber = episodeInfo.EpisodeNumber;
  1861. if (episode.IndexNumber.HasValue)
  1862. {
  1863. changed = true;
  1864. }
  1865. }
  1866. if (!episode.IndexNumberEnd.HasValue)
  1867. {
  1868. episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
  1869. if (episode.IndexNumberEnd.HasValue)
  1870. {
  1871. changed = true;
  1872. }
  1873. }
  1874. if (!episode.ParentIndexNumber.HasValue)
  1875. {
  1876. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  1877. if (!episode.ParentIndexNumber.HasValue)
  1878. {
  1879. var season = episode.Season;
  1880. if (season != null)
  1881. {
  1882. episode.ParentIndexNumber = season.IndexNumber;
  1883. }
  1884. }
  1885. if (episode.ParentIndexNumber.HasValue)
  1886. {
  1887. changed = true;
  1888. }
  1889. }
  1890. }
  1891. return changed;
  1892. }
  1893. public NamingOptions GetNamingOptions()
  1894. {
  1895. var options = new ExtendedNamingOptions();
  1896. // These cause apps to have problems
  1897. options.AudioFileExtensions.Remove(".m3u");
  1898. options.AudioFileExtensions.Remove(".wpl");
  1899. if (!ConfigurationManager.Configuration.EnableAudioArchiveFiles)
  1900. {
  1901. options.AudioFileExtensions.Remove(".rar");
  1902. options.AudioFileExtensions.Remove(".zip");
  1903. }
  1904. if (!ConfigurationManager.Configuration.EnableVideoArchiveFiles)
  1905. {
  1906. options.VideoFileExtensions.Remove(".rar");
  1907. options.VideoFileExtensions.Remove(".zip");
  1908. }
  1909. return options;
  1910. }
  1911. public ItemLookupInfo ParseName(string name)
  1912. {
  1913. var resolver = new VideoResolver(GetNamingOptions(), new PatternsLogger());
  1914. var result = resolver.CleanDateTime(name);
  1915. var cleanName = resolver.CleanString(result.Name);
  1916. return new ItemLookupInfo
  1917. {
  1918. Name = cleanName.Name,
  1919. Year = result.Year
  1920. };
  1921. }
  1922. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1923. {
  1924. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1925. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  1926. .SelectMany(i => _fileSystem.GetFiles(i.FullName, false))
  1927. .ToList();
  1928. var videoListResolver = new VideoListResolver(GetNamingOptions(), new PatternsLogger());
  1929. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new FileMetadata
  1930. {
  1931. Id = i.FullName,
  1932. IsFolder = (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory
  1933. }).ToList());
  1934. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1935. if (currentVideo != null)
  1936. {
  1937. files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
  1938. }
  1939. var resolvers = new IItemResolver[]
  1940. {
  1941. new GenericVideoResolver<Trailer>(this)
  1942. };
  1943. return ResolvePaths(files, directoryService, null, null, resolvers)
  1944. .OfType<Trailer>()
  1945. .Select(video =>
  1946. {
  1947. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1948. var dbItem = GetItemById(video.Id) as Trailer;
  1949. if (dbItem != null)
  1950. {
  1951. video = dbItem;
  1952. }
  1953. video.ExtraType = ExtraType.Trailer;
  1954. video.TrailerTypes = new List<TrailerType> { TrailerType.LocalTrailer };
  1955. return video;
  1956. // Sort them so that the list can be easily compared for changes
  1957. }).OrderBy(i => i.Path).ToList();
  1958. }
  1959. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1960. {
  1961. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1962. .Where(i => string.Equals(i.Name, "extras", StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, "specials", StringComparison.OrdinalIgnoreCase))
  1963. .SelectMany(i => _fileSystem.GetFiles(i.FullName, false))
  1964. .ToList();
  1965. var videoListResolver = new VideoListResolver(GetNamingOptions(), new PatternsLogger());
  1966. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new FileMetadata
  1967. {
  1968. Id = i.FullName,
  1969. IsFolder = (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory
  1970. }).ToList());
  1971. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1972. if (currentVideo != null)
  1973. {
  1974. files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
  1975. }
  1976. return ResolvePaths(files, directoryService, null, null)
  1977. .OfType<Video>()
  1978. .Select(video =>
  1979. {
  1980. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1981. var dbItem = GetItemById(video.Id) as Video;
  1982. if (dbItem != null)
  1983. {
  1984. video = dbItem;
  1985. }
  1986. SetExtraTypeFromFilename(video);
  1987. return video;
  1988. // Sort them so that the list can be easily compared for changes
  1989. }).OrderBy(i => i.Path).ToList();
  1990. }
  1991. public string SubstitutePath(string path, string from, string to)
  1992. {
  1993. if (string.IsNullOrWhiteSpace(path))
  1994. {
  1995. throw new ArgumentNullException("path");
  1996. }
  1997. if (string.IsNullOrWhiteSpace(from))
  1998. {
  1999. throw new ArgumentNullException("from");
  2000. }
  2001. if (string.IsNullOrWhiteSpace(to))
  2002. {
  2003. throw new ArgumentNullException("to");
  2004. }
  2005. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  2006. if (!string.Equals(newPath, path))
  2007. {
  2008. if (to.IndexOf('/') != -1)
  2009. {
  2010. newPath = newPath.Replace('\\', '/');
  2011. }
  2012. else
  2013. {
  2014. newPath = newPath.Replace('/', '\\');
  2015. }
  2016. }
  2017. return newPath;
  2018. }
  2019. private void SetExtraTypeFromFilename(Video item)
  2020. {
  2021. var resolver = new ExtraResolver(GetNamingOptions(), new PatternsLogger(), new RegexProvider());
  2022. var result = resolver.GetExtraInfo(item.Path);
  2023. if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase))
  2024. {
  2025. item.ExtraType = ExtraType.DeletedScene;
  2026. }
  2027. else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase))
  2028. {
  2029. item.ExtraType = ExtraType.BehindTheScenes;
  2030. }
  2031. else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase))
  2032. {
  2033. item.ExtraType = ExtraType.Interview;
  2034. }
  2035. else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase))
  2036. {
  2037. item.ExtraType = ExtraType.Scene;
  2038. }
  2039. else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase))
  2040. {
  2041. item.ExtraType = ExtraType.Sample;
  2042. }
  2043. else
  2044. {
  2045. item.ExtraType = ExtraType.Clip;
  2046. }
  2047. }
  2048. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  2049. {
  2050. return ItemRepository.GetPeople(query);
  2051. }
  2052. public List<PersonInfo> GetPeople(BaseItem item)
  2053. {
  2054. if (item.SupportsPeople)
  2055. {
  2056. var people = GetPeople(new InternalPeopleQuery
  2057. {
  2058. ItemId = item.Id
  2059. });
  2060. if (people.Count > 0)
  2061. {
  2062. return people;
  2063. }
  2064. }
  2065. return new List<PersonInfo>();
  2066. }
  2067. public List<Person> GetPeopleItems(InternalPeopleQuery query)
  2068. {
  2069. return ItemRepository.GetPeopleNames(query).Select(i =>
  2070. {
  2071. try
  2072. {
  2073. return GetPerson(i);
  2074. }
  2075. catch (Exception ex)
  2076. {
  2077. _logger.ErrorException("Error getting person", ex);
  2078. return null;
  2079. }
  2080. }).Where(i => i != null).ToList();
  2081. }
  2082. public List<string> GetPeopleNames(InternalPeopleQuery query)
  2083. {
  2084. return ItemRepository.GetPeopleNames(query);
  2085. }
  2086. public List<PersonInfo> GetAllPeople()
  2087. {
  2088. return GetPeople(new InternalPeopleQuery())
  2089. .DistinctBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  2090. .ToList();
  2091. }
  2092. public Task UpdatePeople(BaseItem item, List<PersonInfo> people)
  2093. {
  2094. if (!item.SupportsPeople)
  2095. {
  2096. return Task.FromResult(true);
  2097. }
  2098. return ItemRepository.UpdatePeople(item.Id, people);
  2099. }
  2100. private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1, 1);
  2101. public async Task<ItemImageInfo> ConvertImageToLocal(IHasImages item, ItemImageInfo image, int imageIndex)
  2102. {
  2103. foreach (var url in image.Path.Split('|'))
  2104. {
  2105. try
  2106. {
  2107. _logger.Debug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2108. await _providerManagerFactory().SaveImage(item, url, _dynamicImageResourcePool, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2109. var newImage = item.GetImageInfo(image.Type, imageIndex);
  2110. if (newImage != null)
  2111. {
  2112. newImage.IsPlaceholder = image.IsPlaceholder;
  2113. }
  2114. await item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2115. return item.GetImageInfo(image.Type, imageIndex);
  2116. }
  2117. catch (HttpException ex)
  2118. {
  2119. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  2120. {
  2121. continue;
  2122. }
  2123. throw;
  2124. }
  2125. }
  2126. // Remove this image to prevent it from retrying over and over
  2127. item.RemoveImage(image);
  2128. await item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2129. throw new InvalidOperationException();
  2130. }
  2131. public void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, bool refreshLibrary)
  2132. {
  2133. if (string.IsNullOrWhiteSpace(name))
  2134. {
  2135. throw new ArgumentNullException("name");
  2136. }
  2137. name = _fileSystem.GetValidFilename(name);
  2138. var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  2139. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2140. while (_fileSystem.DirectoryExists(virtualFolderPath))
  2141. {
  2142. name += "1";
  2143. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2144. }
  2145. if (mediaPaths != null)
  2146. {
  2147. var invalidpath = mediaPaths.FirstOrDefault(i => !_fileSystem.DirectoryExists(i));
  2148. if (invalidpath != null)
  2149. {
  2150. throw new ArgumentException("The specified path does not exist: " + invalidpath + ".");
  2151. }
  2152. }
  2153. _libraryMonitorFactory().Stop();
  2154. try
  2155. {
  2156. _fileSystem.CreateDirectory(virtualFolderPath);
  2157. if (!string.IsNullOrEmpty(collectionType))
  2158. {
  2159. var path = Path.Combine(virtualFolderPath, collectionType + ".collection");
  2160. using (File.Create(path))
  2161. {
  2162. }
  2163. }
  2164. if (mediaPaths != null)
  2165. {
  2166. foreach (var path in mediaPaths)
  2167. {
  2168. AddMediaPath(name, path);
  2169. }
  2170. }
  2171. }
  2172. finally
  2173. {
  2174. Task.Run(() =>
  2175. {
  2176. // No need to start if scanning the library because it will handle it
  2177. if (refreshLibrary)
  2178. {
  2179. ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  2180. }
  2181. else
  2182. {
  2183. // Need to add a delay here or directory watchers may still pick up the changes
  2184. var task = Task.Delay(1000);
  2185. // Have to block here to allow exceptions to bubble
  2186. Task.WaitAll(task);
  2187. _libraryMonitorFactory().Start();
  2188. }
  2189. });
  2190. }
  2191. }
  2192. public void RemoveVirtualFolder(string name, bool refreshLibrary)
  2193. {
  2194. if (string.IsNullOrWhiteSpace(name))
  2195. {
  2196. throw new ArgumentNullException("name");
  2197. }
  2198. var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  2199. var path = Path.Combine(rootFolderPath, name);
  2200. if (!_fileSystem.DirectoryExists(path))
  2201. {
  2202. throw new DirectoryNotFoundException("The media folder does not exist");
  2203. }
  2204. _libraryMonitorFactory().Stop();
  2205. try
  2206. {
  2207. _fileSystem.DeleteDirectory(path, true);
  2208. }
  2209. finally
  2210. {
  2211. Task.Run(() =>
  2212. {
  2213. // No need to start if scanning the library because it will handle it
  2214. if (refreshLibrary)
  2215. {
  2216. ValidateMediaLibrary(new Progress<double>(), CancellationToken.None);
  2217. }
  2218. else
  2219. {
  2220. // Need to add a delay here or directory watchers may still pick up the changes
  2221. var task = Task.Delay(1000);
  2222. // Have to block here to allow exceptions to bubble
  2223. Task.WaitAll(task);
  2224. _libraryMonitorFactory().Start();
  2225. }
  2226. });
  2227. }
  2228. }
  2229. private const string ShortcutFileExtension = ".mblink";
  2230. private const string ShortcutFileSearch = "*" + ShortcutFileExtension;
  2231. public void AddMediaPath(string virtualFolderName, string path)
  2232. {
  2233. if (string.IsNullOrWhiteSpace(path))
  2234. {
  2235. throw new ArgumentNullException("path");
  2236. }
  2237. if (!_fileSystem.DirectoryExists(path))
  2238. {
  2239. throw new DirectoryNotFoundException("The path does not exist.");
  2240. }
  2241. var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  2242. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2243. var shortcutFilename = _fileSystem.GetFileNameWithoutExtension(path);
  2244. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2245. while (_fileSystem.FileExists(lnk))
  2246. {
  2247. shortcutFilename += "1";
  2248. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2249. }
  2250. _fileSystem.CreateShortcut(lnk, path);
  2251. }
  2252. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2253. {
  2254. if (string.IsNullOrWhiteSpace(mediaPath))
  2255. {
  2256. throw new ArgumentNullException("mediaPath");
  2257. }
  2258. var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath;
  2259. var path = Path.Combine(rootFolderPath, virtualFolderName);
  2260. if (!_fileSystem.DirectoryExists(path))
  2261. {
  2262. throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
  2263. }
  2264. var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => _fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2265. if (!string.IsNullOrEmpty(shortcut))
  2266. {
  2267. _fileSystem.DeleteFile(shortcut);
  2268. }
  2269. }
  2270. }
  2271. }