LibraryManager.cs 107 KB

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