LibraryManager.cs 108 KB

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