LibraryManager.cs 109 KB

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