BaseItem.cs 70 KB

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