LibraryManager.cs 106 KB

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