LibraryManager.cs 86 KB

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