LibraryManager.cs 82 KB

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