LibraryManager.cs 110 KB

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