LibraryManager.cs 109 KB

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