LibraryManager.cs 84 KB

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