LibraryManager.cs 112 KB

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