LibraryManager.cs 79 KB

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