BaseItem.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Collections;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.Localization;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Configuration;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Library;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Users;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Runtime.Serialization;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using CommonIO;
  27. using MediaBrowser.Controller.Sorting;
  28. using MediaBrowser.Model.LiveTv;
  29. using MediaBrowser.Model.Providers;
  30. namespace MediaBrowser.Controller.Entities
  31. {
  32. /// <summary>
  33. /// Class BaseItem
  34. /// </summary>
  35. public abstract class BaseItem : IHasProviderIds, ILibraryItem, IHasImages, IHasUserData, IHasMetadata, IHasLookupInfo<ItemLookupInfo>
  36. {
  37. protected BaseItem()
  38. {
  39. Keywords = new List<string>();
  40. Tags = new List<string>();
  41. Genres = new List<string>();
  42. Studios = new List<string>();
  43. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  44. LockedFields = new List<MetadataFields>();
  45. ImageInfos = new List<ItemImageInfo>();
  46. }
  47. public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
  48. public static char SlugChar = '-';
  49. /// <summary>
  50. /// The supported image extensions
  51. /// </summary>
  52. public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  53. public static readonly List<string> SupportedImageExtensionsList = SupportedImageExtensions.ToList();
  54. /// <summary>
  55. /// The trailer folder name
  56. /// </summary>
  57. public static string TrailerFolderName = "trailers";
  58. public static string ThemeSongsFolderName = "theme-music";
  59. public static string ThemeSongFilename = "theme";
  60. public static string ThemeVideosFolderName = "backdrops";
  61. [IgnoreDataMember]
  62. public string PreferredMetadataCountryCode { get; set; }
  63. [IgnoreDataMember]
  64. public string PreferredMetadataLanguage { get; set; }
  65. public long? Size { get; set; }
  66. public string Container { get; set; }
  67. public string ShortOverview { get; set; }
  68. public List<ItemImageInfo> ImageInfos { get; set; }
  69. [IgnoreDataMember]
  70. public bool IsVirtualItem { get; set; }
  71. /// <summary>
  72. /// Gets or sets the album.
  73. /// </summary>
  74. /// <value>The album.</value>
  75. [IgnoreDataMember]
  76. public string Album { get; set; }
  77. /// <summary>
  78. /// Gets or sets the channel identifier.
  79. /// </summary>
  80. /// <value>The channel identifier.</value>
  81. [IgnoreDataMember]
  82. public string ChannelId { get; set; }
  83. [IgnoreDataMember]
  84. public virtual bool SupportsAddingToPlaylist
  85. {
  86. get
  87. {
  88. return false;
  89. }
  90. }
  91. [IgnoreDataMember]
  92. public virtual bool AlwaysScanInternalMetadataPath
  93. {
  94. get { return false; }
  95. }
  96. /// <summary>
  97. /// Gets a value indicating whether this instance is in mixed folder.
  98. /// </summary>
  99. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  100. [IgnoreDataMember]
  101. public bool IsInMixedFolder { get; set; }
  102. [IgnoreDataMember]
  103. public virtual bool SupportsRemoteImageDownloading
  104. {
  105. get
  106. {
  107. return true;
  108. }
  109. }
  110. private string _name;
  111. /// <summary>
  112. /// Gets or sets the name.
  113. /// </summary>
  114. /// <value>The name.</value>
  115. [IgnoreDataMember]
  116. public virtual string Name
  117. {
  118. get
  119. {
  120. return _name;
  121. }
  122. set
  123. {
  124. _name = value;
  125. // lazy load this again
  126. _sortName = null;
  127. }
  128. }
  129. [IgnoreDataMember]
  130. public string SlugName
  131. {
  132. get
  133. {
  134. var name = Name;
  135. if (string.IsNullOrWhiteSpace(name))
  136. {
  137. return string.Empty;
  138. }
  139. return SlugReplaceChars.Aggregate(name, (current, c) => current.Replace(c, SlugChar));
  140. }
  141. }
  142. [IgnoreDataMember]
  143. public bool IsUnaired
  144. {
  145. get { return PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date; }
  146. }
  147. public string OriginalTitle { get; set; }
  148. /// <summary>
  149. /// Gets or sets the id.
  150. /// </summary>
  151. /// <value>The id.</value>
  152. [IgnoreDataMember]
  153. public Guid Id { get; set; }
  154. /// <summary>
  155. /// Gets or sets a value indicating whether this instance is hd.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
  158. [IgnoreDataMember]
  159. public bool? IsHD { get; set; }
  160. /// <summary>
  161. /// Gets or sets the audio.
  162. /// </summary>
  163. /// <value>The audio.</value>
  164. [IgnoreDataMember]
  165. public ProgramAudio? Audio { get; set; }
  166. /// <summary>
  167. /// Return the id that should be used to key display prefs for this item.
  168. /// Default is based on the type for everything except actual generic folders.
  169. /// </summary>
  170. /// <value>The display prefs id.</value>
  171. [IgnoreDataMember]
  172. public virtual Guid DisplayPreferencesId
  173. {
  174. get
  175. {
  176. var thisType = GetType();
  177. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  178. }
  179. }
  180. /// <summary>
  181. /// Gets or sets the path.
  182. /// </summary>
  183. /// <value>The path.</value>
  184. [IgnoreDataMember]
  185. public virtual string Path { get; set; }
  186. [IgnoreDataMember]
  187. public bool IsOffline { get; set; }
  188. [IgnoreDataMember]
  189. public virtual SourceType SourceType { get; set; }
  190. /// <summary>
  191. /// Returns the folder containing the item.
  192. /// If the item is a folder, it returns the folder itself
  193. /// </summary>
  194. [IgnoreDataMember]
  195. public virtual string ContainingFolderPath
  196. {
  197. get
  198. {
  199. if (IsFolder)
  200. {
  201. return Path;
  202. }
  203. return System.IO.Path.GetDirectoryName(Path);
  204. }
  205. }
  206. /// <summary>
  207. /// Gets or sets the name of the service.
  208. /// </summary>
  209. /// <value>The name of the service.</value>
  210. [IgnoreDataMember]
  211. public string ServiceName { get; set; }
  212. /// <summary>
  213. /// If this content came from an external service, the id of the content on that service
  214. /// </summary>
  215. [IgnoreDataMember]
  216. public string ExternalId
  217. {
  218. get { return this.GetProviderId("ProviderExternalId"); }
  219. set
  220. {
  221. this.SetProviderId("ProviderExternalId", value);
  222. }
  223. }
  224. /// <summary>
  225. /// Gets or sets the etag.
  226. /// </summary>
  227. /// <value>The etag.</value>
  228. [IgnoreDataMember]
  229. public string ExternalEtag { get; set; }
  230. [IgnoreDataMember]
  231. public virtual bool IsHidden
  232. {
  233. get
  234. {
  235. return false;
  236. }
  237. }
  238. [IgnoreDataMember]
  239. public virtual bool IsOwnedItem
  240. {
  241. get
  242. {
  243. // Local trailer, special feature, theme video, etc.
  244. // An item that belongs to another item but is not part of the Parent-Child tree
  245. return !IsFolder && ParentId == Guid.Empty && LocationType == LocationType.FileSystem;
  246. }
  247. }
  248. public Task UpdateIsOffline(bool newValue)
  249. {
  250. var item = this;
  251. if (item.IsOffline != newValue)
  252. {
  253. item.IsOffline = newValue;
  254. // this is creating too many repeated db updates
  255. //return item.UpdateToRepository(ItemUpdateType.None, CancellationToken.None);
  256. }
  257. return Task.FromResult(true);
  258. }
  259. /// <summary>
  260. /// Gets or sets the type of the location.
  261. /// </summary>
  262. /// <value>The type of the location.</value>
  263. [IgnoreDataMember]
  264. public virtual LocationType LocationType
  265. {
  266. get
  267. {
  268. //if (IsOffline)
  269. //{
  270. // return LocationType.Offline;
  271. //}
  272. if (string.IsNullOrWhiteSpace(Path))
  273. {
  274. if (SourceType == SourceType.Channel)
  275. {
  276. return LocationType.Remote;
  277. }
  278. return LocationType.Virtual;
  279. }
  280. return FileSystem.IsPathFile(Path) ? LocationType.FileSystem : LocationType.Remote;
  281. }
  282. }
  283. [IgnoreDataMember]
  284. public virtual bool SupportsLocalMetadata
  285. {
  286. get
  287. {
  288. if (SourceType == SourceType.Channel)
  289. {
  290. return false;
  291. }
  292. var locationType = LocationType;
  293. return locationType != LocationType.Remote && locationType != LocationType.Virtual;
  294. }
  295. }
  296. [IgnoreDataMember]
  297. public virtual string FileNameWithoutExtension
  298. {
  299. get
  300. {
  301. if (LocationType == LocationType.FileSystem)
  302. {
  303. return System.IO.Path.GetFileNameWithoutExtension(Path);
  304. }
  305. return null;
  306. }
  307. }
  308. [IgnoreDataMember]
  309. public virtual bool EnableAlphaNumericSorting
  310. {
  311. get
  312. {
  313. return true;
  314. }
  315. }
  316. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  317. {
  318. var list = new List<Tuple<StringBuilder, bool>>();
  319. int thisMarker = 0, thisNumericChunk = 0;
  320. while (thisMarker < s1.Length)
  321. {
  322. if (thisMarker >= s1.Length)
  323. {
  324. break;
  325. }
  326. char thisCh = s1[thisMarker];
  327. StringBuilder thisChunk = new StringBuilder();
  328. while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
  329. {
  330. thisChunk.Append(thisCh);
  331. thisMarker++;
  332. if (thisMarker < s1.Length)
  333. {
  334. thisCh = s1[thisMarker];
  335. }
  336. }
  337. var isNumeric = thisChunk.Length > 0 && char.IsDigit(thisChunk[0]);
  338. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  339. }
  340. return list;
  341. }
  342. /// <summary>
  343. /// This is just a helper for convenience
  344. /// </summary>
  345. /// <value>The primary image path.</value>
  346. [IgnoreDataMember]
  347. public string PrimaryImagePath
  348. {
  349. get { return this.GetImagePath(ImageType.Primary); }
  350. }
  351. public virtual bool IsInternetMetadataEnabled()
  352. {
  353. return ConfigurationManager.Configuration.EnableInternetProviders;
  354. }
  355. public virtual bool CanDelete()
  356. {
  357. if (SourceType == SourceType.Channel)
  358. {
  359. return false;
  360. }
  361. var locationType = LocationType;
  362. return locationType != LocationType.Remote &&
  363. locationType != LocationType.Virtual;
  364. }
  365. public virtual bool IsAuthorizedToDelete(User user)
  366. {
  367. return user.Policy.EnableContentDeletion;
  368. }
  369. public bool CanDelete(User user)
  370. {
  371. return CanDelete() && IsAuthorizedToDelete(user);
  372. }
  373. public virtual bool CanDownload()
  374. {
  375. return false;
  376. }
  377. public virtual bool IsAuthorizedToDownload(User user)
  378. {
  379. return user.Policy.EnableContentDownloading;
  380. }
  381. public bool CanDownload(User user)
  382. {
  383. return CanDownload() && IsAuthorizedToDownload(user);
  384. }
  385. /// <summary>
  386. /// Gets or sets the date created.
  387. /// </summary>
  388. /// <value>The date created.</value>
  389. [IgnoreDataMember]
  390. public DateTime DateCreated { get; set; }
  391. /// <summary>
  392. /// Gets or sets the date modified.
  393. /// </summary>
  394. /// <value>The date modified.</value>
  395. [IgnoreDataMember]
  396. public DateTime DateModified { get; set; }
  397. [IgnoreDataMember]
  398. public DateTime DateLastSaved { get; set; }
  399. [IgnoreDataMember]
  400. public DateTime DateLastRefreshed { get; set; }
  401. [IgnoreDataMember]
  402. public virtual bool EnableRefreshOnDateModifiedChange
  403. {
  404. get { return false; }
  405. }
  406. /// <summary>
  407. /// The logger
  408. /// </summary>
  409. public static ILogger Logger { get; set; }
  410. public static ILibraryManager LibraryManager { get; set; }
  411. public static IServerConfigurationManager ConfigurationManager { get; set; }
  412. public static IProviderManager ProviderManager { get; set; }
  413. public static ILocalizationManager LocalizationManager { get; set; }
  414. public static IItemRepository ItemRepository { get; set; }
  415. public static IFileSystem FileSystem { get; set; }
  416. public static IUserDataManager UserDataManager { get; set; }
  417. public static ILiveTvManager LiveTvManager { get; set; }
  418. public static IChannelManager ChannelManager { get; set; }
  419. public static ICollectionManager CollectionManager { get; set; }
  420. public static IImageProcessor ImageProcessor { get; set; }
  421. public static IMediaSourceManager MediaSourceManager { get; set; }
  422. /// <summary>
  423. /// Returns a <see cref="System.String" /> that represents this instance.
  424. /// </summary>
  425. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  426. public override string ToString()
  427. {
  428. return Name;
  429. }
  430. [IgnoreDataMember]
  431. public bool IsLocked { get; set; }
  432. /// <summary>
  433. /// Gets or sets the locked fields.
  434. /// </summary>
  435. /// <value>The locked fields.</value>
  436. [IgnoreDataMember]
  437. public List<MetadataFields> LockedFields { get; set; }
  438. /// <summary>
  439. /// Gets the type of the media.
  440. /// </summary>
  441. /// <value>The type of the media.</value>
  442. [IgnoreDataMember]
  443. public virtual string MediaType
  444. {
  445. get
  446. {
  447. return null;
  448. }
  449. }
  450. [IgnoreDataMember]
  451. public virtual IEnumerable<string> PhysicalLocations
  452. {
  453. get
  454. {
  455. var locationType = LocationType;
  456. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  457. {
  458. return new string[] { };
  459. }
  460. return new[] { Path };
  461. }
  462. }
  463. private string _forcedSortName;
  464. /// <summary>
  465. /// Gets or sets the name of the forced sort.
  466. /// </summary>
  467. /// <value>The name of the forced sort.</value>
  468. [IgnoreDataMember]
  469. public string ForcedSortName
  470. {
  471. get { return _forcedSortName; }
  472. set { _forcedSortName = value; _sortName = null; }
  473. }
  474. private string _sortName;
  475. /// <summary>
  476. /// Gets the name of the sort.
  477. /// </summary>
  478. /// <value>The name of the sort.</value>
  479. [IgnoreDataMember]
  480. public string SortName
  481. {
  482. get
  483. {
  484. if (_sortName == null)
  485. {
  486. if (!string.IsNullOrWhiteSpace(ForcedSortName))
  487. {
  488. // Need the ToLower because that's what CreateSortName does
  489. _sortName = ModifySortChunks(ForcedSortName).ToLower();
  490. }
  491. else
  492. {
  493. _sortName = CreateSortName();
  494. }
  495. }
  496. return _sortName;
  497. }
  498. set
  499. {
  500. _sortName = value;
  501. }
  502. }
  503. public string GetInternalMetadataPath()
  504. {
  505. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  506. return GetInternalMetadataPath(basePath);
  507. }
  508. protected virtual string GetInternalMetadataPath(string basePath)
  509. {
  510. if (SourceType == SourceType.Channel)
  511. {
  512. return System.IO.Path.Combine(basePath, "channels", ChannelId, Id.ToString("N"));
  513. }
  514. var idString = Id.ToString("N");
  515. basePath = System.IO.Path.Combine(basePath, "library");
  516. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  517. }
  518. /// <summary>
  519. /// Creates the name of the sort.
  520. /// </summary>
  521. /// <returns>System.String.</returns>
  522. protected virtual string CreateSortName()
  523. {
  524. if (Name == null) return null; //some items may not have name filled in properly
  525. if (!EnableAlphaNumericSorting)
  526. {
  527. return Name.TrimStart();
  528. }
  529. var sortable = Name.Trim().ToLower();
  530. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  531. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  532. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  533. {
  534. var searchLower = search.ToLower();
  535. // Remove from beginning if a space follows
  536. if (sortable.StartsWith(searchLower + " "))
  537. {
  538. sortable = sortable.Remove(0, searchLower.Length + 1);
  539. }
  540. // Remove from middle if surrounded by spaces
  541. sortable = sortable.Replace(" " + searchLower + " ", " ");
  542. // Remove from end if followed by a space
  543. if (sortable.EndsWith(" " + searchLower))
  544. {
  545. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  546. }
  547. }
  548. return ModifySortChunks(sortable);
  549. }
  550. private string ModifySortChunks(string name)
  551. {
  552. var chunks = GetSortChunks(name);
  553. var builder = new StringBuilder();
  554. foreach (var chunk in chunks)
  555. {
  556. var chunkBuilder = chunk.Item1;
  557. // This chunk is numeric
  558. if (chunk.Item2)
  559. {
  560. while (chunkBuilder.Length < 10)
  561. {
  562. chunkBuilder.Insert(0, '0');
  563. }
  564. }
  565. builder.Append(chunkBuilder);
  566. }
  567. //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  568. return builder.ToString().RemoveDiacritics();
  569. }
  570. [IgnoreDataMember]
  571. public Guid ParentId { get; set; }
  572. /// <summary>
  573. /// Gets or sets the parent.
  574. /// </summary>
  575. /// <value>The parent.</value>
  576. [IgnoreDataMember]
  577. public Folder Parent
  578. {
  579. get { return GetParent() as Folder; }
  580. set
  581. {
  582. }
  583. }
  584. public void SetParent(Folder parent)
  585. {
  586. ParentId = parent == null ? Guid.Empty : parent.Id;
  587. }
  588. [IgnoreDataMember]
  589. public IEnumerable<Folder> Parents
  590. {
  591. get { return GetParents().OfType<Folder>(); }
  592. }
  593. public BaseItem GetParent()
  594. {
  595. if (ParentId != Guid.Empty)
  596. {
  597. return LibraryManager.GetItemById(ParentId);
  598. }
  599. return null;
  600. }
  601. public IEnumerable<BaseItem> GetParents()
  602. {
  603. var parent = GetParent();
  604. while (parent != null)
  605. {
  606. yield return parent;
  607. parent = parent.GetParent();
  608. }
  609. }
  610. /// <summary>
  611. /// Finds a parent of a given type
  612. /// </summary>
  613. /// <typeparam name="T"></typeparam>
  614. /// <returns>``0.</returns>
  615. public T FindParent<T>()
  616. where T : Folder
  617. {
  618. return GetParents().OfType<T>().FirstOrDefault();
  619. }
  620. [IgnoreDataMember]
  621. public virtual Guid? DisplayParentId
  622. {
  623. get
  624. {
  625. if (ParentId == Guid.Empty)
  626. {
  627. return null;
  628. }
  629. return ParentId;
  630. }
  631. }
  632. [IgnoreDataMember]
  633. public BaseItem DisplayParent
  634. {
  635. get
  636. {
  637. var id = DisplayParentId;
  638. if (!id.HasValue || id.Value == Guid.Empty)
  639. {
  640. return null;
  641. }
  642. return LibraryManager.GetItemById(id.Value);
  643. }
  644. }
  645. /// <summary>
  646. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  647. /// </summary>
  648. /// <value>The premiere date.</value>
  649. [IgnoreDataMember]
  650. public DateTime? PremiereDate { get; set; }
  651. /// <summary>
  652. /// Gets or sets the end date.
  653. /// </summary>
  654. /// <value>The end date.</value>
  655. [IgnoreDataMember]
  656. public DateTime? EndDate { get; set; }
  657. /// <summary>
  658. /// Gets or sets the display type of the media.
  659. /// </summary>
  660. /// <value>The display type of the media.</value>
  661. [IgnoreDataMember]
  662. public string DisplayMediaType { get; set; }
  663. /// <summary>
  664. /// Gets or sets the official rating.
  665. /// </summary>
  666. /// <value>The official rating.</value>
  667. [IgnoreDataMember]
  668. public string OfficialRating { get; set; }
  669. /// <summary>
  670. /// Gets or sets the critic rating.
  671. /// </summary>
  672. /// <value>The critic rating.</value>
  673. [IgnoreDataMember]
  674. public float? CriticRating { get; set; }
  675. /// <summary>
  676. /// Gets or sets the critic rating summary.
  677. /// </summary>
  678. /// <value>The critic rating summary.</value>
  679. [IgnoreDataMember]
  680. public string CriticRatingSummary { get; set; }
  681. /// <summary>
  682. /// Gets or sets the official rating description.
  683. /// </summary>
  684. /// <value>The official rating description.</value>
  685. [IgnoreDataMember]
  686. public string OfficialRatingDescription { get; set; }
  687. /// <summary>
  688. /// Gets or sets the custom rating.
  689. /// </summary>
  690. /// <value>The custom rating.</value>
  691. [IgnoreDataMember]
  692. public string CustomRating { get; set; }
  693. /// <summary>
  694. /// Gets or sets the overview.
  695. /// </summary>
  696. /// <value>The overview.</value>
  697. [IgnoreDataMember]
  698. public string Overview { get; set; }
  699. /// <summary>
  700. /// Gets or sets the studios.
  701. /// </summary>
  702. /// <value>The studios.</value>
  703. [IgnoreDataMember]
  704. public List<string> Studios { get; set; }
  705. /// <summary>
  706. /// Gets or sets the genres.
  707. /// </summary>
  708. /// <value>The genres.</value>
  709. [IgnoreDataMember]
  710. public List<string> Genres { get; set; }
  711. /// <summary>
  712. /// Gets or sets the tags.
  713. /// </summary>
  714. /// <value>The tags.</value>
  715. [IgnoreDataMember]
  716. public List<string> Tags { get; set; }
  717. public List<string> Keywords { get; set; }
  718. /// <summary>
  719. /// Gets or sets the home page URL.
  720. /// </summary>
  721. /// <value>The home page URL.</value>
  722. [IgnoreDataMember]
  723. public string HomePageUrl { get; set; }
  724. /// <summary>
  725. /// Gets or sets the community rating.
  726. /// </summary>
  727. /// <value>The community rating.</value>
  728. [IgnoreDataMember]
  729. public float? CommunityRating { get; set; }
  730. /// <summary>
  731. /// Gets or sets the community rating vote count.
  732. /// </summary>
  733. /// <value>The community rating vote count.</value>
  734. [IgnoreDataMember]
  735. public int? VoteCount { get; set; }
  736. /// <summary>
  737. /// Gets or sets the run time ticks.
  738. /// </summary>
  739. /// <value>The run time ticks.</value>
  740. [IgnoreDataMember]
  741. public long? RunTimeTicks { get; set; }
  742. /// <summary>
  743. /// Gets or sets the production year.
  744. /// </summary>
  745. /// <value>The production year.</value>
  746. [IgnoreDataMember]
  747. public int? ProductionYear { get; set; }
  748. /// <summary>
  749. /// If the item is part of a series, this is it's number in the series.
  750. /// This could be episode number, album track number, etc.
  751. /// </summary>
  752. /// <value>The index number.</value>
  753. [IgnoreDataMember]
  754. public int? IndexNumber { get; set; }
  755. /// <summary>
  756. /// For an episode this could be the season number, or for a song this could be the disc number.
  757. /// </summary>
  758. /// <value>The parent index number.</value>
  759. [IgnoreDataMember]
  760. public int? ParentIndexNumber { get; set; }
  761. [IgnoreDataMember]
  762. public string OfficialRatingForComparison
  763. {
  764. get
  765. {
  766. if (!string.IsNullOrWhiteSpace(OfficialRating))
  767. {
  768. return OfficialRating;
  769. }
  770. var parent = DisplayParent;
  771. if (parent != null)
  772. {
  773. return parent.OfficialRatingForComparison;
  774. }
  775. return null;
  776. }
  777. }
  778. [IgnoreDataMember]
  779. public string CustomRatingForComparison
  780. {
  781. get
  782. {
  783. if (!string.IsNullOrWhiteSpace(CustomRating))
  784. {
  785. return CustomRating;
  786. }
  787. var parent = DisplayParent;
  788. if (parent != null)
  789. {
  790. return parent.CustomRatingForComparison;
  791. }
  792. return null;
  793. }
  794. }
  795. /// <summary>
  796. /// Gets the play access.
  797. /// </summary>
  798. /// <param name="user">The user.</param>
  799. /// <returns>PlayAccess.</returns>
  800. public PlayAccess GetPlayAccess(User user)
  801. {
  802. if (!user.Policy.EnableMediaPlayback)
  803. {
  804. return PlayAccess.None;
  805. }
  806. //if (!user.IsParentalScheduleAllowed())
  807. //{
  808. // return PlayAccess.None;
  809. //}
  810. return PlayAccess.Full;
  811. }
  812. /// <summary>
  813. /// Loads the theme songs.
  814. /// </summary>
  815. /// <returns>List{Audio.Audio}.</returns>
  816. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  817. {
  818. var files = fileSystemChildren.Where(i => i.IsDirectory)
  819. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  820. .SelectMany(i => directoryService.GetFiles(i.FullName))
  821. .ToList();
  822. // Support plex/xbmc convention
  823. files.AddRange(fileSystemChildren
  824. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  825. );
  826. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  827. .OfType<Audio.Audio>()
  828. .Select(audio =>
  829. {
  830. // Try to retrieve it from the db. If we don't find it, use the resolved version
  831. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  832. if (dbItem != null)
  833. {
  834. audio = dbItem;
  835. }
  836. audio.ExtraType = ExtraType.ThemeSong;
  837. return audio;
  838. // Sort them so that the list can be easily compared for changes
  839. }).OrderBy(i => i.Path).ToList();
  840. }
  841. /// <summary>
  842. /// Loads the video backdrops.
  843. /// </summary>
  844. /// <returns>List{Video}.</returns>
  845. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  846. {
  847. var files = fileSystemChildren.Where(i => i.IsDirectory)
  848. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  849. .SelectMany(i => directoryService.GetFiles(i.FullName));
  850. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  851. .OfType<Video>()
  852. .Select(item =>
  853. {
  854. // Try to retrieve it from the db. If we don't find it, use the resolved version
  855. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  856. if (dbItem != null)
  857. {
  858. item = dbItem;
  859. }
  860. item.ExtraType = ExtraType.ThemeVideo;
  861. return item;
  862. // Sort them so that the list can be easily compared for changes
  863. }).OrderBy(i => i.Path).ToList();
  864. }
  865. public Task RefreshMetadata(CancellationToken cancellationToken)
  866. {
  867. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken);
  868. }
  869. /// <summary>
  870. /// Overrides the base implementation to refresh metadata for local trailers
  871. /// </summary>
  872. /// <param name="options">The options.</param>
  873. /// <param name="cancellationToken">The cancellation token.</param>
  874. /// <returns>true if a provider reports we changed</returns>
  875. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  876. {
  877. var locationType = LocationType;
  878. var requiresSave = false;
  879. if (SupportsOwnedItems)
  880. {
  881. try
  882. {
  883. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  884. GetFileSystemChildren(options.DirectoryService).ToList() :
  885. new List<FileSystemMetadata>();
  886. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  887. if (ownedItemsChanged)
  888. {
  889. requiresSave = true;
  890. }
  891. }
  892. catch (Exception ex)
  893. {
  894. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  895. }
  896. }
  897. var refreshOptions = requiresSave
  898. ? new MetadataRefreshOptions(options)
  899. {
  900. ForceSave = true
  901. }
  902. : options;
  903. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  904. }
  905. [IgnoreDataMember]
  906. protected virtual bool SupportsOwnedItems
  907. {
  908. get { return IsFolder || GetParent() != null; }
  909. }
  910. [IgnoreDataMember]
  911. public virtual bool SupportsPeople
  912. {
  913. get { return true; }
  914. }
  915. /// <summary>
  916. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  917. /// Returns true or false indicating if changes were found.
  918. /// </summary>
  919. /// <param name="options"></param>
  920. /// <param name="fileSystemChildren"></param>
  921. /// <param name="cancellationToken"></param>
  922. /// <returns></returns>
  923. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  924. {
  925. var themeSongsChanged = false;
  926. var themeVideosChanged = false;
  927. var localTrailersChanged = false;
  928. if (LocationType == LocationType.FileSystem && GetParent() != null)
  929. {
  930. var hasThemeMedia = this as IHasThemeMedia;
  931. if (hasThemeMedia != null)
  932. {
  933. if (!IsInMixedFolder)
  934. {
  935. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  936. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  937. }
  938. }
  939. var hasTrailers = this as IHasTrailers;
  940. if (hasTrailers != null)
  941. {
  942. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  943. }
  944. }
  945. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  946. }
  947. protected virtual IEnumerable<FileSystemMetadata> GetFileSystemChildren(IDirectoryService directoryService)
  948. {
  949. var path = ContainingFolderPath;
  950. return directoryService.GetFileSystemEntries(path);
  951. }
  952. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  953. {
  954. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  955. var newItemIds = newItems.Select(i => i.Id).ToList();
  956. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  957. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  958. await Task.WhenAll(tasks).ConfigureAwait(false);
  959. item.LocalTrailerIds = newItemIds;
  960. return itemsChanged;
  961. }
  962. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  963. {
  964. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  965. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  966. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  967. var tasks = newThemeVideos.Select(i =>
  968. {
  969. var subOptions = new MetadataRefreshOptions(options);
  970. if (!i.IsThemeMedia)
  971. {
  972. i.ExtraType = ExtraType.ThemeVideo;
  973. subOptions.ForceSave = true;
  974. }
  975. return i.RefreshMetadata(subOptions, cancellationToken);
  976. });
  977. await Task.WhenAll(tasks).ConfigureAwait(false);
  978. item.ThemeVideoIds = newThemeVideoIds;
  979. return themeVideosChanged;
  980. }
  981. /// <summary>
  982. /// Refreshes the theme songs.
  983. /// </summary>
  984. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  985. {
  986. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  987. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  988. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  989. var tasks = newThemeSongs.Select(i =>
  990. {
  991. var subOptions = new MetadataRefreshOptions(options);
  992. if (!i.IsThemeMedia)
  993. {
  994. i.ExtraType = ExtraType.ThemeSong;
  995. subOptions.ForceSave = true;
  996. }
  997. return i.RefreshMetadata(subOptions, cancellationToken);
  998. });
  999. await Task.WhenAll(tasks).ConfigureAwait(false);
  1000. item.ThemeSongIds = newThemeSongIds;
  1001. return themeSongsChanged;
  1002. }
  1003. /// <summary>
  1004. /// Gets or sets the provider ids.
  1005. /// </summary>
  1006. /// <value>The provider ids.</value>
  1007. public Dictionary<string, string> ProviderIds { get; set; }
  1008. [IgnoreDataMember]
  1009. public virtual Folder LatestItemsIndexContainer
  1010. {
  1011. get { return null; }
  1012. }
  1013. public virtual string CreatePresentationUniqueKey()
  1014. {
  1015. return Id.ToString("N");
  1016. }
  1017. [IgnoreDataMember]
  1018. public string PresentationUniqueKey { get; set; }
  1019. public string GetPresentationUniqueKey()
  1020. {
  1021. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1022. }
  1023. public virtual bool RequiresRefresh()
  1024. {
  1025. return false;
  1026. }
  1027. public virtual List<string> GetUserDataKeys()
  1028. {
  1029. var list = new List<string>();
  1030. if (SourceType == SourceType.Channel)
  1031. {
  1032. if (!string.IsNullOrWhiteSpace(ExternalId))
  1033. {
  1034. list.Add(ExternalId);
  1035. }
  1036. }
  1037. list.Add(Id.ToString());
  1038. return list;
  1039. }
  1040. internal virtual bool IsValidFromResolver(BaseItem newItem)
  1041. {
  1042. var current = this;
  1043. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  1044. }
  1045. public void AfterMetadataRefresh()
  1046. {
  1047. _sortName = null;
  1048. }
  1049. /// <summary>
  1050. /// Gets the preferred metadata language.
  1051. /// </summary>
  1052. /// <returns>System.String.</returns>
  1053. public string GetPreferredMetadataLanguage()
  1054. {
  1055. string lang = PreferredMetadataLanguage;
  1056. if (string.IsNullOrWhiteSpace(lang))
  1057. {
  1058. lang = GetParents()
  1059. .Select(i => i.PreferredMetadataLanguage)
  1060. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1061. }
  1062. if (string.IsNullOrWhiteSpace(lang))
  1063. {
  1064. lang = LibraryManager.GetCollectionFolders(this)
  1065. .Select(i => i.PreferredMetadataLanguage)
  1066. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1067. }
  1068. if (string.IsNullOrWhiteSpace(lang))
  1069. {
  1070. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1071. }
  1072. return lang;
  1073. }
  1074. /// <summary>
  1075. /// Gets the preferred metadata language.
  1076. /// </summary>
  1077. /// <returns>System.String.</returns>
  1078. public string GetPreferredMetadataCountryCode()
  1079. {
  1080. string lang = PreferredMetadataCountryCode;
  1081. if (string.IsNullOrWhiteSpace(lang))
  1082. {
  1083. lang = GetParents()
  1084. .Select(i => i.PreferredMetadataCountryCode)
  1085. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1086. }
  1087. if (string.IsNullOrWhiteSpace(lang))
  1088. {
  1089. lang = LibraryManager.GetCollectionFolders(this)
  1090. .Select(i => i.PreferredMetadataCountryCode)
  1091. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1092. }
  1093. if (string.IsNullOrWhiteSpace(lang))
  1094. {
  1095. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1096. }
  1097. return lang;
  1098. }
  1099. public virtual bool IsSaveLocalMetadataEnabled()
  1100. {
  1101. if (SourceType == SourceType.Channel)
  1102. {
  1103. return false;
  1104. }
  1105. return ConfigurationManager.Configuration.SaveLocalMeta;
  1106. }
  1107. /// <summary>
  1108. /// Determines if a given user has access to this item
  1109. /// </summary>
  1110. /// <param name="user">The user.</param>
  1111. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1112. /// <exception cref="System.ArgumentNullException">user</exception>
  1113. public bool IsParentalAllowed(User user)
  1114. {
  1115. if (user == null)
  1116. {
  1117. throw new ArgumentNullException("user");
  1118. }
  1119. if (!IsVisibleViaTags(user))
  1120. {
  1121. return false;
  1122. }
  1123. var maxAllowedRating = user.Policy.MaxParentalRating;
  1124. if (maxAllowedRating == null)
  1125. {
  1126. return true;
  1127. }
  1128. var rating = CustomRatingForComparison;
  1129. if (string.IsNullOrWhiteSpace(rating))
  1130. {
  1131. rating = OfficialRatingForComparison;
  1132. }
  1133. if (string.IsNullOrWhiteSpace(rating))
  1134. {
  1135. return !GetBlockUnratedValue(user.Policy);
  1136. }
  1137. var value = LocalizationManager.GetRatingLevel(rating);
  1138. // Could not determine the integer value
  1139. if (!value.HasValue)
  1140. {
  1141. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1142. if (!isAllowed)
  1143. {
  1144. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1145. }
  1146. return isAllowed;
  1147. }
  1148. return value.Value <= maxAllowedRating.Value;
  1149. }
  1150. public int? GetParentalRatingValue()
  1151. {
  1152. var rating = CustomRating;
  1153. if (string.IsNullOrWhiteSpace(rating))
  1154. {
  1155. rating = OfficialRating;
  1156. }
  1157. if (string.IsNullOrWhiteSpace(rating))
  1158. {
  1159. return null;
  1160. }
  1161. return LocalizationManager.GetRatingLevel(rating);
  1162. }
  1163. public int? GetInheritedParentalRatingValue()
  1164. {
  1165. var rating = CustomRatingForComparison;
  1166. if (string.IsNullOrWhiteSpace(rating))
  1167. {
  1168. rating = OfficialRatingForComparison;
  1169. }
  1170. if (string.IsNullOrWhiteSpace(rating))
  1171. {
  1172. return null;
  1173. }
  1174. return LocalizationManager.GetRatingLevel(rating);
  1175. }
  1176. public List<string> GetInheritedTags()
  1177. {
  1178. var list = new List<string>();
  1179. list.AddRange(Tags);
  1180. foreach (var parent in GetParents())
  1181. {
  1182. list.AddRange(parent.Tags);
  1183. }
  1184. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1185. }
  1186. private bool IsVisibleViaTags(User user)
  1187. {
  1188. var policy = user.Policy;
  1189. if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1190. {
  1191. return false;
  1192. }
  1193. return true;
  1194. }
  1195. protected virtual bool IsAllowTagFilterEnforced()
  1196. {
  1197. return true;
  1198. }
  1199. public virtual UnratedItem GetBlockUnratedType()
  1200. {
  1201. if (SourceType == SourceType.Channel)
  1202. {
  1203. return UnratedItem.ChannelContent;
  1204. }
  1205. return UnratedItem.Other;
  1206. }
  1207. /// <summary>
  1208. /// Gets the block unrated value.
  1209. /// </summary>
  1210. /// <param name="config">The configuration.</param>
  1211. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1212. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1213. {
  1214. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1215. // Special folders like series and albums will override this method.
  1216. if (IsFolder)
  1217. {
  1218. return false;
  1219. }
  1220. if (this is IItemByName)
  1221. {
  1222. return false;
  1223. }
  1224. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1225. }
  1226. /// <summary>
  1227. /// Determines if this folder should be visible to a given user.
  1228. /// Default is just parental allowed. Can be overridden for more functionality.
  1229. /// </summary>
  1230. /// <param name="user">The user.</param>
  1231. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1232. /// <exception cref="System.ArgumentNullException">user</exception>
  1233. public virtual bool IsVisible(User user)
  1234. {
  1235. if (user == null)
  1236. {
  1237. throw new ArgumentNullException("user");
  1238. }
  1239. return IsParentalAllowed(user);
  1240. }
  1241. public virtual bool IsVisibleStandalone(User user)
  1242. {
  1243. if (SourceType == SourceType.Channel)
  1244. {
  1245. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1246. }
  1247. return IsVisibleStandaloneInternal(user, true);
  1248. }
  1249. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1250. {
  1251. if (!IsVisible(user))
  1252. {
  1253. return false;
  1254. }
  1255. if (GetParents().Any(i => !i.IsVisible(user)))
  1256. {
  1257. return false;
  1258. }
  1259. if (checkFolders)
  1260. {
  1261. var topParent = GetParents().LastOrDefault() ?? this;
  1262. if (string.IsNullOrWhiteSpace(topParent.Path))
  1263. {
  1264. return true;
  1265. }
  1266. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1267. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1268. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1269. {
  1270. return false;
  1271. }
  1272. }
  1273. return true;
  1274. }
  1275. /// <summary>
  1276. /// Gets a value indicating whether this instance is folder.
  1277. /// </summary>
  1278. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1279. [IgnoreDataMember]
  1280. public virtual bool IsFolder
  1281. {
  1282. get
  1283. {
  1284. return false;
  1285. }
  1286. }
  1287. public virtual string GetClientTypeName()
  1288. {
  1289. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1290. {
  1291. return "ChannelFolderItem";
  1292. }
  1293. return GetType().Name;
  1294. }
  1295. /// <summary>
  1296. /// Gets the linked child.
  1297. /// </summary>
  1298. /// <param name="info">The info.</param>
  1299. /// <returns>BaseItem.</returns>
  1300. protected BaseItem GetLinkedChild(LinkedChild info)
  1301. {
  1302. // First get using the cached Id
  1303. if (info.ItemId.HasValue)
  1304. {
  1305. if (info.ItemId.Value == Guid.Empty)
  1306. {
  1307. return null;
  1308. }
  1309. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1310. if (itemById != null)
  1311. {
  1312. return itemById;
  1313. }
  1314. }
  1315. var item = FindLinkedChild(info);
  1316. // If still null, log
  1317. if (item == null)
  1318. {
  1319. // Don't keep searching over and over
  1320. info.ItemId = Guid.Empty;
  1321. }
  1322. else
  1323. {
  1324. // Cache the id for next time
  1325. info.ItemId = item.Id;
  1326. }
  1327. return item;
  1328. }
  1329. private BaseItem FindLinkedChild(LinkedChild info)
  1330. {
  1331. if (!string.IsNullOrEmpty(info.Path))
  1332. {
  1333. var itemByPath = LibraryManager.FindByPath(info.Path, null);
  1334. if (itemByPath == null)
  1335. {
  1336. //Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1337. }
  1338. return itemByPath;
  1339. }
  1340. return null;
  1341. }
  1342. [IgnoreDataMember]
  1343. public virtual bool EnableRememberingTrackSelections
  1344. {
  1345. get
  1346. {
  1347. return true;
  1348. }
  1349. }
  1350. /// <summary>
  1351. /// Adds a studio to the item
  1352. /// </summary>
  1353. /// <param name="name">The name.</param>
  1354. /// <exception cref="System.ArgumentNullException"></exception>
  1355. public void AddStudio(string name)
  1356. {
  1357. if (string.IsNullOrWhiteSpace(name))
  1358. {
  1359. throw new ArgumentNullException("name");
  1360. }
  1361. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1362. {
  1363. Studios.Add(name);
  1364. }
  1365. }
  1366. /// <summary>
  1367. /// Adds a genre to the item
  1368. /// </summary>
  1369. /// <param name="name">The name.</param>
  1370. /// <exception cref="System.ArgumentNullException"></exception>
  1371. public void AddGenre(string name)
  1372. {
  1373. if (string.IsNullOrWhiteSpace(name))
  1374. {
  1375. throw new ArgumentNullException("name");
  1376. }
  1377. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1378. {
  1379. Genres.Add(name);
  1380. }
  1381. }
  1382. /// <summary>
  1383. /// Marks the played.
  1384. /// </summary>
  1385. /// <param name="user">The user.</param>
  1386. /// <param name="datePlayed">The date played.</param>
  1387. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1388. /// <returns>Task.</returns>
  1389. /// <exception cref="System.ArgumentNullException"></exception>
  1390. public virtual async Task MarkPlayed(User user,
  1391. DateTime? datePlayed,
  1392. bool resetPosition)
  1393. {
  1394. if (user == null)
  1395. {
  1396. throw new ArgumentNullException();
  1397. }
  1398. var data = UserDataManager.GetUserData(user, this);
  1399. if (datePlayed.HasValue)
  1400. {
  1401. // Increment
  1402. data.PlayCount++;
  1403. }
  1404. // Ensure it's at least one
  1405. data.PlayCount = Math.Max(data.PlayCount, 1);
  1406. if (resetPosition)
  1407. {
  1408. data.PlaybackPositionTicks = 0;
  1409. }
  1410. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1411. data.Played = true;
  1412. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1413. }
  1414. /// <summary>
  1415. /// Marks the unplayed.
  1416. /// </summary>
  1417. /// <param name="user">The user.</param>
  1418. /// <returns>Task.</returns>
  1419. /// <exception cref="System.ArgumentNullException"></exception>
  1420. public virtual async Task MarkUnplayed(User user)
  1421. {
  1422. if (user == null)
  1423. {
  1424. throw new ArgumentNullException();
  1425. }
  1426. var data = UserDataManager.GetUserData(user, this);
  1427. //I think it is okay to do this here.
  1428. // if this is only called when a user is manually forcing something to un-played
  1429. // then it probably is what we want to do...
  1430. data.PlayCount = 0;
  1431. data.PlaybackPositionTicks = 0;
  1432. data.LastPlayedDate = null;
  1433. data.Played = false;
  1434. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1435. }
  1436. /// <summary>
  1437. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1438. /// </summary>
  1439. /// <returns>Task.</returns>
  1440. public virtual Task ChangedExternally()
  1441. {
  1442. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1443. return Task.FromResult(true);
  1444. }
  1445. /// <summary>
  1446. /// Gets an image
  1447. /// </summary>
  1448. /// <param name="type">The type.</param>
  1449. /// <param name="imageIndex">Index of the image.</param>
  1450. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1451. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1452. public bool HasImage(ImageType type, int imageIndex)
  1453. {
  1454. return GetImageInfo(type, imageIndex) != null;
  1455. }
  1456. public void SetImage(ItemImageInfo image, int index)
  1457. {
  1458. if (image.Type == ImageType.Chapter)
  1459. {
  1460. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1461. }
  1462. var existingImage = GetImageInfo(image.Type, index);
  1463. if (existingImage != null)
  1464. {
  1465. ImageInfos.Remove(existingImage);
  1466. }
  1467. ImageInfos.Add(image);
  1468. }
  1469. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1470. {
  1471. if (type == ImageType.Chapter)
  1472. {
  1473. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1474. }
  1475. var image = GetImageInfo(type, index);
  1476. if (image == null)
  1477. {
  1478. ImageInfos.Add(GetImageInfo(file, type));
  1479. }
  1480. else
  1481. {
  1482. var imageInfo = GetImageInfo(file, type);
  1483. image.Path = file.FullName;
  1484. image.DateModified = imageInfo.DateModified;
  1485. image.IsPlaceholder = false;
  1486. }
  1487. }
  1488. /// <summary>
  1489. /// Deletes the image.
  1490. /// </summary>
  1491. /// <param name="type">The type.</param>
  1492. /// <param name="index">The index.</param>
  1493. /// <returns>Task.</returns>
  1494. public Task DeleteImage(ImageType type, int index)
  1495. {
  1496. var info = GetImageInfo(type, index);
  1497. if (info == null)
  1498. {
  1499. // Nothing to do
  1500. return Task.FromResult(true);
  1501. }
  1502. // Remove it from the item
  1503. RemoveImage(info);
  1504. if (info.IsLocalFile)
  1505. {
  1506. // Delete the source file
  1507. var currentFile = new FileInfo(info.Path);
  1508. // Deletion will fail if the file is hidden so remove the attribute first
  1509. if (currentFile.Exists)
  1510. {
  1511. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1512. {
  1513. currentFile.Attributes &= ~FileAttributes.Hidden;
  1514. }
  1515. FileSystem.DeleteFile(currentFile.FullName);
  1516. }
  1517. }
  1518. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1519. }
  1520. public void RemoveImage(ItemImageInfo image)
  1521. {
  1522. ImageInfos.Remove(image);
  1523. }
  1524. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1525. {
  1526. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1527. }
  1528. /// <summary>
  1529. /// Validates that images within the item are still on the file system
  1530. /// </summary>
  1531. public bool ValidateImages(IDirectoryService directoryService)
  1532. {
  1533. var allFiles = ImageInfos
  1534. .Where(i => i.IsLocalFile)
  1535. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1536. .Distinct(StringComparer.OrdinalIgnoreCase)
  1537. .SelectMany(directoryService.GetFiles)
  1538. .Select(i => i.FullName)
  1539. .ToList();
  1540. var deletedImages = ImageInfos
  1541. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1542. .ToList();
  1543. if (deletedImages.Count > 0)
  1544. {
  1545. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1546. }
  1547. return deletedImages.Count > 0;
  1548. }
  1549. /// <summary>
  1550. /// Gets the image path.
  1551. /// </summary>
  1552. /// <param name="imageType">Type of the image.</param>
  1553. /// <param name="imageIndex">Index of the image.</param>
  1554. /// <returns>System.String.</returns>
  1555. /// <exception cref="System.InvalidOperationException">
  1556. /// </exception>
  1557. /// <exception cref="System.ArgumentNullException">item</exception>
  1558. public string GetImagePath(ImageType imageType, int imageIndex)
  1559. {
  1560. var info = GetImageInfo(imageType, imageIndex);
  1561. return info == null ? null : info.Path;
  1562. }
  1563. /// <summary>
  1564. /// Gets the image information.
  1565. /// </summary>
  1566. /// <param name="imageType">Type of the image.</param>
  1567. /// <param name="imageIndex">Index of the image.</param>
  1568. /// <returns>ItemImageInfo.</returns>
  1569. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1570. {
  1571. if (imageType == ImageType.Chapter)
  1572. {
  1573. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1574. if (chapter == null)
  1575. {
  1576. return null;
  1577. }
  1578. var path = chapter.ImagePath;
  1579. if (string.IsNullOrWhiteSpace(path))
  1580. {
  1581. return null;
  1582. }
  1583. return new ItemImageInfo
  1584. {
  1585. Path = path,
  1586. DateModified = chapter.ImageDateModified,
  1587. Type = imageType
  1588. };
  1589. }
  1590. return GetImages(imageType)
  1591. .ElementAtOrDefault(imageIndex);
  1592. }
  1593. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1594. {
  1595. if (imageType == ImageType.Chapter)
  1596. {
  1597. throw new ArgumentException("No image info for chapter images");
  1598. }
  1599. return ImageInfos.Where(i => i.Type == imageType);
  1600. }
  1601. /// <summary>
  1602. /// Adds the images.
  1603. /// </summary>
  1604. /// <param name="imageType">Type of the image.</param>
  1605. /// <param name="images">The images.</param>
  1606. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1607. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1608. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1609. {
  1610. if (imageType == ImageType.Chapter)
  1611. {
  1612. throw new ArgumentException("Cannot call AddImages with chapter images");
  1613. }
  1614. var existingImages = GetImages(imageType)
  1615. .ToList();
  1616. var newImageList = new List<FileSystemMetadata>();
  1617. var imageAdded = false;
  1618. foreach (var newImage in images)
  1619. {
  1620. if (newImage == null)
  1621. {
  1622. throw new ArgumentException("null image found in list");
  1623. }
  1624. var existing = existingImages
  1625. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1626. if (existing == null)
  1627. {
  1628. newImageList.Add(newImage);
  1629. imageAdded = true;
  1630. }
  1631. else
  1632. {
  1633. if (existing.IsLocalFile)
  1634. {
  1635. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1636. }
  1637. }
  1638. }
  1639. if (imageAdded || images.Count != existingImages.Count)
  1640. {
  1641. var newImagePaths = images.Select(i => i.FullName).ToList();
  1642. var deleted = existingImages
  1643. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1644. .ToList();
  1645. ImageInfos = ImageInfos.Except(deleted).ToList();
  1646. }
  1647. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1648. return newImageList.Count > 0;
  1649. }
  1650. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1651. {
  1652. return new ItemImageInfo
  1653. {
  1654. Path = file.FullName,
  1655. Type = type,
  1656. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1657. };
  1658. }
  1659. /// <summary>
  1660. /// Gets the file system path to delete when the item is to be deleted
  1661. /// </summary>
  1662. /// <returns></returns>
  1663. public virtual IEnumerable<string> GetDeletePaths()
  1664. {
  1665. return new[] { Path };
  1666. }
  1667. public bool AllowsMultipleImages(ImageType type)
  1668. {
  1669. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1670. }
  1671. public Task SwapImages(ImageType type, int index1, int index2)
  1672. {
  1673. if (!AllowsMultipleImages(type))
  1674. {
  1675. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1676. }
  1677. var info1 = GetImageInfo(type, index1);
  1678. var info2 = GetImageInfo(type, index2);
  1679. if (info1 == null || info2 == null)
  1680. {
  1681. // Nothing to do
  1682. return Task.FromResult(true);
  1683. }
  1684. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1685. {
  1686. // TODO: Not supported yet
  1687. return Task.FromResult(true);
  1688. }
  1689. var path1 = info1.Path;
  1690. var path2 = info2.Path;
  1691. FileSystem.SwapFiles(path1, path2);
  1692. // Refresh these values
  1693. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1694. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1695. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1696. }
  1697. public virtual bool IsPlayed(User user)
  1698. {
  1699. var userdata = UserDataManager.GetUserData(user, this);
  1700. return userdata != null && userdata.Played;
  1701. }
  1702. public bool IsFavoriteOrLiked(User user)
  1703. {
  1704. var userdata = UserDataManager.GetUserData(user, this);
  1705. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1706. }
  1707. public virtual bool IsUnplayed(User user)
  1708. {
  1709. if (user == null)
  1710. {
  1711. throw new ArgumentNullException("user");
  1712. }
  1713. var userdata = UserDataManager.GetUserData(user, this);
  1714. return userdata == null || !userdata.Played;
  1715. }
  1716. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1717. {
  1718. return GetItemLookupInfo<ItemLookupInfo>();
  1719. }
  1720. protected T GetItemLookupInfo<T>()
  1721. where T : ItemLookupInfo, new()
  1722. {
  1723. return new T
  1724. {
  1725. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1726. MetadataLanguage = GetPreferredMetadataLanguage(),
  1727. Name = Name,
  1728. ProviderIds = ProviderIds,
  1729. IndexNumber = IndexNumber,
  1730. ParentIndexNumber = ParentIndexNumber,
  1731. Year = ProductionYear,
  1732. PremiereDate = PremiereDate
  1733. };
  1734. }
  1735. /// <summary>
  1736. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1737. /// </summary>
  1738. public virtual bool BeforeMetadataRefresh()
  1739. {
  1740. _sortName = null;
  1741. var hasChanges = false;
  1742. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1743. {
  1744. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1745. hasChanges = true;
  1746. }
  1747. return hasChanges;
  1748. }
  1749. protected static string GetMappedPath(string path, LocationType locationType)
  1750. {
  1751. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1752. {
  1753. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1754. {
  1755. path = LibraryManager.SubstitutePath(path, map.From, map.To);
  1756. }
  1757. }
  1758. return path;
  1759. }
  1760. public virtual Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1761. {
  1762. if (RunTimeTicks.HasValue)
  1763. {
  1764. double pct = RunTimeTicks.Value;
  1765. if (pct > 0)
  1766. {
  1767. pct = userData.PlaybackPositionTicks / pct;
  1768. if (pct > 0)
  1769. {
  1770. dto.PlayedPercentage = 100 * pct;
  1771. }
  1772. }
  1773. }
  1774. return Task.FromResult(true);
  1775. }
  1776. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1777. {
  1778. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1779. {
  1780. ImageRefreshMode = options.ImageRefreshMode,
  1781. MetadataRefreshMode = options.MetadataRefreshMode,
  1782. ReplaceAllMetadata = options.ReplaceAllMetadata
  1783. };
  1784. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1785. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1786. var video = LibraryManager.GetItemById(id) as Video;
  1787. if (video == null)
  1788. {
  1789. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1790. newOptions.ForceSave = true;
  1791. }
  1792. if (video == null)
  1793. {
  1794. return Task.FromResult(true);
  1795. }
  1796. return video.RefreshMetadata(newOptions, cancellationToken);
  1797. }
  1798. public string GetEtag(User user)
  1799. {
  1800. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1801. }
  1802. protected virtual List<string> GetEtagValues(User user)
  1803. {
  1804. return new List<string>
  1805. {
  1806. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1807. };
  1808. }
  1809. public virtual IEnumerable<Guid> GetAncestorIds()
  1810. {
  1811. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1812. }
  1813. public BaseItem GetTopParent()
  1814. {
  1815. if (IsTopParent)
  1816. {
  1817. return this;
  1818. }
  1819. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1820. }
  1821. [IgnoreDataMember]
  1822. public virtual bool IsTopParent
  1823. {
  1824. get
  1825. {
  1826. if (GetParent() is AggregateFolder || this is BasePluginFolder || this is Channel)
  1827. {
  1828. return true;
  1829. }
  1830. var view = this as UserView;
  1831. if (view != null && string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1832. {
  1833. return true;
  1834. }
  1835. if (view != null && string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1836. {
  1837. return true;
  1838. }
  1839. return false;
  1840. }
  1841. }
  1842. [IgnoreDataMember]
  1843. public virtual bool SupportsAncestors
  1844. {
  1845. get
  1846. {
  1847. return true;
  1848. }
  1849. }
  1850. [IgnoreDataMember]
  1851. public virtual bool StopRefreshIfLocalMetadataFound
  1852. {
  1853. get
  1854. {
  1855. return true;
  1856. }
  1857. }
  1858. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1859. {
  1860. return new[] { Id };
  1861. }
  1862. public virtual Task Delete(DeleteOptions options)
  1863. {
  1864. return LibraryManager.DeleteItem(this, options);
  1865. }
  1866. public virtual Task OnFileDeleted()
  1867. {
  1868. // Remove from database
  1869. return Delete(new DeleteOptions
  1870. {
  1871. DeleteFileLocation = false
  1872. });
  1873. }
  1874. public virtual List<ExternalUrl> GetRelatedUrls()
  1875. {
  1876. return new List<ExternalUrl>();
  1877. }
  1878. }
  1879. }