LibraryManager.cs 110 KB

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