LibraryManager.cs 110 KB

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