LibraryManager.cs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428
  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.Net;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. using CommonIO;
  39. using MediaBrowser.Model.Extensions;
  40. using MediaBrowser.Model.Net;
  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. /// <summary>
  129. /// The _library items cache
  130. /// </summary>
  131. private readonly ConcurrentDictionary<Guid, BaseItem> _libraryItemsCache;
  132. /// <summary>
  133. /// Gets the library items cache.
  134. /// </summary>
  135. /// <value>The library items cache.</value>
  136. private ConcurrentDictionary<Guid, BaseItem> LibraryItemsCache
  137. {
  138. get
  139. {
  140. return _libraryItemsCache;
  141. }
  142. }
  143. private readonly IFileSystem _fileSystem;
  144. /// <summary>
  145. /// Initializes a new instance of the <see cref="LibraryManager" /> class.
  146. /// </summary>
  147. /// <param name="logger">The logger.</param>
  148. /// <param name="taskManager">The task manager.</param>
  149. /// <param name="userManager">The user manager.</param>
  150. /// <param name="configurationManager">The configuration manager.</param>
  151. /// <param name="userDataRepository">The user data repository.</param>
  152. public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func<ILibraryMonitor> libraryMonitorFactory, IFileSystem fileSystem, Func<IProviderManager> providerManagerFactory)
  153. {
  154. _logger = logger;
  155. _taskManager = taskManager;
  156. _userManager = userManager;
  157. ConfigurationManager = configurationManager;
  158. _userDataRepository = userDataRepository;
  159. _libraryMonitorFactory = libraryMonitorFactory;
  160. _fileSystem = fileSystem;
  161. _providerManagerFactory = providerManagerFactory;
  162. ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>();
  163. _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>();
  164. ConfigurationManager.ConfigurationUpdated += ConfigurationUpdated;
  165. RecordConfigurationValues(configurationManager.Configuration);
  166. }
  167. /// <summary>
  168. /// Adds the parts.
  169. /// </summary>
  170. /// <param name="rules">The rules.</param>
  171. /// <param name="pluginFolders">The plugin folders.</param>
  172. /// <param name="resolvers">The resolvers.</param>
  173. /// <param name="introProviders">The intro providers.</param>
  174. /// <param name="itemComparers">The item comparers.</param>
  175. /// <param name="postscanTasks">The postscan tasks.</param>
  176. public void AddParts(IEnumerable<IResolverIgnoreRule> rules,
  177. IEnumerable<IVirtualFolderCreator> pluginFolders,
  178. IEnumerable<IItemResolver> resolvers,
  179. IEnumerable<IIntroProvider> introProviders,
  180. IEnumerable<IBaseItemComparer> itemComparers,
  181. IEnumerable<ILibraryPostScanTask> postscanTasks)
  182. {
  183. EntityResolutionIgnoreRules = rules.ToArray();
  184. PluginFolderCreators = pluginFolders.ToArray();
  185. EntityResolvers = resolvers.OrderBy(i => i.Priority).ToArray();
  186. MultiItemResolvers = EntityResolvers.OfType<IMultiItemResolver>().ToArray();
  187. IntroProviders = introProviders.ToArray();
  188. Comparers = itemComparers.ToArray();
  189. PostscanTasks = postscanTasks.OrderBy(i =>
  190. {
  191. var hasOrder = i as IHasOrder;
  192. return hasOrder == null ? 0 : hasOrder.Order;
  193. }).ToArray();
  194. }
  195. /// <summary>
  196. /// The _root folder
  197. /// </summary>
  198. private volatile AggregateFolder _rootFolder;
  199. /// <summary>
  200. /// The _root folder sync lock
  201. /// </summary>
  202. private readonly object _rootFolderSyncLock = new object();
  203. /// <summary>
  204. /// Gets the root folder.
  205. /// </summary>
  206. /// <value>The root folder.</value>
  207. public AggregateFolder RootFolder
  208. {
  209. get
  210. {
  211. if (_rootFolder == null)
  212. {
  213. lock (_rootFolderSyncLock)
  214. {
  215. if (_rootFolder == null)
  216. {
  217. _rootFolder = CreateRootFolder();
  218. }
  219. }
  220. }
  221. return _rootFolder;
  222. }
  223. }
  224. /// <summary>
  225. /// The _season zero display name
  226. /// </summary>
  227. private string _seasonZeroDisplayName;
  228. private bool _wizardCompleted;
  229. /// <summary>
  230. /// Records the configuration values.
  231. /// </summary>
  232. /// <param name="configuration">The configuration.</param>
  233. private void RecordConfigurationValues(ServerConfiguration configuration)
  234. {
  235. _seasonZeroDisplayName = configuration.SeasonZeroDisplayName;
  236. _wizardCompleted = configuration.IsStartupWizardCompleted;
  237. }
  238. /// <summary>
  239. /// Configurations the updated.
  240. /// </summary>
  241. /// <param name="sender">The sender.</param>
  242. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  243. void ConfigurationUpdated(object sender, EventArgs e)
  244. {
  245. var config = ConfigurationManager.Configuration;
  246. var newSeasonZeroName = ConfigurationManager.Configuration.SeasonZeroDisplayName;
  247. var seasonZeroNameChanged = !string.Equals(_seasonZeroDisplayName, newSeasonZeroName, StringComparison.Ordinal);
  248. var wizardChanged = config.IsStartupWizardCompleted != _wizardCompleted;
  249. RecordConfigurationValues(config);
  250. if (seasonZeroNameChanged || wizardChanged)
  251. {
  252. _taskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  253. }
  254. if (seasonZeroNameChanged)
  255. {
  256. Task.Run(async () =>
  257. {
  258. await UpdateSeasonZeroNames(newSeasonZeroName, CancellationToken.None).ConfigureAwait(false);
  259. });
  260. }
  261. }
  262. /// <summary>
  263. /// Updates the season zero names.
  264. /// </summary>
  265. /// <param name="newName">The new name.</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. /// <returns>Task.</returns>
  268. private async Task UpdateSeasonZeroNames(string newName, CancellationToken cancellationToken)
  269. {
  270. var seasons = RootFolder.GetRecursiveChildren(i => i is Season)
  271. .Cast<Season>()
  272. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == 0 && !string.Equals(i.Name, newName, StringComparison.Ordinal))
  273. .ToList();
  274. foreach (var season in seasons)
  275. {
  276. season.Name = newName;
  277. try
  278. {
  279. await UpdateItem(season, ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  280. }
  281. catch (Exception ex)
  282. {
  283. _logger.ErrorException("Error saving {0}", ex, season.Path);
  284. }
  285. }
  286. }
  287. /// <summary>
  288. /// Updates the item in library cache.
  289. /// </summary>
  290. /// <param name="item">The item.</param>
  291. private void UpdateItemInLibraryCache(BaseItem item)
  292. {
  293. RegisterItem(item);
  294. }
  295. public void RegisterItem(BaseItem item)
  296. {
  297. if (item == null)
  298. {
  299. throw new ArgumentNullException("item");
  300. }
  301. RegisterItem(item.Id, item);
  302. }
  303. private void RegisterItem(Guid id, BaseItem item)
  304. {
  305. if (item is LiveTvProgram)
  306. {
  307. return;
  308. }
  309. if (item is IChannelItem)
  310. {
  311. return;
  312. }
  313. if (item is IItemByName)
  314. {
  315. if (!(item is MusicArtist))
  316. {
  317. return;
  318. }
  319. }
  320. //if (!(item is Folder))
  321. //{
  322. // return;
  323. //}
  324. LibraryItemsCache.AddOrUpdate(id, item, delegate { return item; });
  325. }
  326. public async Task DeleteItem(BaseItem item, DeleteOptions options)
  327. {
  328. _logger.Debug("Deleting item, Type: {0}, Name: {1}, Path: {2}, Id: {3}",
  329. item.GetType().Name,
  330. item.Name,
  331. item.Path ?? string.Empty,
  332. item.Id);
  333. var parent = item.Parent;
  334. var locationType = item.LocationType;
  335. var children = item.IsFolder
  336. ? ((Folder)item).GetRecursiveChildren().ToList()
  337. : new List<BaseItem>();
  338. foreach (var metadataPath in GetMetadataPaths(item, children))
  339. {
  340. _logger.Debug("Deleting path {0}", metadataPath);
  341. try
  342. {
  343. _fileSystem.DeleteDirectory(metadataPath, true);
  344. }
  345. catch (DirectoryNotFoundException)
  346. {
  347. }
  348. catch (Exception ex)
  349. {
  350. _logger.ErrorException("Error deleting {0}", ex, metadataPath);
  351. }
  352. }
  353. if (options.DeleteFileLocation && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  354. {
  355. foreach (var path in item.GetDeletePaths().ToList())
  356. {
  357. if (_fileSystem.DirectoryExists(path))
  358. {
  359. _logger.Debug("Deleting path {0}", path);
  360. _fileSystem.DeleteDirectory(path, true);
  361. }
  362. else if (_fileSystem.FileExists(path))
  363. {
  364. _logger.Debug("Deleting path {0}", path);
  365. _fileSystem.DeleteFile(path);
  366. }
  367. }
  368. if (parent != null)
  369. {
  370. await parent.ValidateChildren(new Progress<double>(), CancellationToken.None)
  371. .ConfigureAwait(false);
  372. }
  373. }
  374. else if (parent != null)
  375. {
  376. await parent.RemoveChild(item, CancellationToken.None).ConfigureAwait(false);
  377. }
  378. await ItemRepository.DeleteItem(item.Id, CancellationToken.None).ConfigureAwait(false);
  379. foreach (var child in children)
  380. {
  381. await ItemRepository.DeleteItem(child.Id, CancellationToken.None).ConfigureAwait(false);
  382. }
  383. BaseItem removed;
  384. _libraryItemsCache.TryRemove(item.Id, out removed);
  385. ReportItemRemoved(item);
  386. }
  387. private IEnumerable<string> GetMetadataPaths(BaseItem item, IEnumerable<BaseItem> children)
  388. {
  389. var list = new List<string>
  390. {
  391. item.GetInternalMetadataPath()
  392. };
  393. list.AddRange(children.Select(i => i.GetInternalMetadataPath()));
  394. return list;
  395. }
  396. /// <summary>
  397. /// Resolves the item.
  398. /// </summary>
  399. /// <param name="args">The args.</param>
  400. /// <returns>BaseItem.</returns>
  401. private BaseItem ResolveItem(ItemResolveArgs args)
  402. {
  403. var item = EntityResolvers.Select(r => Resolve(args, r))
  404. .FirstOrDefault(i => i != null);
  405. if (item != null)
  406. {
  407. ResolverHelper.SetInitialItemValues(item, args, _fileSystem, this);
  408. }
  409. return item;
  410. }
  411. private BaseItem Resolve(ItemResolveArgs args, IItemResolver resolver)
  412. {
  413. try
  414. {
  415. return resolver.ResolvePath(args);
  416. }
  417. catch (Exception ex)
  418. {
  419. _logger.ErrorException("Error in {0} resolving {1}", ex, resolver.GetType().Name, args.Path);
  420. return null;
  421. }
  422. }
  423. public Guid GetNewItemId(string key, Type type)
  424. {
  425. if (string.IsNullOrWhiteSpace(key))
  426. {
  427. throw new ArgumentNullException("key");
  428. }
  429. if (type == null)
  430. {
  431. throw new ArgumentNullException("type");
  432. }
  433. if (ConfigurationManager.Configuration.EnableLocalizedGuids && key.StartsWith(ConfigurationManager.ApplicationPaths.ProgramDataPath))
  434. {
  435. // Try to normalize paths located underneath program-data in an attempt to make them more portable
  436. key = key.Substring(ConfigurationManager.ApplicationPaths.ProgramDataPath.Length)
  437. .TrimStart(new[] { '/', '\\' })
  438. .Replace("/", "\\");
  439. }
  440. key = type.FullName + key.ToLower();
  441. return key.GetMD5();
  442. }
  443. public IEnumerable<BaseItem> ReplaceVideosWithPrimaryVersions(IEnumerable<BaseItem> items)
  444. {
  445. if (items == null)
  446. {
  447. throw new ArgumentNullException("items");
  448. }
  449. var dict = new Dictionary<Guid, BaseItem>();
  450. foreach (var item in items)
  451. {
  452. var video = item as Video;
  453. if (video != null)
  454. {
  455. if (video.PrimaryVersionId.HasValue)
  456. {
  457. var primary = GetItemById(video.PrimaryVersionId.Value) as Video;
  458. if (primary != null)
  459. {
  460. dict[primary.Id] = primary;
  461. continue;
  462. }
  463. }
  464. }
  465. dict[item.Id] = item;
  466. }
  467. return dict.Values;
  468. }
  469. /// <summary>
  470. /// Ensure supplied item has only one instance throughout
  471. /// </summary>
  472. /// <param name="item">The item.</param>
  473. /// <returns>The proper instance to the item</returns>
  474. public BaseItem GetOrAddByReferenceItem(BaseItem item)
  475. {
  476. // Add this item to our list if not there already
  477. if (!ByReferenceItems.TryAdd(item.Id, item))
  478. {
  479. // Already there - return the existing reference
  480. item = ByReferenceItems[item.Id];
  481. }
  482. return item;
  483. }
  484. public BaseItem ResolvePath(FileSystemMetadata fileInfo,
  485. Folder parent = null)
  486. {
  487. return ResolvePath(fileInfo, new DirectoryService(_logger, _fileSystem), parent);
  488. }
  489. private BaseItem ResolvePath(FileSystemMetadata fileInfo, IDirectoryService directoryService, Folder parent = null, string collectionType = null)
  490. {
  491. if (fileInfo == null)
  492. {
  493. throw new ArgumentNullException("fileInfo");
  494. }
  495. var fullPath = fileInfo.FullName;
  496. if (string.IsNullOrWhiteSpace(collectionType) && parent != null)
  497. {
  498. collectionType = GetContentTypeOverride(fullPath, true);
  499. }
  500. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, directoryService)
  501. {
  502. Parent = parent,
  503. Path = fullPath,
  504. FileInfo = fileInfo,
  505. CollectionType = collectionType
  506. };
  507. // Return null if ignore rules deem that we should do so
  508. if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args)))
  509. {
  510. return null;
  511. }
  512. // Gather child folder and files
  513. if (args.IsDirectory)
  514. {
  515. var isPhysicalRoot = args.IsPhysicalRoot;
  516. // When resolving the root, we need it's grandchildren (children of user views)
  517. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  518. var fileSystemDictionary = FileData.GetFilteredFileSystemEntries(directoryService, args.Path, _fileSystem, _logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  519. // Need to remove subpaths that may have been resolved from shortcuts
  520. // Example: if \\server\movies exists, then strip out \\server\movies\action
  521. if (isPhysicalRoot)
  522. {
  523. var paths = NormalizeRootPathList(fileSystemDictionary.Values);
  524. fileSystemDictionary = paths.ToDictionary(i => i.FullName);
  525. }
  526. args.FileSystemDictionary = fileSystemDictionary;
  527. }
  528. // Check to see if we should resolve based on our contents
  529. if (args.IsDirectory && !ShouldResolvePathContents(args))
  530. {
  531. return null;
  532. }
  533. return ResolveItem(args);
  534. }
  535. public IEnumerable<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths)
  536. {
  537. var originalList = paths.ToList();
  538. var list = originalList.Where(i => i.IsDirectory)
  539. .Select(i => _fileSystem.NormalizePath(i.FullName))
  540. .Distinct(StringComparer.OrdinalIgnoreCase)
  541. .ToList();
  542. var dupes = list.Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && list.Any(i => _fileSystem.ContainsSubPath(i, subPath)))
  543. .ToList();
  544. foreach (var dupe in dupes)
  545. {
  546. _logger.Info("Found duplicate path: {0}", dupe);
  547. }
  548. var newList = list.Except(dupes, StringComparer.OrdinalIgnoreCase).Select(_fileSystem.GetDirectoryInfo).ToList();
  549. newList.AddRange(originalList.Where(i => !i.IsDirectory));
  550. return newList;
  551. }
  552. /// <summary>
  553. /// Determines whether a path should be ignored based on its contents - called after the contents have been read
  554. /// </summary>
  555. /// <param name="args">The args.</param>
  556. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  557. private static bool ShouldResolvePathContents(ItemResolveArgs args)
  558. {
  559. // Ignore any folders containing a file called .ignore
  560. return !args.ContainsFileSystemEntryByName(".ignore");
  561. }
  562. public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryService, Folder parent, string collectionType)
  563. {
  564. var fileList = files.ToList();
  565. if (parent != null)
  566. {
  567. foreach (var resolver in MultiItemResolvers)
  568. {
  569. var result = resolver.ResolveMultiple(parent, fileList, collectionType, directoryService);
  570. if (result != null && result.Items.Count > 0)
  571. {
  572. var items = new List<BaseItem>();
  573. items.AddRange(result.Items);
  574. foreach (var item in items)
  575. {
  576. ResolverHelper.SetInitialItemValues(item, parent, _fileSystem, this, directoryService);
  577. }
  578. items.AddRange(ResolveFileList(result.ExtraFiles, directoryService, parent, collectionType));
  579. return items;
  580. }
  581. }
  582. }
  583. return ResolveFileList(fileList, directoryService, parent, collectionType);
  584. }
  585. private IEnumerable<BaseItem> ResolveFileList(IEnumerable<FileSystemMetadata> fileList, IDirectoryService directoryService, Folder parent, string collectionType)
  586. {
  587. return fileList.Select(f =>
  588. {
  589. try
  590. {
  591. return ResolvePath(f, directoryService, parent, collectionType);
  592. }
  593. catch (Exception ex)
  594. {
  595. _logger.ErrorException("Error resolving path {0}", ex, f.FullName);
  596. return null;
  597. }
  598. }).Where(i => i != null);
  599. }
  600. /// <summary>
  601. /// Creates the root media folder
  602. /// </summary>
  603. /// <returns>AggregateFolder.</returns>
  604. /// <exception cref="System.InvalidOperationException">Cannot create the root folder until plugins have loaded</exception>
  605. public AggregateFolder CreateRootFolder()
  606. {
  607. var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath;
  608. _fileSystem.CreateDirectory(rootFolderPath);
  609. var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath));
  610. // Add in the plug-in folders
  611. foreach (var child in PluginFolderCreators)
  612. {
  613. var folder = child.GetFolder();
  614. if (folder != null)
  615. {
  616. if (folder.Id == Guid.Empty)
  617. {
  618. if (string.IsNullOrWhiteSpace(folder.Path))
  619. {
  620. folder.Id = GetNewItemId(folder.GetType().Name, folder.GetType());
  621. }
  622. else
  623. {
  624. folder.Id = GetNewItemId(folder.Path, folder.GetType());
  625. }
  626. }
  627. var dbItem = GetItemById(folder.Id) as BasePluginFolder;
  628. if (dbItem != null && string.Equals(dbItem.Path, folder.Path, StringComparison.OrdinalIgnoreCase))
  629. {
  630. folder = dbItem;
  631. }
  632. rootFolder.AddVirtualChild(folder);
  633. RegisterItem(folder);
  634. }
  635. }
  636. return rootFolder;
  637. }
  638. private volatile 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. /// <summary>
  1078. /// Gets the intros.
  1079. /// </summary>
  1080. /// <param name="item">The item.</param>
  1081. /// <param name="user">The user.</param>
  1082. /// <returns>IEnumerable{System.String}.</returns>
  1083. public async Task<IEnumerable<Video>> GetIntros(BaseItem item, User user)
  1084. {
  1085. var tasks = IntroProviders
  1086. .OrderBy(i => (i.GetType().Name.IndexOf("Default", StringComparison.OrdinalIgnoreCase) == -1 ? 0 : 1))
  1087. .Take(1)
  1088. .Select(i => GetIntros(i, item, user));
  1089. var items = await Task.WhenAll(tasks).ConfigureAwait(false);
  1090. return items
  1091. .SelectMany(i => i.ToArray())
  1092. .Select(ResolveIntro)
  1093. .Where(i => i != null);
  1094. }
  1095. /// <summary>
  1096. /// Gets the intros.
  1097. /// </summary>
  1098. /// <param name="provider">The provider.</param>
  1099. /// <param name="item">The item.</param>
  1100. /// <param name="user">The user.</param>
  1101. /// <returns>Task&lt;IEnumerable&lt;IntroInfo&gt;&gt;.</returns>
  1102. private async Task<IEnumerable<IntroInfo>> GetIntros(IIntroProvider provider, BaseItem item, User user)
  1103. {
  1104. try
  1105. {
  1106. return await provider.GetIntros(item, user).ConfigureAwait(false);
  1107. }
  1108. catch (Exception ex)
  1109. {
  1110. _logger.ErrorException("Error getting intros", ex);
  1111. return new List<IntroInfo>();
  1112. }
  1113. }
  1114. /// <summary>
  1115. /// Gets all intro files.
  1116. /// </summary>
  1117. /// <returns>IEnumerable{System.String}.</returns>
  1118. public IEnumerable<string> GetAllIntroFiles()
  1119. {
  1120. return IntroProviders.SelectMany(i =>
  1121. {
  1122. try
  1123. {
  1124. return i.GetAllIntroFiles().ToList();
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. _logger.ErrorException("Error getting intro files", ex);
  1129. return new List<string>();
  1130. }
  1131. });
  1132. }
  1133. /// <summary>
  1134. /// Resolves the intro.
  1135. /// </summary>
  1136. /// <param name="info">The info.</param>
  1137. /// <returns>Video.</returns>
  1138. private Video ResolveIntro(IntroInfo info)
  1139. {
  1140. Video video = null;
  1141. if (info.ItemId.HasValue)
  1142. {
  1143. // Get an existing item by Id
  1144. video = GetItemById(info.ItemId.Value) as Video;
  1145. if (video == null)
  1146. {
  1147. _logger.Error("Unable to locate item with Id {0}.", info.ItemId.Value);
  1148. }
  1149. }
  1150. else if (!string.IsNullOrEmpty(info.Path))
  1151. {
  1152. try
  1153. {
  1154. // Try to resolve the path into a video
  1155. video = ResolvePath(_fileSystem.GetFileSystemInfo(info.Path)) as Video;
  1156. if (video == null)
  1157. {
  1158. _logger.Error("Intro resolver returned null for {0}.", info.Path);
  1159. }
  1160. else
  1161. {
  1162. // Pull the saved db item that will include metadata
  1163. var dbItem = GetItemById(video.Id) as Video;
  1164. if (dbItem != null)
  1165. {
  1166. video = dbItem;
  1167. }
  1168. }
  1169. }
  1170. catch (Exception ex)
  1171. {
  1172. _logger.ErrorException("Error resolving path {0}.", ex, info.Path);
  1173. }
  1174. }
  1175. else
  1176. {
  1177. _logger.Error("IntroProvider returned an IntroInfo with null Path and ItemId.");
  1178. }
  1179. return video;
  1180. }
  1181. /// <summary>
  1182. /// Sorts the specified sort by.
  1183. /// </summary>
  1184. /// <param name="items">The items.</param>
  1185. /// <param name="user">The user.</param>
  1186. /// <param name="sortBy">The sort by.</param>
  1187. /// <param name="sortOrder">The sort order.</param>
  1188. /// <returns>IEnumerable{BaseItem}.</returns>
  1189. public IEnumerable<BaseItem> Sort(IEnumerable<BaseItem> items, User user, IEnumerable<string> sortBy, SortOrder sortOrder)
  1190. {
  1191. var isFirst = true;
  1192. IOrderedEnumerable<BaseItem> orderedItems = null;
  1193. foreach (var orderBy in sortBy.Select(o => GetComparer(o, user)).Where(c => c != null))
  1194. {
  1195. if (isFirst)
  1196. {
  1197. orderedItems = sortOrder == SortOrder.Descending ? items.OrderByDescending(i => i, orderBy) : items.OrderBy(i => i, orderBy);
  1198. }
  1199. else
  1200. {
  1201. orderedItems = sortOrder == SortOrder.Descending ? orderedItems.ThenByDescending(i => i, orderBy) : orderedItems.ThenBy(i => i, orderBy);
  1202. }
  1203. isFirst = false;
  1204. }
  1205. return orderedItems ?? items;
  1206. }
  1207. /// <summary>
  1208. /// Gets the comparer.
  1209. /// </summary>
  1210. /// <param name="name">The name.</param>
  1211. /// <param name="user">The user.</param>
  1212. /// <returns>IBaseItemComparer.</returns>
  1213. private IBaseItemComparer GetComparer(string name, User user)
  1214. {
  1215. var comparer = Comparers.FirstOrDefault(c => string.Equals(name, c.Name, StringComparison.OrdinalIgnoreCase));
  1216. if (comparer != null)
  1217. {
  1218. // If it requires a user, create a new one, and assign the user
  1219. if (comparer is IUserBaseItemComparer)
  1220. {
  1221. var userComparer = (IUserBaseItemComparer)Activator.CreateInstance(comparer.GetType());
  1222. userComparer.User = user;
  1223. userComparer.UserManager = _userManager;
  1224. userComparer.UserDataRepository = _userDataRepository;
  1225. return userComparer;
  1226. }
  1227. }
  1228. return comparer;
  1229. }
  1230. /// <summary>
  1231. /// Creates the item.
  1232. /// </summary>
  1233. /// <param name="item">The item.</param>
  1234. /// <param name="cancellationToken">The cancellation token.</param>
  1235. /// <returns>Task.</returns>
  1236. public Task CreateItem(BaseItem item, CancellationToken cancellationToken)
  1237. {
  1238. return CreateItems(new[] { item }, cancellationToken);
  1239. }
  1240. /// <summary>
  1241. /// Creates the items.
  1242. /// </summary>
  1243. /// <param name="items">The items.</param>
  1244. /// <param name="cancellationToken">The cancellation token.</param>
  1245. /// <returns>Task.</returns>
  1246. public async Task CreateItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  1247. {
  1248. var list = items.ToList();
  1249. await ItemRepository.SaveItems(list, cancellationToken).ConfigureAwait(false);
  1250. foreach (var item in list)
  1251. {
  1252. UpdateItemInLibraryCache(item);
  1253. }
  1254. if (ItemAdded != null)
  1255. {
  1256. foreach (var item in list)
  1257. {
  1258. try
  1259. {
  1260. ItemAdded(this, new ItemChangeEventArgs { Item = item });
  1261. }
  1262. catch (Exception ex)
  1263. {
  1264. _logger.ErrorException("Error in ItemAdded event handler", ex);
  1265. }
  1266. }
  1267. }
  1268. }
  1269. /// <summary>
  1270. /// Updates the item.
  1271. /// </summary>
  1272. /// <param name="item">The item.</param>
  1273. /// <param name="updateReason">The update reason.</param>
  1274. /// <param name="cancellationToken">The cancellation token.</param>
  1275. /// <returns>Task.</returns>
  1276. public async Task UpdateItem(BaseItem item, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1277. {
  1278. var locationType = item.LocationType;
  1279. if (locationType != LocationType.Remote && locationType != LocationType.Virtual)
  1280. {
  1281. await _providerManagerFactory().SaveMetadata(item, updateReason).ConfigureAwait(false);
  1282. }
  1283. item.DateLastSaved = DateTime.UtcNow;
  1284. var logName = item.LocationType == LocationType.Remote ? item.Name ?? item.Path : item.Path ?? item.Name;
  1285. _logger.Debug("Saving {0} to database.", logName);
  1286. await ItemRepository.SaveItem(item, cancellationToken).ConfigureAwait(false);
  1287. UpdateItemInLibraryCache(item);
  1288. if (ItemUpdated != null)
  1289. {
  1290. try
  1291. {
  1292. ItemUpdated(this, new ItemChangeEventArgs
  1293. {
  1294. Item = item,
  1295. UpdateReason = updateReason
  1296. });
  1297. }
  1298. catch (Exception ex)
  1299. {
  1300. _logger.ErrorException("Error in ItemUpdated event handler", ex);
  1301. }
  1302. }
  1303. }
  1304. /// <summary>
  1305. /// Reports the item removed.
  1306. /// </summary>
  1307. /// <param name="item">The item.</param>
  1308. public void ReportItemRemoved(BaseItem item)
  1309. {
  1310. if (ItemRemoved != null)
  1311. {
  1312. try
  1313. {
  1314. ItemRemoved(this, new ItemChangeEventArgs { Item = item });
  1315. }
  1316. catch (Exception ex)
  1317. {
  1318. _logger.ErrorException("Error in ItemRemoved event handler", ex);
  1319. }
  1320. }
  1321. }
  1322. /// <summary>
  1323. /// Retrieves the item.
  1324. /// </summary>
  1325. /// <param name="id">The id.</param>
  1326. /// <returns>BaseItem.</returns>
  1327. public BaseItem RetrieveItem(Guid id)
  1328. {
  1329. return ItemRepository.RetrieveItem(id);
  1330. }
  1331. public IEnumerable<Folder> GetCollectionFolders(BaseItem item)
  1332. {
  1333. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1334. {
  1335. item = item.Parent;
  1336. }
  1337. if (item == null)
  1338. {
  1339. return new List<Folder>();
  1340. }
  1341. return GetUserRootFolder().Children
  1342. .OfType<Folder>()
  1343. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase));
  1344. }
  1345. public string GetContentType(BaseItem item)
  1346. {
  1347. string configuredContentType = GetConfiguredContentType(item, false);
  1348. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1349. {
  1350. return configuredContentType;
  1351. }
  1352. configuredContentType = GetConfiguredContentType(item, true);
  1353. if (!string.IsNullOrWhiteSpace(configuredContentType))
  1354. {
  1355. return configuredContentType;
  1356. }
  1357. return GetInheritedContentType(item);
  1358. }
  1359. public string GetInheritedContentType(BaseItem item)
  1360. {
  1361. var type = GetTopFolderContentType(item);
  1362. if (!string.IsNullOrWhiteSpace(type))
  1363. {
  1364. return type;
  1365. }
  1366. return item.Parents
  1367. .Select(GetConfiguredContentType)
  1368. .LastOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1369. }
  1370. public string GetConfiguredContentType(BaseItem item)
  1371. {
  1372. return GetConfiguredContentType(item, false);
  1373. }
  1374. public string GetConfiguredContentType(string path)
  1375. {
  1376. return GetContentTypeOverride(path, false);
  1377. }
  1378. public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1379. {
  1380. ICollectionFolder collectionFolder = item as ICollectionFolder;
  1381. if (collectionFolder != null)
  1382. {
  1383. return collectionFolder.CollectionType;
  1384. }
  1385. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1386. }
  1387. private string GetContentTypeOverride(string path, bool inherit)
  1388. {
  1389. var nameValuePair = ConfigurationManager.Configuration.ContentTypes.FirstOrDefault(i => string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase) || (inherit && _fileSystem.ContainsSubPath(i.Name, path)));
  1390. if (nameValuePair != null)
  1391. {
  1392. return nameValuePair.Value;
  1393. }
  1394. return null;
  1395. }
  1396. private string GetTopFolderContentType(BaseItem item)
  1397. {
  1398. while (!(item.Parent is AggregateFolder) && item.Parent != null)
  1399. {
  1400. item = item.Parent;
  1401. }
  1402. if (item == null)
  1403. {
  1404. return null;
  1405. }
  1406. return GetUserRootFolder().Children
  1407. .OfType<ICollectionFolder>()
  1408. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1409. .Select(i => i.CollectionType)
  1410. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1411. }
  1412. private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
  1413. //private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromMinutes(1);
  1414. public Task<UserView> GetNamedView(User user,
  1415. string name,
  1416. string viewType,
  1417. string sortName,
  1418. CancellationToken cancellationToken)
  1419. {
  1420. return GetNamedViewInternal(user, name, null, viewType, sortName, null, cancellationToken);
  1421. }
  1422. public async Task<UserView> GetNamedView(string name,
  1423. string viewType,
  1424. string sortName,
  1425. CancellationToken cancellationToken)
  1426. {
  1427. var path = Path.Combine(ConfigurationManager.ApplicationPaths.ItemsByNamePath, "views");
  1428. path = Path.Combine(path, _fileSystem.GetValidFilename(viewType));
  1429. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1430. var item = GetItemById(id) as UserView;
  1431. var refresh = false;
  1432. if (item == null ||
  1433. !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1434. {
  1435. _fileSystem.CreateDirectory(path);
  1436. item = new UserView
  1437. {
  1438. Path = path,
  1439. Id = id,
  1440. DateCreated = DateTime.UtcNow,
  1441. Name = name,
  1442. ViewType = viewType,
  1443. ForcedSortName = sortName
  1444. };
  1445. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1446. refresh = true;
  1447. }
  1448. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1449. {
  1450. item.ViewType = viewType;
  1451. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1452. }
  1453. if (!refresh)
  1454. {
  1455. refresh = (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval;
  1456. }
  1457. if (!refresh && item.DisplayParentId != Guid.Empty)
  1458. {
  1459. var displayParent = GetItemById(item.DisplayParentId);
  1460. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1461. }
  1462. if (refresh)
  1463. {
  1464. await item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None).ConfigureAwait(false);
  1465. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1466. {
  1467. // Not sure why this is necessary but need to figure it out
  1468. // View images are not getting utilized without this
  1469. ForceSave = true
  1470. });
  1471. }
  1472. return item;
  1473. }
  1474. public Task<UserView> GetNamedView(User user,
  1475. string name,
  1476. string parentId,
  1477. string viewType,
  1478. string sortName,
  1479. string uniqueId,
  1480. CancellationToken cancellationToken)
  1481. {
  1482. if (string.IsNullOrWhiteSpace(parentId))
  1483. {
  1484. throw new ArgumentNullException("parentId");
  1485. }
  1486. return GetNamedViewInternal(user, name, parentId, viewType, sortName, uniqueId, cancellationToken);
  1487. }
  1488. private async Task<UserView> GetNamedViewInternal(User user,
  1489. string name,
  1490. string parentId,
  1491. string viewType,
  1492. string sortName,
  1493. string uniqueId,
  1494. CancellationToken cancellationToken)
  1495. {
  1496. if (string.IsNullOrWhiteSpace(name))
  1497. {
  1498. throw new ArgumentNullException("name");
  1499. }
  1500. var idValues = "37_namedview_" + name + user.Id.ToString("N") + (parentId ?? string.Empty);
  1501. if (!string.IsNullOrWhiteSpace(uniqueId))
  1502. {
  1503. idValues += uniqueId;
  1504. }
  1505. var id = GetNewItemId(idValues, typeof(UserView));
  1506. var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
  1507. var item = GetItemById(id) as UserView;
  1508. var isNew = false;
  1509. if (item == null)
  1510. {
  1511. _fileSystem.CreateDirectory(path);
  1512. item = new UserView
  1513. {
  1514. Path = path,
  1515. Id = id,
  1516. DateCreated = DateTime.UtcNow,
  1517. Name = name,
  1518. ViewType = viewType,
  1519. ForcedSortName = sortName,
  1520. UserId = user.Id
  1521. };
  1522. if (!string.IsNullOrWhiteSpace(parentId))
  1523. {
  1524. item.DisplayParentId = new Guid(parentId);
  1525. }
  1526. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1527. isNew = true;
  1528. }
  1529. if (!item.UserId.HasValue)
  1530. {
  1531. item.UserId = user.Id;
  1532. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1533. }
  1534. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1535. {
  1536. item.ViewType = viewType;
  1537. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1538. }
  1539. var refresh = isNew || (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval;
  1540. if (!refresh && item.DisplayParentId != Guid.Empty)
  1541. {
  1542. var displayParent = GetItemById(item.DisplayParentId);
  1543. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1544. }
  1545. if (refresh)
  1546. {
  1547. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1548. {
  1549. // Need to force save to increment DateLastSaved
  1550. ForceSave = true
  1551. });
  1552. }
  1553. return item;
  1554. }
  1555. public async Task<UserView> GetShadowView(BaseItem parent,
  1556. string viewType,
  1557. string sortName,
  1558. string uniqueId,
  1559. CancellationToken cancellationToken)
  1560. {
  1561. if (parent == null)
  1562. {
  1563. throw new ArgumentNullException("parent");
  1564. }
  1565. var name = parent.Name;
  1566. var parentId = parent.Id;
  1567. var idValues = "37_namedview_" + name + parentId + (viewType ?? string.Empty);
  1568. if (!string.IsNullOrWhiteSpace(uniqueId))
  1569. {
  1570. idValues += uniqueId;
  1571. }
  1572. var id = GetNewItemId(idValues, typeof(UserView));
  1573. var path = parent.Path;
  1574. var item = GetItemById(id) as UserView;
  1575. var isNew = false;
  1576. if (item == null)
  1577. {
  1578. _fileSystem.CreateDirectory(path);
  1579. item = new UserView
  1580. {
  1581. Path = path,
  1582. Id = id,
  1583. DateCreated = DateTime.UtcNow,
  1584. Name = name,
  1585. ViewType = viewType,
  1586. ForcedSortName = sortName
  1587. };
  1588. item.DisplayParentId = parentId;
  1589. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1590. isNew = true;
  1591. }
  1592. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1593. {
  1594. item.ViewType = viewType;
  1595. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1596. }
  1597. var refresh = isNew || (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval;
  1598. if (!refresh && item.DisplayParentId != Guid.Empty)
  1599. {
  1600. var displayParent = GetItemById(item.DisplayParentId);
  1601. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1602. }
  1603. if (refresh)
  1604. {
  1605. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1606. {
  1607. // Need to force save to increment DateLastSaved
  1608. ForceSave = true
  1609. });
  1610. }
  1611. return item;
  1612. }
  1613. public async Task<UserView> GetNamedView(string name,
  1614. string parentId,
  1615. string viewType,
  1616. string sortName,
  1617. string uniqueId,
  1618. CancellationToken cancellationToken)
  1619. {
  1620. if (string.IsNullOrWhiteSpace(name))
  1621. {
  1622. throw new ArgumentNullException("name");
  1623. }
  1624. var idValues = "37_namedview_" + name + (parentId ?? string.Empty) + (viewType ?? string.Empty);
  1625. if (!string.IsNullOrWhiteSpace(uniqueId))
  1626. {
  1627. idValues += uniqueId;
  1628. }
  1629. var id = GetNewItemId(idValues, typeof(UserView));
  1630. var path = Path.Combine(ConfigurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N"));
  1631. var item = GetItemById(id) as UserView;
  1632. var isNew = false;
  1633. if (item == null)
  1634. {
  1635. _fileSystem.CreateDirectory(path);
  1636. item = new UserView
  1637. {
  1638. Path = path,
  1639. Id = id,
  1640. DateCreated = DateTime.UtcNow,
  1641. Name = name,
  1642. ViewType = viewType,
  1643. ForcedSortName = sortName
  1644. };
  1645. if (!string.IsNullOrWhiteSpace(parentId))
  1646. {
  1647. item.DisplayParentId = new Guid(parentId);
  1648. }
  1649. await CreateItem(item, cancellationToken).ConfigureAwait(false);
  1650. isNew = true;
  1651. }
  1652. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1653. {
  1654. item.ViewType = viewType;
  1655. await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false);
  1656. }
  1657. var refresh = isNew || (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval;
  1658. if (!refresh && item.DisplayParentId != Guid.Empty)
  1659. {
  1660. var displayParent = GetItemById(item.DisplayParentId);
  1661. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1662. }
  1663. if (refresh)
  1664. {
  1665. _providerManagerFactory().QueueRefresh(item.Id, new MetadataRefreshOptions(_fileSystem)
  1666. {
  1667. // Need to force save to increment DateLastSaved
  1668. ForceSave = true
  1669. });
  1670. }
  1671. return item;
  1672. }
  1673. public bool IsVideoFile(string path)
  1674. {
  1675. var resolver = new VideoResolver(GetNamingOptions(), new PatternsLogger());
  1676. return resolver.IsVideoFile(path);
  1677. }
  1678. public bool IsAudioFile(string path)
  1679. {
  1680. var parser = new AudioFileParser(GetNamingOptions());
  1681. return parser.IsAudioFile(path);
  1682. }
  1683. public int? GetSeasonNumberFromPath(string path)
  1684. {
  1685. return new SeasonPathParser(GetNamingOptions(), new RegexProvider()).Parse(path, true, true).SeasonNumber;
  1686. }
  1687. public bool FillMissingEpisodeNumbersFromPath(Episode episode)
  1688. {
  1689. var resolver = new EpisodeResolver(GetNamingOptions(),
  1690. new PatternsLogger());
  1691. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd ||
  1692. episode.VideoType == VideoType.HdDvd;
  1693. var locationType = episode.LocationType;
  1694. var episodeInfo = locationType == LocationType.FileSystem || locationType == LocationType.Offline ?
  1695. resolver.Resolve(episode.Path, isFolder) :
  1696. new Naming.TV.EpisodeInfo();
  1697. if (episodeInfo == null)
  1698. {
  1699. episodeInfo = new Naming.TV.EpisodeInfo();
  1700. }
  1701. var changed = false;
  1702. if (episodeInfo.IsByDate)
  1703. {
  1704. if (episode.IndexNumber.HasValue)
  1705. {
  1706. episode.IndexNumber = null;
  1707. changed = true;
  1708. }
  1709. if (episode.IndexNumberEnd.HasValue)
  1710. {
  1711. episode.IndexNumberEnd = null;
  1712. changed = true;
  1713. }
  1714. if (!episode.PremiereDate.HasValue)
  1715. {
  1716. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  1717. {
  1718. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  1719. }
  1720. if (episode.PremiereDate.HasValue)
  1721. {
  1722. changed = true;
  1723. }
  1724. }
  1725. if (!episode.ProductionYear.HasValue)
  1726. {
  1727. episode.ProductionYear = episodeInfo.Year;
  1728. if (episode.ProductionYear.HasValue)
  1729. {
  1730. changed = true;
  1731. }
  1732. }
  1733. if (!episode.ParentIndexNumber.HasValue)
  1734. {
  1735. var season = episode.Season;
  1736. if (season != null)
  1737. {
  1738. episode.ParentIndexNumber = season.IndexNumber;
  1739. }
  1740. if (episode.ParentIndexNumber.HasValue)
  1741. {
  1742. changed = true;
  1743. }
  1744. }
  1745. }
  1746. else
  1747. {
  1748. if (!episode.IndexNumber.HasValue)
  1749. {
  1750. episode.IndexNumber = episodeInfo.EpisodeNumber;
  1751. if (episode.IndexNumber.HasValue)
  1752. {
  1753. changed = true;
  1754. }
  1755. }
  1756. if (!episode.IndexNumberEnd.HasValue)
  1757. {
  1758. episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
  1759. if (episode.IndexNumberEnd.HasValue)
  1760. {
  1761. changed = true;
  1762. }
  1763. }
  1764. if (!episode.ParentIndexNumber.HasValue)
  1765. {
  1766. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  1767. if (!episode.ParentIndexNumber.HasValue)
  1768. {
  1769. var season = episode.Season;
  1770. if (season != null)
  1771. {
  1772. episode.ParentIndexNumber = season.IndexNumber;
  1773. }
  1774. }
  1775. if (episode.ParentIndexNumber.HasValue)
  1776. {
  1777. changed = true;
  1778. }
  1779. }
  1780. }
  1781. return changed;
  1782. }
  1783. public NamingOptions GetNamingOptions()
  1784. {
  1785. var options = new ExtendedNamingOptions();
  1786. // These cause apps to have problems
  1787. options.AudioFileExtensions.Remove(".m3u");
  1788. options.AudioFileExtensions.Remove(".wpl");
  1789. if (!ConfigurationManager.Configuration.EnableAudioArchiveFiles)
  1790. {
  1791. options.AudioFileExtensions.Remove(".rar");
  1792. options.AudioFileExtensions.Remove(".zip");
  1793. }
  1794. if (!ConfigurationManager.Configuration.EnableVideoArchiveFiles)
  1795. {
  1796. options.VideoFileExtensions.Remove(".rar");
  1797. options.VideoFileExtensions.Remove(".zip");
  1798. }
  1799. return options;
  1800. }
  1801. public ItemLookupInfo ParseName(string name)
  1802. {
  1803. var resolver = new VideoResolver(GetNamingOptions(), new PatternsLogger());
  1804. var result = resolver.CleanDateTime(name);
  1805. var cleanName = resolver.CleanString(result.Name);
  1806. return new ItemLookupInfo
  1807. {
  1808. Name = cleanName.Name,
  1809. Year = result.Year
  1810. };
  1811. }
  1812. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1813. {
  1814. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1815. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  1816. .SelectMany(i => _fileSystem.GetFiles(i.FullName, false))
  1817. .ToList();
  1818. var videoListResolver = new VideoListResolver(GetNamingOptions(), new PatternsLogger());
  1819. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new FileMetadata
  1820. {
  1821. Id = i.FullName,
  1822. IsFolder = ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1823. }).ToList());
  1824. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1825. if (currentVideo != null)
  1826. {
  1827. files.AddRange(currentVideo.Extras.Where(i => string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
  1828. }
  1829. return ResolvePaths(files, directoryService, null, null)
  1830. .OfType<Video>()
  1831. .Select(video =>
  1832. {
  1833. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1834. var dbItem = GetItemById(video.Id) as Video;
  1835. if (dbItem != null)
  1836. {
  1837. video = dbItem;
  1838. }
  1839. video.ExtraType = ExtraType.Trailer;
  1840. return video;
  1841. // Sort them so that the list can be easily compared for changes
  1842. }).OrderBy(i => i.Path).ToList();
  1843. }
  1844. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1845. {
  1846. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1847. .Where(i => string.Equals(i.Name, "extras", StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, "specials", StringComparison.OrdinalIgnoreCase))
  1848. .SelectMany(i => _fileSystem.GetFiles(i.FullName, false))
  1849. .ToList();
  1850. var videoListResolver = new VideoListResolver(GetNamingOptions(), new PatternsLogger());
  1851. var videos = videoListResolver.Resolve(fileSystemChildren.Select(i => new FileMetadata
  1852. {
  1853. Id = i.FullName,
  1854. IsFolder = ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
  1855. }).ToList());
  1856. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  1857. if (currentVideo != null)
  1858. {
  1859. files.AddRange(currentVideo.Extras.Where(i => !string.Equals(i.ExtraType, "trailer", StringComparison.OrdinalIgnoreCase)).Select(i => _fileSystem.GetFileInfo(i.Path)));
  1860. }
  1861. return ResolvePaths(files, directoryService, null, null)
  1862. .OfType<Video>()
  1863. .Select(video =>
  1864. {
  1865. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1866. var dbItem = GetItemById(video.Id) as Video;
  1867. if (dbItem != null)
  1868. {
  1869. video = dbItem;
  1870. }
  1871. SetExtraTypeFromFilename(video);
  1872. return video;
  1873. // Sort them so that the list can be easily compared for changes
  1874. }).OrderBy(i => i.Path).ToList();
  1875. }
  1876. public string SubstitutePath(string path, string from, string to)
  1877. {
  1878. if (string.IsNullOrWhiteSpace(path))
  1879. {
  1880. throw new ArgumentNullException("path");
  1881. }
  1882. if (string.IsNullOrWhiteSpace(from))
  1883. {
  1884. throw new ArgumentNullException("from");
  1885. }
  1886. if (string.IsNullOrWhiteSpace(to))
  1887. {
  1888. throw new ArgumentNullException("to");
  1889. }
  1890. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  1891. if (!string.Equals(newPath, path))
  1892. {
  1893. if (to.IndexOf('/') != -1)
  1894. {
  1895. newPath = newPath.Replace('\\', '/');
  1896. }
  1897. else
  1898. {
  1899. newPath = newPath.Replace('/', '\\');
  1900. }
  1901. }
  1902. return newPath;
  1903. }
  1904. private void SetExtraTypeFromFilename(Video item)
  1905. {
  1906. var resolver = new ExtraResolver(GetNamingOptions(), new PatternsLogger(), new RegexProvider());
  1907. var result = resolver.GetExtraInfo(item.Path);
  1908. if (string.Equals(result.ExtraType, "deletedscene", StringComparison.OrdinalIgnoreCase))
  1909. {
  1910. item.ExtraType = ExtraType.DeletedScene;
  1911. }
  1912. else if (string.Equals(result.ExtraType, "behindthescenes", StringComparison.OrdinalIgnoreCase))
  1913. {
  1914. item.ExtraType = ExtraType.BehindTheScenes;
  1915. }
  1916. else if (string.Equals(result.ExtraType, "interview", StringComparison.OrdinalIgnoreCase))
  1917. {
  1918. item.ExtraType = ExtraType.Interview;
  1919. }
  1920. else if (string.Equals(result.ExtraType, "scene", StringComparison.OrdinalIgnoreCase))
  1921. {
  1922. item.ExtraType = ExtraType.Scene;
  1923. }
  1924. else if (string.Equals(result.ExtraType, "sample", StringComparison.OrdinalIgnoreCase))
  1925. {
  1926. item.ExtraType = ExtraType.Sample;
  1927. }
  1928. else
  1929. {
  1930. item.ExtraType = ExtraType.Clip;
  1931. }
  1932. }
  1933. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  1934. {
  1935. return ItemRepository.GetPeople(query);
  1936. }
  1937. public List<PersonInfo> GetPeople(BaseItem item)
  1938. {
  1939. if (item.SupportsPeople)
  1940. {
  1941. var people = GetPeople(new InternalPeopleQuery
  1942. {
  1943. ItemId = item.Id
  1944. });
  1945. if (people.Count > 0)
  1946. {
  1947. return people;
  1948. }
  1949. }
  1950. return new List<PersonInfo>();
  1951. }
  1952. public List<Person> GetPeopleItems(InternalPeopleQuery query)
  1953. {
  1954. return ItemRepository.GetPeopleNames(query).Select(i =>
  1955. {
  1956. try
  1957. {
  1958. return GetPerson(i);
  1959. }
  1960. catch (Exception ex)
  1961. {
  1962. _logger.ErrorException("Error getting person", ex);
  1963. return null;
  1964. }
  1965. }).Where(i => i != null).ToList();
  1966. }
  1967. public List<string> GetPeopleNames(InternalPeopleQuery query)
  1968. {
  1969. return ItemRepository.GetPeopleNames(query);
  1970. }
  1971. public List<PersonInfo> GetAllPeople()
  1972. {
  1973. return GetPeople(new InternalPeopleQuery())
  1974. .DistinctBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
  1975. .ToList();
  1976. }
  1977. public Task UpdatePeople(BaseItem item, List<PersonInfo> people)
  1978. {
  1979. if (!item.SupportsPeople)
  1980. {
  1981. return Task.FromResult(true);
  1982. }
  1983. return ItemRepository.UpdatePeople(item.Id, people);
  1984. }
  1985. private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1,1);
  1986. public async Task<ItemImageInfo> ConvertImageToLocal(IHasImages item, ItemImageInfo image, int imageIndex)
  1987. {
  1988. foreach (var url in image.Path.Split('|'))
  1989. {
  1990. try
  1991. {
  1992. _logger.Debug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  1993. await _providerManagerFactory().SaveImage(item, url, _dynamicImageResourcePool, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  1994. var newImage = item.GetImageInfo(image.Type, imageIndex);
  1995. if (newImage != null)
  1996. {
  1997. newImage.IsPlaceholder = image.IsPlaceholder;
  1998. }
  1999. await item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2000. return item.GetImageInfo(image.Type, imageIndex);
  2001. }
  2002. catch (HttpException ex)
  2003. {
  2004. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  2005. {
  2006. continue;
  2007. }
  2008. throw;
  2009. }
  2010. }
  2011. // Remove this image to prevent it from retrying over and over
  2012. item.RemoveImage(image);
  2013. await item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  2014. throw new InvalidOperationException();
  2015. }
  2016. }
  2017. }