LibraryManager.cs 109 KB

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