LibraryManager.cs 108 KB

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