LibraryManager.cs 84 KB

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