LibraryManager.cs 87 KB

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