LibraryManager.cs 111 KB

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