LibraryManager.cs 109 KB

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