BaseItem.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266
  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. [IgnoreDataMember]
  670. public int InheritedParentalRatingValue { get; set; }
  671. /// <summary>
  672. /// Gets or sets the critic rating.
  673. /// </summary>
  674. /// <value>The critic rating.</value>
  675. [IgnoreDataMember]
  676. public float? CriticRating { get; set; }
  677. /// <summary>
  678. /// Gets or sets the critic rating summary.
  679. /// </summary>
  680. /// <value>The critic rating summary.</value>
  681. [IgnoreDataMember]
  682. public string CriticRatingSummary { get; set; }
  683. /// <summary>
  684. /// Gets or sets the official rating description.
  685. /// </summary>
  686. /// <value>The official rating description.</value>
  687. [IgnoreDataMember]
  688. public string OfficialRatingDescription { get; set; }
  689. /// <summary>
  690. /// Gets or sets the custom rating.
  691. /// </summary>
  692. /// <value>The custom rating.</value>
  693. [IgnoreDataMember]
  694. public string CustomRating { get; set; }
  695. /// <summary>
  696. /// Gets or sets the overview.
  697. /// </summary>
  698. /// <value>The overview.</value>
  699. [IgnoreDataMember]
  700. public string Overview { get; set; }
  701. /// <summary>
  702. /// Gets or sets the studios.
  703. /// </summary>
  704. /// <value>The studios.</value>
  705. [IgnoreDataMember]
  706. public List<string> Studios { get; set; }
  707. /// <summary>
  708. /// Gets or sets the genres.
  709. /// </summary>
  710. /// <value>The genres.</value>
  711. [IgnoreDataMember]
  712. public List<string> Genres { get; set; }
  713. /// <summary>
  714. /// Gets or sets the tags.
  715. /// </summary>
  716. /// <value>The tags.</value>
  717. [IgnoreDataMember]
  718. public List<string> Tags { get; set; }
  719. public List<string> Keywords { get; set; }
  720. /// <summary>
  721. /// Gets or sets the home page URL.
  722. /// </summary>
  723. /// <value>The home page URL.</value>
  724. [IgnoreDataMember]
  725. public string HomePageUrl { get; set; }
  726. /// <summary>
  727. /// Gets or sets the community rating.
  728. /// </summary>
  729. /// <value>The community rating.</value>
  730. [IgnoreDataMember]
  731. public float? CommunityRating { get; set; }
  732. /// <summary>
  733. /// Gets or sets the community rating vote count.
  734. /// </summary>
  735. /// <value>The community rating vote count.</value>
  736. [IgnoreDataMember]
  737. public int? VoteCount { get; set; }
  738. /// <summary>
  739. /// Gets or sets the run time ticks.
  740. /// </summary>
  741. /// <value>The run time ticks.</value>
  742. [IgnoreDataMember]
  743. public long? RunTimeTicks { get; set; }
  744. /// <summary>
  745. /// Gets or sets the production year.
  746. /// </summary>
  747. /// <value>The production year.</value>
  748. [IgnoreDataMember]
  749. public int? ProductionYear { get; set; }
  750. /// <summary>
  751. /// If the item is part of a series, this is it's number in the series.
  752. /// This could be episode number, album track number, etc.
  753. /// </summary>
  754. /// <value>The index number.</value>
  755. [IgnoreDataMember]
  756. public int? IndexNumber { get; set; }
  757. /// <summary>
  758. /// For an episode this could be the season number, or for a song this could be the disc number.
  759. /// </summary>
  760. /// <value>The parent index number.</value>
  761. [IgnoreDataMember]
  762. public int? ParentIndexNumber { get; set; }
  763. [IgnoreDataMember]
  764. public string OfficialRatingForComparison
  765. {
  766. get
  767. {
  768. if (!string.IsNullOrWhiteSpace(OfficialRating))
  769. {
  770. return OfficialRating;
  771. }
  772. var parent = DisplayParent;
  773. if (parent != null)
  774. {
  775. return parent.OfficialRatingForComparison;
  776. }
  777. return null;
  778. }
  779. }
  780. [IgnoreDataMember]
  781. public string CustomRatingForComparison
  782. {
  783. get
  784. {
  785. if (!string.IsNullOrWhiteSpace(CustomRating))
  786. {
  787. return CustomRating;
  788. }
  789. var parent = DisplayParent;
  790. if (parent != null)
  791. {
  792. return parent.CustomRatingForComparison;
  793. }
  794. return null;
  795. }
  796. }
  797. /// <summary>
  798. /// Gets the play access.
  799. /// </summary>
  800. /// <param name="user">The user.</param>
  801. /// <returns>PlayAccess.</returns>
  802. public PlayAccess GetPlayAccess(User user)
  803. {
  804. if (!user.Policy.EnableMediaPlayback)
  805. {
  806. return PlayAccess.None;
  807. }
  808. //if (!user.IsParentalScheduleAllowed())
  809. //{
  810. // return PlayAccess.None;
  811. //}
  812. return PlayAccess.Full;
  813. }
  814. /// <summary>
  815. /// Loads the theme songs.
  816. /// </summary>
  817. /// <returns>List{Audio.Audio}.</returns>
  818. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  819. {
  820. var files = fileSystemChildren.Where(i => i.IsDirectory)
  821. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  822. .SelectMany(i => directoryService.GetFiles(i.FullName))
  823. .ToList();
  824. // Support plex/xbmc convention
  825. files.AddRange(fileSystemChildren
  826. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  827. );
  828. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  829. .OfType<Audio.Audio>()
  830. .Select(audio =>
  831. {
  832. // Try to retrieve it from the db. If we don't find it, use the resolved version
  833. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  834. if (dbItem != null)
  835. {
  836. audio = dbItem;
  837. }
  838. audio.ExtraType = ExtraType.ThemeSong;
  839. return audio;
  840. // Sort them so that the list can be easily compared for changes
  841. }).OrderBy(i => i.Path).ToList();
  842. }
  843. /// <summary>
  844. /// Loads the video backdrops.
  845. /// </summary>
  846. /// <returns>List{Video}.</returns>
  847. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  848. {
  849. var files = fileSystemChildren.Where(i => i.IsDirectory)
  850. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  851. .SelectMany(i => directoryService.GetFiles(i.FullName));
  852. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  853. .OfType<Video>()
  854. .Select(item =>
  855. {
  856. // Try to retrieve it from the db. If we don't find it, use the resolved version
  857. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  858. if (dbItem != null)
  859. {
  860. item = dbItem;
  861. }
  862. item.ExtraType = ExtraType.ThemeVideo;
  863. return item;
  864. // Sort them so that the list can be easily compared for changes
  865. }).OrderBy(i => i.Path).ToList();
  866. }
  867. public Task RefreshMetadata(CancellationToken cancellationToken)
  868. {
  869. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken);
  870. }
  871. /// <summary>
  872. /// Overrides the base implementation to refresh metadata for local trailers
  873. /// </summary>
  874. /// <param name="options">The options.</param>
  875. /// <param name="cancellationToken">The cancellation token.</param>
  876. /// <returns>true if a provider reports we changed</returns>
  877. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  878. {
  879. var locationType = LocationType;
  880. var requiresSave = false;
  881. if (SupportsOwnedItems)
  882. {
  883. try
  884. {
  885. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  886. GetFileSystemChildren(options.DirectoryService).ToList() :
  887. new List<FileSystemMetadata>();
  888. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  889. if (ownedItemsChanged)
  890. {
  891. requiresSave = true;
  892. }
  893. }
  894. catch (Exception ex)
  895. {
  896. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  897. }
  898. }
  899. var refreshOptions = requiresSave
  900. ? new MetadataRefreshOptions(options)
  901. {
  902. ForceSave = true
  903. }
  904. : options;
  905. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  906. }
  907. [IgnoreDataMember]
  908. protected virtual bool SupportsOwnedItems
  909. {
  910. get { return IsFolder || GetParent() != null; }
  911. }
  912. [IgnoreDataMember]
  913. public virtual bool SupportsPeople
  914. {
  915. get { return true; }
  916. }
  917. /// <summary>
  918. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  919. /// Returns true or false indicating if changes were found.
  920. /// </summary>
  921. /// <param name="options"></param>
  922. /// <param name="fileSystemChildren"></param>
  923. /// <param name="cancellationToken"></param>
  924. /// <returns></returns>
  925. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  926. {
  927. var themeSongsChanged = false;
  928. var themeVideosChanged = false;
  929. var localTrailersChanged = false;
  930. if (LocationType == LocationType.FileSystem && GetParent() != null)
  931. {
  932. var hasThemeMedia = this as IHasThemeMedia;
  933. if (hasThemeMedia != null)
  934. {
  935. if (!IsInMixedFolder)
  936. {
  937. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  938. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  939. }
  940. }
  941. var hasTrailers = this as IHasTrailers;
  942. if (hasTrailers != null)
  943. {
  944. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  945. }
  946. }
  947. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  948. }
  949. protected virtual IEnumerable<FileSystemMetadata> GetFileSystemChildren(IDirectoryService directoryService)
  950. {
  951. var path = ContainingFolderPath;
  952. return directoryService.GetFileSystemEntries(path);
  953. }
  954. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  955. {
  956. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  957. var newItemIds = newItems.Select(i => i.Id).ToList();
  958. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  959. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  960. await Task.WhenAll(tasks).ConfigureAwait(false);
  961. item.LocalTrailerIds = newItemIds;
  962. return itemsChanged;
  963. }
  964. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  965. {
  966. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  967. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  968. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  969. var tasks = newThemeVideos.Select(i =>
  970. {
  971. var subOptions = new MetadataRefreshOptions(options);
  972. if (!i.IsThemeMedia)
  973. {
  974. i.ExtraType = ExtraType.ThemeVideo;
  975. subOptions.ForceSave = true;
  976. }
  977. return i.RefreshMetadata(subOptions, cancellationToken);
  978. });
  979. await Task.WhenAll(tasks).ConfigureAwait(false);
  980. item.ThemeVideoIds = newThemeVideoIds;
  981. return themeVideosChanged;
  982. }
  983. /// <summary>
  984. /// Refreshes the theme songs.
  985. /// </summary>
  986. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  987. {
  988. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  989. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  990. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  991. var tasks = newThemeSongs.Select(i =>
  992. {
  993. var subOptions = new MetadataRefreshOptions(options);
  994. if (!i.IsThemeMedia)
  995. {
  996. i.ExtraType = ExtraType.ThemeSong;
  997. subOptions.ForceSave = true;
  998. }
  999. return i.RefreshMetadata(subOptions, cancellationToken);
  1000. });
  1001. await Task.WhenAll(tasks).ConfigureAwait(false);
  1002. item.ThemeSongIds = newThemeSongIds;
  1003. return themeSongsChanged;
  1004. }
  1005. /// <summary>
  1006. /// Gets or sets the provider ids.
  1007. /// </summary>
  1008. /// <value>The provider ids.</value>
  1009. public Dictionary<string, string> ProviderIds { get; set; }
  1010. [IgnoreDataMember]
  1011. public virtual Folder LatestItemsIndexContainer
  1012. {
  1013. get { return null; }
  1014. }
  1015. public virtual string CreatePresentationUniqueKey()
  1016. {
  1017. return Id.ToString("N");
  1018. }
  1019. [IgnoreDataMember]
  1020. public string PresentationUniqueKey { get; set; }
  1021. public string GetPresentationUniqueKey()
  1022. {
  1023. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1024. }
  1025. public virtual bool RequiresRefresh()
  1026. {
  1027. return false;
  1028. }
  1029. public virtual List<string> GetUserDataKeys()
  1030. {
  1031. var list = new List<string>();
  1032. if (SourceType == SourceType.Channel)
  1033. {
  1034. if (!string.IsNullOrWhiteSpace(ExternalId))
  1035. {
  1036. list.Add(ExternalId);
  1037. }
  1038. }
  1039. list.Add(Id.ToString());
  1040. return list;
  1041. }
  1042. internal virtual bool IsValidFromResolver(BaseItem newItem)
  1043. {
  1044. var current = this;
  1045. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  1046. }
  1047. public void AfterMetadataRefresh()
  1048. {
  1049. _sortName = null;
  1050. }
  1051. /// <summary>
  1052. /// Gets the preferred metadata language.
  1053. /// </summary>
  1054. /// <returns>System.String.</returns>
  1055. public string GetPreferredMetadataLanguage()
  1056. {
  1057. string lang = PreferredMetadataLanguage;
  1058. if (string.IsNullOrWhiteSpace(lang))
  1059. {
  1060. lang = GetParents()
  1061. .Select(i => i.PreferredMetadataLanguage)
  1062. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1063. }
  1064. if (string.IsNullOrWhiteSpace(lang))
  1065. {
  1066. lang = LibraryManager.GetCollectionFolders(this)
  1067. .Select(i => i.PreferredMetadataLanguage)
  1068. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1069. }
  1070. if (string.IsNullOrWhiteSpace(lang))
  1071. {
  1072. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1073. }
  1074. return lang;
  1075. }
  1076. /// <summary>
  1077. /// Gets the preferred metadata language.
  1078. /// </summary>
  1079. /// <returns>System.String.</returns>
  1080. public string GetPreferredMetadataCountryCode()
  1081. {
  1082. string lang = PreferredMetadataCountryCode;
  1083. if (string.IsNullOrWhiteSpace(lang))
  1084. {
  1085. lang = GetParents()
  1086. .Select(i => i.PreferredMetadataCountryCode)
  1087. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1088. }
  1089. if (string.IsNullOrWhiteSpace(lang))
  1090. {
  1091. lang = LibraryManager.GetCollectionFolders(this)
  1092. .Select(i => i.PreferredMetadataCountryCode)
  1093. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  1094. }
  1095. if (string.IsNullOrWhiteSpace(lang))
  1096. {
  1097. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1098. }
  1099. return lang;
  1100. }
  1101. public virtual bool IsSaveLocalMetadataEnabled()
  1102. {
  1103. if (SourceType == SourceType.Channel)
  1104. {
  1105. return false;
  1106. }
  1107. return ConfigurationManager.Configuration.SaveLocalMeta;
  1108. }
  1109. /// <summary>
  1110. /// Determines if a given user has access to this item
  1111. /// </summary>
  1112. /// <param name="user">The user.</param>
  1113. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1114. /// <exception cref="System.ArgumentNullException">user</exception>
  1115. public bool IsParentalAllowed(User user)
  1116. {
  1117. if (user == null)
  1118. {
  1119. throw new ArgumentNullException("user");
  1120. }
  1121. if (!IsVisibleViaTags(user))
  1122. {
  1123. return false;
  1124. }
  1125. var maxAllowedRating = user.Policy.MaxParentalRating;
  1126. if (maxAllowedRating == null)
  1127. {
  1128. return true;
  1129. }
  1130. var rating = CustomRatingForComparison;
  1131. if (string.IsNullOrWhiteSpace(rating))
  1132. {
  1133. rating = OfficialRatingForComparison;
  1134. }
  1135. if (string.IsNullOrWhiteSpace(rating))
  1136. {
  1137. return !GetBlockUnratedValue(user.Policy);
  1138. }
  1139. var value = LocalizationManager.GetRatingLevel(rating);
  1140. // Could not determine the integer value
  1141. if (!value.HasValue)
  1142. {
  1143. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1144. if (!isAllowed)
  1145. {
  1146. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1147. }
  1148. return isAllowed;
  1149. }
  1150. return value.Value <= maxAllowedRating.Value;
  1151. }
  1152. public int? GetParentalRatingValue()
  1153. {
  1154. var rating = CustomRating;
  1155. if (string.IsNullOrWhiteSpace(rating))
  1156. {
  1157. rating = OfficialRating;
  1158. }
  1159. if (string.IsNullOrWhiteSpace(rating))
  1160. {
  1161. return null;
  1162. }
  1163. return LocalizationManager.GetRatingLevel(rating);
  1164. }
  1165. public int? GetInheritedParentalRatingValue()
  1166. {
  1167. var rating = CustomRatingForComparison;
  1168. if (string.IsNullOrWhiteSpace(rating))
  1169. {
  1170. rating = OfficialRatingForComparison;
  1171. }
  1172. if (string.IsNullOrWhiteSpace(rating))
  1173. {
  1174. return null;
  1175. }
  1176. return LocalizationManager.GetRatingLevel(rating);
  1177. }
  1178. public List<string> GetInheritedTags()
  1179. {
  1180. var list = new List<string>();
  1181. list.AddRange(Tags);
  1182. foreach (var parent in GetParents())
  1183. {
  1184. list.AddRange(parent.Tags);
  1185. }
  1186. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1187. }
  1188. private bool IsVisibleViaTags(User user)
  1189. {
  1190. var policy = user.Policy;
  1191. if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1192. {
  1193. return false;
  1194. }
  1195. return true;
  1196. }
  1197. protected virtual bool IsAllowTagFilterEnforced()
  1198. {
  1199. return true;
  1200. }
  1201. public virtual UnratedItem GetBlockUnratedType()
  1202. {
  1203. if (SourceType == SourceType.Channel)
  1204. {
  1205. return UnratedItem.ChannelContent;
  1206. }
  1207. return UnratedItem.Other;
  1208. }
  1209. /// <summary>
  1210. /// Gets the block unrated value.
  1211. /// </summary>
  1212. /// <param name="config">The configuration.</param>
  1213. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1214. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1215. {
  1216. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1217. // Special folders like series and albums will override this method.
  1218. if (IsFolder)
  1219. {
  1220. return false;
  1221. }
  1222. if (this is IItemByName)
  1223. {
  1224. return false;
  1225. }
  1226. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1227. }
  1228. /// <summary>
  1229. /// Determines if this folder should be visible to a given user.
  1230. /// Default is just parental allowed. Can be overridden for more functionality.
  1231. /// </summary>
  1232. /// <param name="user">The user.</param>
  1233. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1234. /// <exception cref="System.ArgumentNullException">user</exception>
  1235. public virtual bool IsVisible(User user)
  1236. {
  1237. if (user == null)
  1238. {
  1239. throw new ArgumentNullException("user");
  1240. }
  1241. return IsParentalAllowed(user);
  1242. }
  1243. public virtual bool IsVisibleStandalone(User user)
  1244. {
  1245. if (SourceType == SourceType.Channel)
  1246. {
  1247. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1248. }
  1249. return IsVisibleStandaloneInternal(user, true);
  1250. }
  1251. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1252. {
  1253. if (!IsVisible(user))
  1254. {
  1255. return false;
  1256. }
  1257. if (GetParents().Any(i => !i.IsVisible(user)))
  1258. {
  1259. return false;
  1260. }
  1261. if (checkFolders)
  1262. {
  1263. var topParent = GetParents().LastOrDefault() ?? this;
  1264. if (string.IsNullOrWhiteSpace(topParent.Path))
  1265. {
  1266. return true;
  1267. }
  1268. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1269. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1270. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1271. {
  1272. return false;
  1273. }
  1274. }
  1275. return true;
  1276. }
  1277. /// <summary>
  1278. /// Gets a value indicating whether this instance is folder.
  1279. /// </summary>
  1280. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1281. [IgnoreDataMember]
  1282. public virtual bool IsFolder
  1283. {
  1284. get
  1285. {
  1286. return false;
  1287. }
  1288. }
  1289. public virtual string GetClientTypeName()
  1290. {
  1291. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1292. {
  1293. return "ChannelFolderItem";
  1294. }
  1295. return GetType().Name;
  1296. }
  1297. /// <summary>
  1298. /// Gets the linked child.
  1299. /// </summary>
  1300. /// <param name="info">The info.</param>
  1301. /// <returns>BaseItem.</returns>
  1302. protected BaseItem GetLinkedChild(LinkedChild info)
  1303. {
  1304. // First get using the cached Id
  1305. if (info.ItemId.HasValue)
  1306. {
  1307. if (info.ItemId.Value == Guid.Empty)
  1308. {
  1309. return null;
  1310. }
  1311. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1312. if (itemById != null)
  1313. {
  1314. return itemById;
  1315. }
  1316. }
  1317. var item = FindLinkedChild(info);
  1318. // If still null, log
  1319. if (item == null)
  1320. {
  1321. // Don't keep searching over and over
  1322. info.ItemId = Guid.Empty;
  1323. }
  1324. else
  1325. {
  1326. // Cache the id for next time
  1327. info.ItemId = item.Id;
  1328. }
  1329. return item;
  1330. }
  1331. private BaseItem FindLinkedChild(LinkedChild info)
  1332. {
  1333. if (!string.IsNullOrEmpty(info.Path))
  1334. {
  1335. var itemByPath = LibraryManager.FindByPath(info.Path, null);
  1336. if (itemByPath == null)
  1337. {
  1338. //Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1339. }
  1340. return itemByPath;
  1341. }
  1342. return null;
  1343. }
  1344. [IgnoreDataMember]
  1345. public virtual bool EnableRememberingTrackSelections
  1346. {
  1347. get
  1348. {
  1349. return true;
  1350. }
  1351. }
  1352. /// <summary>
  1353. /// Adds a studio to the item
  1354. /// </summary>
  1355. /// <param name="name">The name.</param>
  1356. /// <exception cref="System.ArgumentNullException"></exception>
  1357. public void AddStudio(string name)
  1358. {
  1359. if (string.IsNullOrWhiteSpace(name))
  1360. {
  1361. throw new ArgumentNullException("name");
  1362. }
  1363. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1364. {
  1365. Studios.Add(name);
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// Adds a genre to the item
  1370. /// </summary>
  1371. /// <param name="name">The name.</param>
  1372. /// <exception cref="System.ArgumentNullException"></exception>
  1373. public void AddGenre(string name)
  1374. {
  1375. if (string.IsNullOrWhiteSpace(name))
  1376. {
  1377. throw new ArgumentNullException("name");
  1378. }
  1379. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1380. {
  1381. Genres.Add(name);
  1382. }
  1383. }
  1384. /// <summary>
  1385. /// Marks the played.
  1386. /// </summary>
  1387. /// <param name="user">The user.</param>
  1388. /// <param name="datePlayed">The date played.</param>
  1389. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1390. /// <returns>Task.</returns>
  1391. /// <exception cref="System.ArgumentNullException"></exception>
  1392. public virtual async Task MarkPlayed(User user,
  1393. DateTime? datePlayed,
  1394. bool resetPosition)
  1395. {
  1396. if (user == null)
  1397. {
  1398. throw new ArgumentNullException();
  1399. }
  1400. var data = UserDataManager.GetUserData(user, this);
  1401. if (datePlayed.HasValue)
  1402. {
  1403. // Increment
  1404. data.PlayCount++;
  1405. }
  1406. // Ensure it's at least one
  1407. data.PlayCount = Math.Max(data.PlayCount, 1);
  1408. if (resetPosition)
  1409. {
  1410. data.PlaybackPositionTicks = 0;
  1411. }
  1412. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1413. data.Played = true;
  1414. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1415. }
  1416. /// <summary>
  1417. /// Marks the unplayed.
  1418. /// </summary>
  1419. /// <param name="user">The user.</param>
  1420. /// <returns>Task.</returns>
  1421. /// <exception cref="System.ArgumentNullException"></exception>
  1422. public virtual async Task MarkUnplayed(User user)
  1423. {
  1424. if (user == null)
  1425. {
  1426. throw new ArgumentNullException();
  1427. }
  1428. var data = UserDataManager.GetUserData(user, this);
  1429. //I think it is okay to do this here.
  1430. // if this is only called when a user is manually forcing something to un-played
  1431. // then it probably is what we want to do...
  1432. data.PlayCount = 0;
  1433. data.PlaybackPositionTicks = 0;
  1434. data.LastPlayedDate = null;
  1435. data.Played = false;
  1436. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1437. }
  1438. /// <summary>
  1439. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1440. /// </summary>
  1441. /// <returns>Task.</returns>
  1442. public virtual Task ChangedExternally()
  1443. {
  1444. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1445. return Task.FromResult(true);
  1446. }
  1447. /// <summary>
  1448. /// Gets an image
  1449. /// </summary>
  1450. /// <param name="type">The type.</param>
  1451. /// <param name="imageIndex">Index of the image.</param>
  1452. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1453. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1454. public bool HasImage(ImageType type, int imageIndex)
  1455. {
  1456. return GetImageInfo(type, imageIndex) != null;
  1457. }
  1458. public void SetImage(ItemImageInfo image, int index)
  1459. {
  1460. if (image.Type == ImageType.Chapter)
  1461. {
  1462. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1463. }
  1464. var existingImage = GetImageInfo(image.Type, index);
  1465. if (existingImage != null)
  1466. {
  1467. ImageInfos.Remove(existingImage);
  1468. }
  1469. ImageInfos.Add(image);
  1470. }
  1471. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1472. {
  1473. if (type == ImageType.Chapter)
  1474. {
  1475. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1476. }
  1477. var image = GetImageInfo(type, index);
  1478. if (image == null)
  1479. {
  1480. ImageInfos.Add(GetImageInfo(file, type));
  1481. }
  1482. else
  1483. {
  1484. var imageInfo = GetImageInfo(file, type);
  1485. image.Path = file.FullName;
  1486. image.DateModified = imageInfo.DateModified;
  1487. image.IsPlaceholder = false;
  1488. }
  1489. }
  1490. /// <summary>
  1491. /// Deletes the image.
  1492. /// </summary>
  1493. /// <param name="type">The type.</param>
  1494. /// <param name="index">The index.</param>
  1495. /// <returns>Task.</returns>
  1496. public Task DeleteImage(ImageType type, int index)
  1497. {
  1498. var info = GetImageInfo(type, index);
  1499. if (info == null)
  1500. {
  1501. // Nothing to do
  1502. return Task.FromResult(true);
  1503. }
  1504. // Remove it from the item
  1505. RemoveImage(info);
  1506. if (info.IsLocalFile)
  1507. {
  1508. // Delete the source file
  1509. var currentFile = new FileInfo(info.Path);
  1510. // Deletion will fail if the file is hidden so remove the attribute first
  1511. if (currentFile.Exists)
  1512. {
  1513. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1514. {
  1515. currentFile.Attributes &= ~FileAttributes.Hidden;
  1516. }
  1517. FileSystem.DeleteFile(currentFile.FullName);
  1518. }
  1519. }
  1520. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1521. }
  1522. public void RemoveImage(ItemImageInfo image)
  1523. {
  1524. ImageInfos.Remove(image);
  1525. }
  1526. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1527. {
  1528. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1529. }
  1530. /// <summary>
  1531. /// Validates that images within the item are still on the file system
  1532. /// </summary>
  1533. public bool ValidateImages(IDirectoryService directoryService)
  1534. {
  1535. var allFiles = ImageInfos
  1536. .Where(i => i.IsLocalFile)
  1537. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1538. .Distinct(StringComparer.OrdinalIgnoreCase)
  1539. .SelectMany(directoryService.GetFiles)
  1540. .Select(i => i.FullName)
  1541. .ToList();
  1542. var deletedImages = ImageInfos
  1543. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1544. .ToList();
  1545. if (deletedImages.Count > 0)
  1546. {
  1547. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1548. }
  1549. return deletedImages.Count > 0;
  1550. }
  1551. /// <summary>
  1552. /// Gets the image path.
  1553. /// </summary>
  1554. /// <param name="imageType">Type of the image.</param>
  1555. /// <param name="imageIndex">Index of the image.</param>
  1556. /// <returns>System.String.</returns>
  1557. /// <exception cref="System.InvalidOperationException">
  1558. /// </exception>
  1559. /// <exception cref="System.ArgumentNullException">item</exception>
  1560. public string GetImagePath(ImageType imageType, int imageIndex)
  1561. {
  1562. var info = GetImageInfo(imageType, imageIndex);
  1563. return info == null ? null : info.Path;
  1564. }
  1565. /// <summary>
  1566. /// Gets the image information.
  1567. /// </summary>
  1568. /// <param name="imageType">Type of the image.</param>
  1569. /// <param name="imageIndex">Index of the image.</param>
  1570. /// <returns>ItemImageInfo.</returns>
  1571. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1572. {
  1573. if (imageType == ImageType.Chapter)
  1574. {
  1575. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1576. if (chapter == null)
  1577. {
  1578. return null;
  1579. }
  1580. var path = chapter.ImagePath;
  1581. if (string.IsNullOrWhiteSpace(path))
  1582. {
  1583. return null;
  1584. }
  1585. return new ItemImageInfo
  1586. {
  1587. Path = path,
  1588. DateModified = chapter.ImageDateModified,
  1589. Type = imageType
  1590. };
  1591. }
  1592. return GetImages(imageType)
  1593. .ElementAtOrDefault(imageIndex);
  1594. }
  1595. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1596. {
  1597. if (imageType == ImageType.Chapter)
  1598. {
  1599. throw new ArgumentException("No image info for chapter images");
  1600. }
  1601. return ImageInfos.Where(i => i.Type == imageType);
  1602. }
  1603. /// <summary>
  1604. /// Adds the images.
  1605. /// </summary>
  1606. /// <param name="imageType">Type of the image.</param>
  1607. /// <param name="images">The images.</param>
  1608. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1609. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1610. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1611. {
  1612. if (imageType == ImageType.Chapter)
  1613. {
  1614. throw new ArgumentException("Cannot call AddImages with chapter images");
  1615. }
  1616. var existingImages = GetImages(imageType)
  1617. .ToList();
  1618. var newImageList = new List<FileSystemMetadata>();
  1619. var imageAdded = false;
  1620. foreach (var newImage in images)
  1621. {
  1622. if (newImage == null)
  1623. {
  1624. throw new ArgumentException("null image found in list");
  1625. }
  1626. var existing = existingImages
  1627. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1628. if (existing == null)
  1629. {
  1630. newImageList.Add(newImage);
  1631. imageAdded = true;
  1632. }
  1633. else
  1634. {
  1635. if (existing.IsLocalFile)
  1636. {
  1637. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1638. }
  1639. }
  1640. }
  1641. if (imageAdded || images.Count != existingImages.Count)
  1642. {
  1643. var newImagePaths = images.Select(i => i.FullName).ToList();
  1644. var deleted = existingImages
  1645. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1646. .ToList();
  1647. ImageInfos = ImageInfos.Except(deleted).ToList();
  1648. }
  1649. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1650. return newImageList.Count > 0;
  1651. }
  1652. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1653. {
  1654. return new ItemImageInfo
  1655. {
  1656. Path = file.FullName,
  1657. Type = type,
  1658. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1659. };
  1660. }
  1661. /// <summary>
  1662. /// Gets the file system path to delete when the item is to be deleted
  1663. /// </summary>
  1664. /// <returns></returns>
  1665. public virtual IEnumerable<string> GetDeletePaths()
  1666. {
  1667. return new[] { Path };
  1668. }
  1669. public bool AllowsMultipleImages(ImageType type)
  1670. {
  1671. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1672. }
  1673. public Task SwapImages(ImageType type, int index1, int index2)
  1674. {
  1675. if (!AllowsMultipleImages(type))
  1676. {
  1677. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1678. }
  1679. var info1 = GetImageInfo(type, index1);
  1680. var info2 = GetImageInfo(type, index2);
  1681. if (info1 == null || info2 == null)
  1682. {
  1683. // Nothing to do
  1684. return Task.FromResult(true);
  1685. }
  1686. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1687. {
  1688. // TODO: Not supported yet
  1689. return Task.FromResult(true);
  1690. }
  1691. var path1 = info1.Path;
  1692. var path2 = info2.Path;
  1693. FileSystem.SwapFiles(path1, path2);
  1694. // Refresh these values
  1695. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1696. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1697. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1698. }
  1699. public virtual bool IsPlayed(User user)
  1700. {
  1701. var userdata = UserDataManager.GetUserData(user, this);
  1702. return userdata != null && userdata.Played;
  1703. }
  1704. public bool IsFavoriteOrLiked(User user)
  1705. {
  1706. var userdata = UserDataManager.GetUserData(user, this);
  1707. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1708. }
  1709. public virtual bool IsUnplayed(User user)
  1710. {
  1711. if (user == null)
  1712. {
  1713. throw new ArgumentNullException("user");
  1714. }
  1715. var userdata = UserDataManager.GetUserData(user, this);
  1716. return userdata == null || !userdata.Played;
  1717. }
  1718. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1719. {
  1720. return GetItemLookupInfo<ItemLookupInfo>();
  1721. }
  1722. protected T GetItemLookupInfo<T>()
  1723. where T : ItemLookupInfo, new()
  1724. {
  1725. return new T
  1726. {
  1727. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1728. MetadataLanguage = GetPreferredMetadataLanguage(),
  1729. Name = Name,
  1730. ProviderIds = ProviderIds,
  1731. IndexNumber = IndexNumber,
  1732. ParentIndexNumber = ParentIndexNumber,
  1733. Year = ProductionYear,
  1734. PremiereDate = PremiereDate
  1735. };
  1736. }
  1737. /// <summary>
  1738. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1739. /// </summary>
  1740. public virtual bool BeforeMetadataRefresh()
  1741. {
  1742. _sortName = null;
  1743. var hasChanges = false;
  1744. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1745. {
  1746. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1747. hasChanges = true;
  1748. }
  1749. return hasChanges;
  1750. }
  1751. protected static string GetMappedPath(string path, LocationType locationType)
  1752. {
  1753. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1754. {
  1755. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1756. {
  1757. path = LibraryManager.SubstitutePath(path, map.From, map.To);
  1758. }
  1759. }
  1760. return path;
  1761. }
  1762. public virtual Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1763. {
  1764. if (RunTimeTicks.HasValue)
  1765. {
  1766. double pct = RunTimeTicks.Value;
  1767. if (pct > 0)
  1768. {
  1769. pct = userData.PlaybackPositionTicks / pct;
  1770. if (pct > 0)
  1771. {
  1772. dto.PlayedPercentage = 100 * pct;
  1773. }
  1774. }
  1775. }
  1776. return Task.FromResult(true);
  1777. }
  1778. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1779. {
  1780. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1781. {
  1782. ImageRefreshMode = options.ImageRefreshMode,
  1783. MetadataRefreshMode = options.MetadataRefreshMode,
  1784. ReplaceAllMetadata = options.ReplaceAllMetadata
  1785. };
  1786. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1787. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1788. var video = LibraryManager.GetItemById(id) as Video;
  1789. if (video == null)
  1790. {
  1791. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1792. newOptions.ForceSave = true;
  1793. }
  1794. if (video == null)
  1795. {
  1796. return Task.FromResult(true);
  1797. }
  1798. return video.RefreshMetadata(newOptions, cancellationToken);
  1799. }
  1800. public string GetEtag(User user)
  1801. {
  1802. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1803. }
  1804. protected virtual List<string> GetEtagValues(User user)
  1805. {
  1806. return new List<string>
  1807. {
  1808. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1809. };
  1810. }
  1811. public virtual IEnumerable<Guid> GetAncestorIds()
  1812. {
  1813. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1814. }
  1815. public BaseItem GetTopParent()
  1816. {
  1817. if (IsTopParent)
  1818. {
  1819. return this;
  1820. }
  1821. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1822. }
  1823. [IgnoreDataMember]
  1824. public virtual bool IsTopParent
  1825. {
  1826. get
  1827. {
  1828. if (GetParent() is AggregateFolder || this is BasePluginFolder || this is Channel)
  1829. {
  1830. return true;
  1831. }
  1832. var view = this as UserView;
  1833. if (view != null && string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1834. {
  1835. return true;
  1836. }
  1837. if (view != null && string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1838. {
  1839. return true;
  1840. }
  1841. return false;
  1842. }
  1843. }
  1844. [IgnoreDataMember]
  1845. public virtual bool SupportsAncestors
  1846. {
  1847. get
  1848. {
  1849. return true;
  1850. }
  1851. }
  1852. [IgnoreDataMember]
  1853. public virtual bool StopRefreshIfLocalMetadataFound
  1854. {
  1855. get
  1856. {
  1857. return true;
  1858. }
  1859. }
  1860. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1861. {
  1862. return new[] { Id };
  1863. }
  1864. public virtual Task Delete(DeleteOptions options)
  1865. {
  1866. return LibraryManager.DeleteItem(this, options);
  1867. }
  1868. public virtual Task OnFileDeleted()
  1869. {
  1870. // Remove from database
  1871. return Delete(new DeleteOptions
  1872. {
  1873. DeleteFileLocation = false
  1874. });
  1875. }
  1876. public virtual List<ExternalUrl> GetRelatedUrls()
  1877. {
  1878. return new List<ExternalUrl>();
  1879. }
  1880. }
  1881. }