LibraryManager.cs 106 KB

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