LibraryManager.cs 109 KB

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