BaseItem.cs 70 KB

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