LibraryManager.cs 109 KB

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