LibraryManager.cs 111 KB

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