LibraryManager.cs 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161
  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. public void UpdateImages(BaseItem item)
  1539. {
  1540. if (item == null)
  1541. {
  1542. throw new ArgumentNullException(nameof(item));
  1543. }
  1544. var outdated = item.ImageInfos
  1545. .Where(i => (i.IsLocalFile && (i.Width == 0 || i.Height == 0 || string.IsNullOrEmpty(i.BlurHash))))
  1546. .ToList();
  1547. if (outdated.Count == 0)
  1548. {
  1549. RegisterItem(item);
  1550. return;
  1551. }
  1552. outdated.ForEach(img =>
  1553. {
  1554. ImageDimensions size = _imageProcessor.GetImageDimensions(item, img);
  1555. img.Width = size.Width;
  1556. img.Height = size.Height;
  1557. img.BlurHash = _imageProcessor.GetImageBlurHash(img.Path);
  1558. });
  1559. _itemRepository.SaveImages(item);
  1560. RegisterItem(item);
  1561. }
  1562. /// <summary>
  1563. /// Updates the item.
  1564. /// </summary>
  1565. public void UpdateItems(IEnumerable<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1566. {
  1567. // Don't iterate multiple times
  1568. var itemsList = items.ToList();
  1569. foreach (var item in itemsList)
  1570. {
  1571. if (item.IsFileProtocol)
  1572. {
  1573. ProviderManager.SaveMetadata(item, updateReason);
  1574. }
  1575. item.DateLastSaved = DateTime.UtcNow;
  1576. UpdateImages(item);
  1577. }
  1578. _itemRepository.SaveItems(itemsList, cancellationToken);
  1579. if (ItemUpdated != null)
  1580. {
  1581. foreach (var item in itemsList)
  1582. {
  1583. // With the live tv guide this just creates too much noise
  1584. if (item.SourceType != SourceType.Library)
  1585. {
  1586. continue;
  1587. }
  1588. try
  1589. {
  1590. ItemUpdated(
  1591. this,
  1592. new ItemChangeEventArgs
  1593. {
  1594. Item = item,
  1595. Parent = parent,
  1596. UpdateReason = updateReason
  1597. });
  1598. }
  1599. catch (Exception ex)
  1600. {
  1601. _logger.LogError(ex, "Error in ItemUpdated event handler");
  1602. }
  1603. }
  1604. }
  1605. }
  1606. /// <summary>
  1607. /// Updates the item.
  1608. /// </summary>
  1609. /// <param name="item">The item.</param>
  1610. /// <param name="parent">The parent item.</param>
  1611. /// <param name="updateReason">The update reason.</param>
  1612. /// <param name="cancellationToken">The cancellation token.</param>
  1613. public void UpdateItem(BaseItem item, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
  1614. {
  1615. UpdateItems(new[] { item }, parent, updateReason, cancellationToken);
  1616. }
  1617. /// <summary>
  1618. /// Reports the item removed.
  1619. /// </summary>
  1620. /// <param name="item">The item.</param>
  1621. /// <param name="parent">The parent item.</param>
  1622. public void ReportItemRemoved(BaseItem item, BaseItem parent)
  1623. {
  1624. if (ItemRemoved != null)
  1625. {
  1626. try
  1627. {
  1628. ItemRemoved(
  1629. this,
  1630. new ItemChangeEventArgs
  1631. {
  1632. Item = item,
  1633. Parent = parent
  1634. });
  1635. }
  1636. catch (Exception ex)
  1637. {
  1638. _logger.LogError(ex, "Error in ItemRemoved event handler");
  1639. }
  1640. }
  1641. }
  1642. /// <summary>
  1643. /// Retrieves the item.
  1644. /// </summary>
  1645. /// <param name="id">The id.</param>
  1646. /// <returns>BaseItem.</returns>
  1647. public BaseItem RetrieveItem(Guid id)
  1648. {
  1649. return _itemRepository.RetrieveItem(id);
  1650. }
  1651. public List<Folder> GetCollectionFolders(BaseItem item)
  1652. {
  1653. while (item != null)
  1654. {
  1655. var parent = item.GetParent();
  1656. if (parent == null || parent is AggregateFolder)
  1657. {
  1658. break;
  1659. }
  1660. item = parent;
  1661. }
  1662. if (item == null)
  1663. {
  1664. return new List<Folder>();
  1665. }
  1666. return GetCollectionFoldersInternal(item, GetUserRootFolder().Children.OfType<Folder>().ToList());
  1667. }
  1668. public List<Folder> GetCollectionFolders(BaseItem item, List<Folder> allUserRootChildren)
  1669. {
  1670. while (item != null)
  1671. {
  1672. var parent = item.GetParent();
  1673. if (parent == null || parent is AggregateFolder)
  1674. {
  1675. break;
  1676. }
  1677. item = parent;
  1678. }
  1679. if (item == null)
  1680. {
  1681. return new List<Folder>();
  1682. }
  1683. return GetCollectionFoldersInternal(item, allUserRootChildren);
  1684. }
  1685. private static List<Folder> GetCollectionFoldersInternal(BaseItem item, List<Folder> allUserRootChildren)
  1686. {
  1687. return allUserRootChildren
  1688. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path, StringComparer.OrdinalIgnoreCase))
  1689. .ToList();
  1690. }
  1691. public LibraryOptions GetLibraryOptions(BaseItem item)
  1692. {
  1693. if (!(item is CollectionFolder collectionFolder))
  1694. {
  1695. collectionFolder = GetCollectionFolders(item)
  1696. .OfType<CollectionFolder>()
  1697. .FirstOrDefault();
  1698. }
  1699. return collectionFolder == null ? new LibraryOptions() : collectionFolder.GetLibraryOptions();
  1700. }
  1701. public string GetContentType(BaseItem item)
  1702. {
  1703. string configuredContentType = GetConfiguredContentType(item, false);
  1704. if (!string.IsNullOrEmpty(configuredContentType))
  1705. {
  1706. return configuredContentType;
  1707. }
  1708. configuredContentType = GetConfiguredContentType(item, true);
  1709. if (!string.IsNullOrEmpty(configuredContentType))
  1710. {
  1711. return configuredContentType;
  1712. }
  1713. return GetInheritedContentType(item);
  1714. }
  1715. public string GetInheritedContentType(BaseItem item)
  1716. {
  1717. var type = GetTopFolderContentType(item);
  1718. if (!string.IsNullOrEmpty(type))
  1719. {
  1720. return type;
  1721. }
  1722. return item.GetParents()
  1723. .Select(GetConfiguredContentType)
  1724. .LastOrDefault(i => !string.IsNullOrEmpty(i));
  1725. }
  1726. public string GetConfiguredContentType(BaseItem item)
  1727. {
  1728. return GetConfiguredContentType(item, false);
  1729. }
  1730. public string GetConfiguredContentType(string path)
  1731. {
  1732. return GetContentTypeOverride(path, false);
  1733. }
  1734. public string GetConfiguredContentType(BaseItem item, bool inheritConfiguredPath)
  1735. {
  1736. if (item is ICollectionFolder collectionFolder)
  1737. {
  1738. return collectionFolder.CollectionType;
  1739. }
  1740. return GetContentTypeOverride(item.ContainingFolderPath, inheritConfiguredPath);
  1741. }
  1742. private string GetContentTypeOverride(string path, bool inherit)
  1743. {
  1744. var nameValuePair = _configurationManager.Configuration.ContentTypes
  1745. .FirstOrDefault(i => _fileSystem.AreEqual(i.Name, path)
  1746. || (inherit && !string.IsNullOrEmpty(i.Name)
  1747. && _fileSystem.ContainsSubPath(i.Name, path)));
  1748. return nameValuePair?.Value;
  1749. }
  1750. private string GetTopFolderContentType(BaseItem item)
  1751. {
  1752. if (item == null)
  1753. {
  1754. return null;
  1755. }
  1756. while (!item.ParentId.Equals(Guid.Empty))
  1757. {
  1758. var parent = item.GetParent();
  1759. if (parent == null || parent is AggregateFolder)
  1760. {
  1761. break;
  1762. }
  1763. item = parent;
  1764. }
  1765. return GetUserRootFolder().Children
  1766. .OfType<ICollectionFolder>()
  1767. .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))
  1768. .Select(i => i.CollectionType)
  1769. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1770. }
  1771. private readonly TimeSpan _viewRefreshInterval = TimeSpan.FromHours(24);
  1772. public UserView GetNamedView(
  1773. User user,
  1774. string name,
  1775. string viewType,
  1776. string sortName)
  1777. {
  1778. return GetNamedView(user, name, Guid.Empty, viewType, sortName);
  1779. }
  1780. public UserView GetNamedView(
  1781. string name,
  1782. string viewType,
  1783. string sortName)
  1784. {
  1785. var path = Path.Combine(
  1786. _configurationManager.ApplicationPaths.InternalMetadataPath,
  1787. "views",
  1788. _fileSystem.GetValidFilename(viewType));
  1789. var id = GetNewItemId(path + "_namedview_" + name, typeof(UserView));
  1790. var item = GetItemById(id) as UserView;
  1791. var refresh = false;
  1792. if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
  1793. {
  1794. Directory.CreateDirectory(path);
  1795. item = new UserView
  1796. {
  1797. Path = path,
  1798. Id = id,
  1799. DateCreated = DateTime.UtcNow,
  1800. Name = name,
  1801. ViewType = viewType,
  1802. ForcedSortName = sortName
  1803. };
  1804. CreateItem(item, null);
  1805. refresh = true;
  1806. }
  1807. if (refresh)
  1808. {
  1809. item.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None);
  1810. ProviderManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
  1811. }
  1812. return item;
  1813. }
  1814. public UserView GetNamedView(
  1815. User user,
  1816. string name,
  1817. Guid parentId,
  1818. string viewType,
  1819. string sortName)
  1820. {
  1821. var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
  1822. var idValues = "38_namedview_" + name + user.Id.ToString("N", CultureInfo.InvariantCulture) + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
  1823. var id = GetNewItemId(idValues, typeof(UserView));
  1824. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1825. var item = GetItemById(id) as UserView;
  1826. var isNew = false;
  1827. if (item == null)
  1828. {
  1829. Directory.CreateDirectory(path);
  1830. item = new UserView
  1831. {
  1832. Path = path,
  1833. Id = id,
  1834. DateCreated = DateTime.UtcNow,
  1835. Name = name,
  1836. ViewType = viewType,
  1837. ForcedSortName = sortName,
  1838. UserId = user.Id,
  1839. DisplayParentId = parentId
  1840. };
  1841. CreateItem(item, null);
  1842. isNew = true;
  1843. }
  1844. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1845. if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
  1846. {
  1847. var displayParent = GetItemById(item.DisplayParentId);
  1848. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1849. }
  1850. if (refresh)
  1851. {
  1852. ProviderManager.QueueRefresh(
  1853. item.Id,
  1854. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1855. {
  1856. // Need to force save to increment DateLastSaved
  1857. ForceSave = true
  1858. },
  1859. RefreshPriority.Normal);
  1860. }
  1861. return item;
  1862. }
  1863. public UserView GetShadowView(
  1864. BaseItem parent,
  1865. string viewType,
  1866. string sortName)
  1867. {
  1868. if (parent == null)
  1869. {
  1870. throw new ArgumentNullException(nameof(parent));
  1871. }
  1872. var name = parent.Name;
  1873. var parentId = parent.Id;
  1874. var idValues = "38_namedview_" + name + parentId + (viewType ?? string.Empty);
  1875. var id = GetNewItemId(idValues, typeof(UserView));
  1876. var path = parent.Path;
  1877. var item = GetItemById(id) as UserView;
  1878. var isNew = false;
  1879. if (item == null)
  1880. {
  1881. Directory.CreateDirectory(path);
  1882. item = new UserView
  1883. {
  1884. Path = path,
  1885. Id = id,
  1886. DateCreated = DateTime.UtcNow,
  1887. Name = name,
  1888. ViewType = viewType,
  1889. ForcedSortName = sortName
  1890. };
  1891. item.DisplayParentId = parentId;
  1892. CreateItem(item, null);
  1893. isNew = true;
  1894. }
  1895. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1896. if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
  1897. {
  1898. var displayParent = GetItemById(item.DisplayParentId);
  1899. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1900. }
  1901. if (refresh)
  1902. {
  1903. ProviderManager.QueueRefresh(
  1904. item.Id,
  1905. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1906. {
  1907. // Need to force save to increment DateLastSaved
  1908. ForceSave = true
  1909. },
  1910. RefreshPriority.Normal);
  1911. }
  1912. return item;
  1913. }
  1914. public UserView GetNamedView(
  1915. string name,
  1916. Guid parentId,
  1917. string viewType,
  1918. string sortName,
  1919. string uniqueId)
  1920. {
  1921. if (string.IsNullOrEmpty(name))
  1922. {
  1923. throw new ArgumentNullException(nameof(name));
  1924. }
  1925. var parentIdString = parentId.Equals(Guid.Empty) ? null : parentId.ToString("N", CultureInfo.InvariantCulture);
  1926. var idValues = "37_namedview_" + name + (parentIdString ?? string.Empty) + (viewType ?? string.Empty);
  1927. if (!string.IsNullOrEmpty(uniqueId))
  1928. {
  1929. idValues += uniqueId;
  1930. }
  1931. var id = GetNewItemId(idValues, typeof(UserView));
  1932. var path = Path.Combine(_configurationManager.ApplicationPaths.InternalMetadataPath, "views", id.ToString("N", CultureInfo.InvariantCulture));
  1933. var item = GetItemById(id) as UserView;
  1934. var isNew = false;
  1935. if (item == null)
  1936. {
  1937. Directory.CreateDirectory(path);
  1938. item = new UserView
  1939. {
  1940. Path = path,
  1941. Id = id,
  1942. DateCreated = DateTime.UtcNow,
  1943. Name = name,
  1944. ViewType = viewType,
  1945. ForcedSortName = sortName
  1946. };
  1947. item.DisplayParentId = parentId;
  1948. CreateItem(item, null);
  1949. isNew = true;
  1950. }
  1951. if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase))
  1952. {
  1953. item.ViewType = viewType;
  1954. item.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None);
  1955. }
  1956. var refresh = isNew || DateTime.UtcNow - item.DateLastRefreshed >= _viewRefreshInterval;
  1957. if (!refresh && !item.DisplayParentId.Equals(Guid.Empty))
  1958. {
  1959. var displayParent = GetItemById(item.DisplayParentId);
  1960. refresh = displayParent != null && displayParent.DateLastSaved > item.DateLastRefreshed;
  1961. }
  1962. if (refresh)
  1963. {
  1964. ProviderManager.QueueRefresh(
  1965. item.Id,
  1966. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1967. {
  1968. // Need to force save to increment DateLastSaved
  1969. ForceSave = true
  1970. },
  1971. RefreshPriority.Normal);
  1972. }
  1973. return item;
  1974. }
  1975. public void AddExternalSubtitleStreams(
  1976. List<MediaStream> streams,
  1977. string videoPath,
  1978. string[] files)
  1979. {
  1980. new SubtitleResolver(BaseItem.LocalizationManager).AddExternalSubtitleStreams(streams, videoPath, streams.Count, files);
  1981. }
  1982. /// <inheritdoc />
  1983. public bool IsVideoFile(string path)
  1984. {
  1985. var resolver = new VideoResolver(GetNamingOptions());
  1986. return resolver.IsVideoFile(path);
  1987. }
  1988. /// <inheritdoc />
  1989. public bool IsAudioFile(string path)
  1990. => AudioFileParser.IsAudioFile(path, GetNamingOptions());
  1991. /// <inheritdoc />
  1992. public int? GetSeasonNumberFromPath(string path)
  1993. => SeasonPathParser.Parse(path, true, true).SeasonNumber;
  1994. /// <inheritdoc />
  1995. public bool FillMissingEpisodeNumbersFromPath(Episode episode, bool forceRefresh)
  1996. {
  1997. var series = episode.Series;
  1998. bool? isAbsoluteNaming = series == null ? false : string.Equals(series.DisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase);
  1999. if (!isAbsoluteNaming.Value)
  2000. {
  2001. // In other words, no filter applied
  2002. isAbsoluteNaming = null;
  2003. }
  2004. var resolver = new EpisodeResolver(GetNamingOptions());
  2005. var isFolder = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd;
  2006. var episodeInfo = episode.IsFileProtocol ?
  2007. resolver.Resolve(episode.Path, isFolder, null, null, isAbsoluteNaming) :
  2008. new Naming.TV.EpisodeInfo();
  2009. if (episodeInfo == null)
  2010. {
  2011. episodeInfo = new Naming.TV.EpisodeInfo();
  2012. }
  2013. try
  2014. {
  2015. var libraryOptions = GetLibraryOptions(episode);
  2016. if (libraryOptions.EnableEmbeddedEpisodeInfos && string.Equals(episodeInfo.Container, "mp4", StringComparison.OrdinalIgnoreCase))
  2017. {
  2018. // Read from metadata
  2019. var mediaInfo = _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  2020. {
  2021. MediaSource = episode.GetMediaSources(false)[0],
  2022. MediaType = DlnaProfileType.Video
  2023. }, CancellationToken.None).GetAwaiter().GetResult();
  2024. if (mediaInfo.ParentIndexNumber > 0)
  2025. {
  2026. episodeInfo.SeasonNumber = mediaInfo.ParentIndexNumber;
  2027. }
  2028. if (mediaInfo.IndexNumber > 0)
  2029. {
  2030. episodeInfo.EpisodeNumber = mediaInfo.IndexNumber;
  2031. }
  2032. if (!string.IsNullOrEmpty(mediaInfo.ShowName))
  2033. {
  2034. episodeInfo.SeriesName = mediaInfo.ShowName;
  2035. }
  2036. }
  2037. }
  2038. catch (Exception ex)
  2039. {
  2040. _logger.LogError(ex, "Error reading the episode informations with ffprobe. Episode: {EpisodeInfo}", episodeInfo.Path);
  2041. }
  2042. var changed = false;
  2043. if (episodeInfo.IsByDate)
  2044. {
  2045. if (episode.IndexNumber.HasValue)
  2046. {
  2047. episode.IndexNumber = null;
  2048. changed = true;
  2049. }
  2050. if (episode.IndexNumberEnd.HasValue)
  2051. {
  2052. episode.IndexNumberEnd = null;
  2053. changed = true;
  2054. }
  2055. if (!episode.PremiereDate.HasValue)
  2056. {
  2057. if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue)
  2058. {
  2059. episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime();
  2060. }
  2061. if (episode.PremiereDate.HasValue)
  2062. {
  2063. changed = true;
  2064. }
  2065. }
  2066. if (!episode.ProductionYear.HasValue)
  2067. {
  2068. episode.ProductionYear = episodeInfo.Year;
  2069. if (episode.ProductionYear.HasValue)
  2070. {
  2071. changed = true;
  2072. }
  2073. }
  2074. }
  2075. else
  2076. {
  2077. if (!episode.IndexNumber.HasValue || forceRefresh)
  2078. {
  2079. if (episode.IndexNumber != episodeInfo.EpisodeNumber)
  2080. {
  2081. changed = true;
  2082. }
  2083. episode.IndexNumber = episodeInfo.EpisodeNumber;
  2084. }
  2085. if (!episode.IndexNumberEnd.HasValue || forceRefresh)
  2086. {
  2087. if (episode.IndexNumberEnd != episodeInfo.EndingEpsiodeNumber)
  2088. {
  2089. changed = true;
  2090. }
  2091. episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber;
  2092. }
  2093. if (!episode.ParentIndexNumber.HasValue || forceRefresh)
  2094. {
  2095. if (episode.ParentIndexNumber != episodeInfo.SeasonNumber)
  2096. {
  2097. changed = true;
  2098. }
  2099. episode.ParentIndexNumber = episodeInfo.SeasonNumber;
  2100. }
  2101. }
  2102. if (!episode.ParentIndexNumber.HasValue)
  2103. {
  2104. var season = episode.Season;
  2105. if (season != null)
  2106. {
  2107. episode.ParentIndexNumber = season.IndexNumber;
  2108. }
  2109. else
  2110. {
  2111. /*
  2112. Anime series don't generally have a season in their file name, however,
  2113. tvdb needs a season to correctly get the metadata.
  2114. Hence, a null season needs to be filled with something. */
  2115. //FIXME perhaps this would be better for tvdb parser to ask for season 1 if no season is specified
  2116. episode.ParentIndexNumber = 1;
  2117. }
  2118. if (episode.ParentIndexNumber.HasValue)
  2119. {
  2120. changed = true;
  2121. }
  2122. }
  2123. return changed;
  2124. }
  2125. public NamingOptions GetNamingOptions()
  2126. {
  2127. if (_namingOptions == null)
  2128. {
  2129. _namingOptions = new NamingOptions();
  2130. _videoFileExtensions = _namingOptions.VideoFileExtensions;
  2131. }
  2132. return _namingOptions;
  2133. }
  2134. public ItemLookupInfo ParseName(string name)
  2135. {
  2136. var resolver = new VideoResolver(GetNamingOptions());
  2137. var result = resolver.CleanDateTime(name);
  2138. return new ItemLookupInfo
  2139. {
  2140. Name = resolver.TryCleanString(result.Name, out var newName) ? newName.ToString() : result.Name,
  2141. Year = result.Year
  2142. };
  2143. }
  2144. public IEnumerable<Video> FindTrailers(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2145. {
  2146. var namingOptions = GetNamingOptions();
  2147. var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
  2148. .Where(i => string.Equals(i.Name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  2149. .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
  2150. .ToList();
  2151. var videoListResolver = new VideoListResolver(namingOptions);
  2152. var videos = videoListResolver.Resolve(fileSystemChildren);
  2153. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  2154. if (currentVideo != null)
  2155. {
  2156. files.AddRange(currentVideo.Extras.Where(i => i.ExtraType == ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
  2157. }
  2158. var resolvers = new IItemResolver[]
  2159. {
  2160. new GenericVideoResolver<Trailer>(this)
  2161. };
  2162. return ResolvePaths(files, directoryService, null, new LibraryOptions(), null, resolvers)
  2163. .OfType<Trailer>()
  2164. .Select(video =>
  2165. {
  2166. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2167. var dbItem = GetItemById(video.Id) as Trailer;
  2168. if (dbItem != null)
  2169. {
  2170. video = dbItem;
  2171. }
  2172. video.ParentId = Guid.Empty;
  2173. video.OwnerId = owner.Id;
  2174. video.ExtraType = ExtraType.Trailer;
  2175. video.TrailerTypes = new[] { TrailerType.LocalTrailer };
  2176. return video;
  2177. // Sort them so that the list can be easily compared for changes
  2178. }).OrderBy(i => i.Path);
  2179. }
  2180. public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  2181. {
  2182. var namingOptions = GetNamingOptions();
  2183. var files = owner.IsInMixedFolder ? new List<FileSystemMetadata>() : fileSystemChildren.Where(i => i.IsDirectory)
  2184. .Where(i => BaseItem.AllExtrasTypesFolderNames.Contains(i.Name ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  2185. .SelectMany(i => _fileSystem.GetFiles(i.FullName, _videoFileExtensions, false, false))
  2186. .ToList();
  2187. var videoListResolver = new VideoListResolver(namingOptions);
  2188. var videos = videoListResolver.Resolve(fileSystemChildren);
  2189. var currentVideo = videos.FirstOrDefault(i => string.Equals(owner.Path, i.Files.First().Path, StringComparison.OrdinalIgnoreCase));
  2190. if (currentVideo != null)
  2191. {
  2192. files.AddRange(currentVideo.Extras.Where(i => i.ExtraType != ExtraType.Trailer).Select(i => _fileSystem.GetFileInfo(i.Path)));
  2193. }
  2194. return ResolvePaths(files, directoryService, null, new LibraryOptions(), null)
  2195. .OfType<Video>()
  2196. .Select(video =>
  2197. {
  2198. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2199. var dbItem = GetItemById(video.Id) as Video;
  2200. if (dbItem != null)
  2201. {
  2202. video = dbItem;
  2203. }
  2204. video.ParentId = Guid.Empty;
  2205. video.OwnerId = owner.Id;
  2206. SetExtraTypeFromFilename(video);
  2207. return video;
  2208. // Sort them so that the list can be easily compared for changes
  2209. }).OrderBy(i => i.Path);
  2210. }
  2211. public string GetPathAfterNetworkSubstitution(string path, BaseItem ownerItem)
  2212. {
  2213. if (ownerItem != null)
  2214. {
  2215. var libraryOptions = GetLibraryOptions(ownerItem);
  2216. if (libraryOptions != null)
  2217. {
  2218. foreach (var pathInfo in libraryOptions.PathInfos)
  2219. {
  2220. if (string.IsNullOrWhiteSpace(pathInfo.Path) || string.IsNullOrWhiteSpace(pathInfo.NetworkPath))
  2221. {
  2222. continue;
  2223. }
  2224. var substitutionResult = SubstitutePathInternal(path, pathInfo.Path, pathInfo.NetworkPath);
  2225. if (substitutionResult.Item2)
  2226. {
  2227. return substitutionResult.Item1;
  2228. }
  2229. }
  2230. }
  2231. }
  2232. var metadataPath = _configurationManager.Configuration.MetadataPath;
  2233. var metadataNetworkPath = _configurationManager.Configuration.MetadataNetworkPath;
  2234. if (!string.IsNullOrWhiteSpace(metadataPath) && !string.IsNullOrWhiteSpace(metadataNetworkPath))
  2235. {
  2236. var metadataSubstitutionResult = SubstitutePathInternal(path, metadataPath, metadataNetworkPath);
  2237. if (metadataSubstitutionResult.Item2)
  2238. {
  2239. return metadataSubstitutionResult.Item1;
  2240. }
  2241. }
  2242. foreach (var map in _configurationManager.Configuration.PathSubstitutions)
  2243. {
  2244. if (!string.IsNullOrWhiteSpace(map.From))
  2245. {
  2246. var substitutionResult = SubstitutePathInternal(path, map.From, map.To);
  2247. if (substitutionResult.Item2)
  2248. {
  2249. return substitutionResult.Item1;
  2250. }
  2251. }
  2252. }
  2253. return path;
  2254. }
  2255. public string SubstitutePath(string path, string from, string to)
  2256. {
  2257. return SubstitutePathInternal(path, from, to).Item1;
  2258. }
  2259. private Tuple<string, bool> SubstitutePathInternal(string path, string from, string to)
  2260. {
  2261. if (string.IsNullOrWhiteSpace(path))
  2262. {
  2263. throw new ArgumentNullException(nameof(path));
  2264. }
  2265. if (string.IsNullOrWhiteSpace(from))
  2266. {
  2267. throw new ArgumentNullException(nameof(from));
  2268. }
  2269. if (string.IsNullOrWhiteSpace(to))
  2270. {
  2271. throw new ArgumentNullException(nameof(to));
  2272. }
  2273. from = from.Trim();
  2274. to = to.Trim();
  2275. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  2276. var changed = false;
  2277. if (!string.Equals(newPath, path, StringComparison.Ordinal))
  2278. {
  2279. if (to.IndexOf('/', StringComparison.Ordinal) != -1)
  2280. {
  2281. newPath = newPath.Replace('\\', '/');
  2282. }
  2283. else
  2284. {
  2285. newPath = newPath.Replace('/', '\\');
  2286. }
  2287. changed = true;
  2288. }
  2289. return new Tuple<string, bool>(newPath, changed);
  2290. }
  2291. private void SetExtraTypeFromFilename(Video item)
  2292. {
  2293. var resolver = new ExtraResolver(GetNamingOptions());
  2294. var result = resolver.GetExtraInfo(item.Path);
  2295. item.ExtraType = result.ExtraType;
  2296. }
  2297. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  2298. {
  2299. return _itemRepository.GetPeople(query);
  2300. }
  2301. public List<PersonInfo> GetPeople(BaseItem item)
  2302. {
  2303. if (item.SupportsPeople)
  2304. {
  2305. var people = GetPeople(new InternalPeopleQuery
  2306. {
  2307. ItemId = item.Id
  2308. });
  2309. if (people.Count > 0)
  2310. {
  2311. return people;
  2312. }
  2313. }
  2314. return new List<PersonInfo>();
  2315. }
  2316. public List<Person> GetPeopleItems(InternalPeopleQuery query)
  2317. {
  2318. return _itemRepository.GetPeopleNames(query).Select(i =>
  2319. {
  2320. try
  2321. {
  2322. return GetPerson(i);
  2323. }
  2324. catch (Exception ex)
  2325. {
  2326. _logger.LogError(ex, "Error getting person");
  2327. return null;
  2328. }
  2329. }).Where(i => i != null).ToList();
  2330. }
  2331. public List<string> GetPeopleNames(InternalPeopleQuery query)
  2332. {
  2333. return _itemRepository.GetPeopleNames(query);
  2334. }
  2335. public void UpdatePeople(BaseItem item, List<PersonInfo> people)
  2336. {
  2337. if (!item.SupportsPeople)
  2338. {
  2339. return;
  2340. }
  2341. _itemRepository.UpdatePeople(item.Id, people);
  2342. }
  2343. public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex)
  2344. {
  2345. foreach (var url in image.Path.Split('|'))
  2346. {
  2347. try
  2348. {
  2349. _logger.LogDebug("ConvertImageToLocal item {0} - image url: {1}", item.Id, url);
  2350. await ProviderManager.SaveImage(item, url, image.Type, imageIndex, CancellationToken.None).ConfigureAwait(false);
  2351. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2352. return item.GetImageInfo(image.Type, imageIndex);
  2353. }
  2354. catch (HttpException ex)
  2355. {
  2356. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  2357. {
  2358. continue;
  2359. }
  2360. throw;
  2361. }
  2362. }
  2363. // Remove this image to prevent it from retrying over and over
  2364. item.RemoveImage(image);
  2365. item.UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2366. throw new InvalidOperationException();
  2367. }
  2368. public async Task AddVirtualFolder(string name, string collectionType, LibraryOptions options, bool refreshLibrary)
  2369. {
  2370. if (string.IsNullOrWhiteSpace(name))
  2371. {
  2372. throw new ArgumentNullException(nameof(name));
  2373. }
  2374. name = _fileSystem.GetValidFilename(name);
  2375. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2376. var virtualFolderPath = Path.Combine(rootFolderPath, name);
  2377. while (Directory.Exists(virtualFolderPath))
  2378. {
  2379. name += "1";
  2380. virtualFolderPath = Path.Combine(rootFolderPath, name);
  2381. }
  2382. var mediaPathInfos = options.PathInfos;
  2383. if (mediaPathInfos != null)
  2384. {
  2385. var invalidpath = mediaPathInfos.FirstOrDefault(i => !Directory.Exists(i.Path));
  2386. if (invalidpath != null)
  2387. {
  2388. throw new ArgumentException("The specified path does not exist: " + invalidpath.Path + ".");
  2389. }
  2390. }
  2391. LibraryMonitor.Stop();
  2392. try
  2393. {
  2394. Directory.CreateDirectory(virtualFolderPath);
  2395. if (!string.IsNullOrEmpty(collectionType))
  2396. {
  2397. var path = Path.Combine(virtualFolderPath, collectionType + ".collection");
  2398. File.WriteAllBytes(path, Array.Empty<byte>());
  2399. }
  2400. CollectionFolder.SaveLibraryOptions(virtualFolderPath, options);
  2401. if (mediaPathInfos != null)
  2402. {
  2403. foreach (var path in mediaPathInfos)
  2404. {
  2405. AddMediaPathInternal(name, path, false);
  2406. }
  2407. }
  2408. }
  2409. finally
  2410. {
  2411. if (refreshLibrary)
  2412. {
  2413. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2414. StartScanInBackground();
  2415. }
  2416. else
  2417. {
  2418. // Need to add a delay here or directory watchers may still pick up the changes
  2419. await Task.Delay(1000).ConfigureAwait(false);
  2420. LibraryMonitor.Start();
  2421. }
  2422. }
  2423. }
  2424. private void StartScanInBackground()
  2425. {
  2426. Task.Run(() =>
  2427. {
  2428. // No need to start if scanning the library because it will handle it
  2429. ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None);
  2430. });
  2431. }
  2432. private static bool ValidateNetworkPath(string path)
  2433. {
  2434. //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  2435. //{
  2436. // // We can't validate protocol-based paths, so just allow them
  2437. // if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
  2438. // {
  2439. // return Directory.Exists(path);
  2440. // }
  2441. //}
  2442. // Without native support for unc, we cannot validate this when running under mono
  2443. return true;
  2444. }
  2445. private const string ShortcutFileExtension = ".mblink";
  2446. public void AddMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
  2447. {
  2448. AddMediaPathInternal(virtualFolderName, pathInfo, true);
  2449. }
  2450. private void AddMediaPathInternal(string virtualFolderName, MediaPathInfo pathInfo, bool saveLibraryOptions)
  2451. {
  2452. if (pathInfo == null)
  2453. {
  2454. throw new ArgumentNullException(nameof(pathInfo));
  2455. }
  2456. var path = pathInfo.Path;
  2457. if (string.IsNullOrWhiteSpace(path))
  2458. {
  2459. throw new ArgumentException(nameof(path));
  2460. }
  2461. if (!Directory.Exists(path))
  2462. {
  2463. throw new FileNotFoundException("The path does not exist.");
  2464. }
  2465. if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
  2466. {
  2467. throw new FileNotFoundException("The network path does not exist.");
  2468. }
  2469. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2470. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2471. var shortcutFilename = Path.GetFileNameWithoutExtension(path);
  2472. var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2473. while (File.Exists(lnk))
  2474. {
  2475. shortcutFilename += "1";
  2476. lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
  2477. }
  2478. _fileSystem.CreateShortcut(lnk, _appHost.ReverseVirtualPath(path));
  2479. RemoveContentTypeOverrides(path);
  2480. if (saveLibraryOptions)
  2481. {
  2482. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2483. var list = libraryOptions.PathInfos.ToList();
  2484. list.Add(pathInfo);
  2485. libraryOptions.PathInfos = list.ToArray();
  2486. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2487. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2488. }
  2489. }
  2490. public void UpdateMediaPath(string virtualFolderName, MediaPathInfo pathInfo)
  2491. {
  2492. if (pathInfo == null)
  2493. {
  2494. throw new ArgumentNullException(nameof(pathInfo));
  2495. }
  2496. if (!string.IsNullOrWhiteSpace(pathInfo.NetworkPath) && !ValidateNetworkPath(pathInfo.NetworkPath))
  2497. {
  2498. throw new FileNotFoundException("The network path does not exist.");
  2499. }
  2500. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2501. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2502. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2503. SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
  2504. var list = libraryOptions.PathInfos.ToList();
  2505. foreach (var originalPathInfo in list)
  2506. {
  2507. if (string.Equals(pathInfo.Path, originalPathInfo.Path, StringComparison.Ordinal))
  2508. {
  2509. originalPathInfo.NetworkPath = pathInfo.NetworkPath;
  2510. break;
  2511. }
  2512. }
  2513. libraryOptions.PathInfos = list.ToArray();
  2514. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2515. }
  2516. private void SyncLibraryOptionsToLocations(string virtualFolderPath, LibraryOptions options)
  2517. {
  2518. var topLibraryFolders = GetUserRootFolder().Children.ToList();
  2519. var info = GetVirtualFolderInfo(virtualFolderPath, topLibraryFolders, null);
  2520. if (info.Locations.Length > 0 && info.Locations.Length != options.PathInfos.Length)
  2521. {
  2522. var list = options.PathInfos.ToList();
  2523. foreach (var location in info.Locations)
  2524. {
  2525. if (!list.Any(i => string.Equals(i.Path, location, StringComparison.Ordinal)))
  2526. {
  2527. list.Add(new MediaPathInfo
  2528. {
  2529. Path = location
  2530. });
  2531. }
  2532. }
  2533. options.PathInfos = list.ToArray();
  2534. }
  2535. }
  2536. public async Task RemoveVirtualFolder(string name, bool refreshLibrary)
  2537. {
  2538. if (string.IsNullOrWhiteSpace(name))
  2539. {
  2540. throw new ArgumentNullException(nameof(name));
  2541. }
  2542. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2543. var path = Path.Combine(rootFolderPath, name);
  2544. if (!Directory.Exists(path))
  2545. {
  2546. throw new FileNotFoundException("The media folder does not exist");
  2547. }
  2548. LibraryMonitor.Stop();
  2549. try
  2550. {
  2551. Directory.Delete(path, true);
  2552. }
  2553. finally
  2554. {
  2555. CollectionFolder.OnCollectionFolderChange();
  2556. if (refreshLibrary)
  2557. {
  2558. await ValidateTopLibraryFolders(CancellationToken.None).ConfigureAwait(false);
  2559. StartScanInBackground();
  2560. }
  2561. else
  2562. {
  2563. // Need to add a delay here or directory watchers may still pick up the changes
  2564. await Task.Delay(1000).ConfigureAwait(false);
  2565. LibraryMonitor.Start();
  2566. }
  2567. }
  2568. }
  2569. private void RemoveContentTypeOverrides(string path)
  2570. {
  2571. if (string.IsNullOrWhiteSpace(path))
  2572. {
  2573. throw new ArgumentNullException(nameof(path));
  2574. }
  2575. var removeList = new List<NameValuePair>();
  2576. foreach (var contentType in _configurationManager.Configuration.ContentTypes)
  2577. {
  2578. if (string.IsNullOrWhiteSpace(contentType.Name))
  2579. {
  2580. removeList.Add(contentType);
  2581. }
  2582. else if (_fileSystem.AreEqual(path, contentType.Name)
  2583. || _fileSystem.ContainsSubPath(path, contentType.Name))
  2584. {
  2585. removeList.Add(contentType);
  2586. }
  2587. }
  2588. if (removeList.Count > 0)
  2589. {
  2590. _configurationManager.Configuration.ContentTypes = _configurationManager.Configuration.ContentTypes
  2591. .Except(removeList)
  2592. .ToArray();
  2593. _configurationManager.SaveConfiguration();
  2594. }
  2595. }
  2596. public void RemoveMediaPath(string virtualFolderName, string mediaPath)
  2597. {
  2598. if (string.IsNullOrEmpty(mediaPath))
  2599. {
  2600. throw new ArgumentNullException(nameof(mediaPath));
  2601. }
  2602. var rootFolderPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath;
  2603. var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);
  2604. if (!Directory.Exists(virtualFolderPath))
  2605. {
  2606. throw new FileNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName));
  2607. }
  2608. var shortcut = _fileSystem.GetFilePaths(virtualFolderPath, true)
  2609. .Where(i => string.Equals(ShortcutFileExtension, Path.GetExtension(i), StringComparison.OrdinalIgnoreCase))
  2610. .FirstOrDefault(f => _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(f)).Equals(mediaPath, StringComparison.OrdinalIgnoreCase));
  2611. if (!string.IsNullOrEmpty(shortcut))
  2612. {
  2613. _fileSystem.DeleteFile(shortcut);
  2614. }
  2615. var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
  2616. libraryOptions.PathInfos = libraryOptions
  2617. .PathInfos
  2618. .Where(i => !string.Equals(i.Path, mediaPath, StringComparison.Ordinal))
  2619. .ToArray();
  2620. CollectionFolder.SaveLibraryOptions(virtualFolderPath, libraryOptions);
  2621. }
  2622. }
  2623. }