LibraryManager.cs 109 KB

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