LibraryManager.cs 111 KB

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