BaseItem.cs 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280
  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 ConfigurationManager.Configuration.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. return ConfigurationManager.Configuration.SaveLocalMeta;
  1122. }
  1123. /// <summary>
  1124. /// Determines if a given user has access to this item
  1125. /// </summary>
  1126. /// <param name="user">The user.</param>
  1127. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1128. /// <exception cref="System.ArgumentNullException">user</exception>
  1129. public bool IsParentalAllowed(User user)
  1130. {
  1131. if (user == null)
  1132. {
  1133. throw new ArgumentNullException("user");
  1134. }
  1135. if (!IsVisibleViaTags(user))
  1136. {
  1137. return false;
  1138. }
  1139. var maxAllowedRating = user.Policy.MaxParentalRating;
  1140. if (maxAllowedRating == null)
  1141. {
  1142. return true;
  1143. }
  1144. var rating = CustomRatingForComparison;
  1145. if (string.IsNullOrWhiteSpace(rating))
  1146. {
  1147. rating = OfficialRatingForComparison;
  1148. }
  1149. if (string.IsNullOrWhiteSpace(rating))
  1150. {
  1151. return !GetBlockUnratedValue(user.Policy);
  1152. }
  1153. var value = LocalizationManager.GetRatingLevel(rating);
  1154. // Could not determine the integer value
  1155. if (!value.HasValue)
  1156. {
  1157. var isAllowed = !GetBlockUnratedValue(user.Policy);
  1158. if (!isAllowed)
  1159. {
  1160. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1161. }
  1162. return isAllowed;
  1163. }
  1164. return value.Value <= maxAllowedRating.Value;
  1165. }
  1166. public int? GetParentalRatingValue()
  1167. {
  1168. var rating = CustomRating;
  1169. if (string.IsNullOrWhiteSpace(rating))
  1170. {
  1171. rating = OfficialRating;
  1172. }
  1173. if (string.IsNullOrWhiteSpace(rating))
  1174. {
  1175. return null;
  1176. }
  1177. return LocalizationManager.GetRatingLevel(rating);
  1178. }
  1179. public int? GetInheritedParentalRatingValue()
  1180. {
  1181. var rating = CustomRatingForComparison;
  1182. if (string.IsNullOrWhiteSpace(rating))
  1183. {
  1184. rating = OfficialRatingForComparison;
  1185. }
  1186. if (string.IsNullOrWhiteSpace(rating))
  1187. {
  1188. return null;
  1189. }
  1190. return LocalizationManager.GetRatingLevel(rating);
  1191. }
  1192. public List<string> GetInheritedTags()
  1193. {
  1194. var list = new List<string>();
  1195. list.AddRange(Tags);
  1196. foreach (var parent in GetParents())
  1197. {
  1198. list.AddRange(parent.Tags);
  1199. }
  1200. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1201. }
  1202. private bool IsVisibleViaTags(User user)
  1203. {
  1204. var policy = user.Policy;
  1205. if (policy.BlockedTags.Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1206. {
  1207. return false;
  1208. }
  1209. return true;
  1210. }
  1211. protected virtual bool IsAllowTagFilterEnforced()
  1212. {
  1213. return true;
  1214. }
  1215. public virtual UnratedItem GetBlockUnratedType()
  1216. {
  1217. if (SourceType == SourceType.Channel)
  1218. {
  1219. return UnratedItem.ChannelContent;
  1220. }
  1221. return UnratedItem.Other;
  1222. }
  1223. /// <summary>
  1224. /// Gets the block unrated value.
  1225. /// </summary>
  1226. /// <param name="config">The configuration.</param>
  1227. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1228. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  1229. {
  1230. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1231. // Special folders like series and albums will override this method.
  1232. if (IsFolder)
  1233. {
  1234. return false;
  1235. }
  1236. if (this is IItemByName)
  1237. {
  1238. return false;
  1239. }
  1240. return config.BlockUnratedItems.Contains(GetBlockUnratedType());
  1241. }
  1242. /// <summary>
  1243. /// Determines if this folder should be visible to a given user.
  1244. /// Default is just parental allowed. Can be overridden for more functionality.
  1245. /// </summary>
  1246. /// <param name="user">The user.</param>
  1247. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1248. /// <exception cref="System.ArgumentNullException">user</exception>
  1249. public virtual bool IsVisible(User user)
  1250. {
  1251. if (user == null)
  1252. {
  1253. throw new ArgumentNullException("user");
  1254. }
  1255. return IsParentalAllowed(user);
  1256. }
  1257. public virtual bool IsVisibleStandalone(User user)
  1258. {
  1259. if (SourceType == SourceType.Channel)
  1260. {
  1261. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1262. }
  1263. return IsVisibleStandaloneInternal(user, true);
  1264. }
  1265. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1266. {
  1267. if (!IsVisible(user))
  1268. {
  1269. return false;
  1270. }
  1271. if (GetParents().Any(i => !i.IsVisible(user)))
  1272. {
  1273. return false;
  1274. }
  1275. if (checkFolders)
  1276. {
  1277. var topParent = GetParents().LastOrDefault() ?? this;
  1278. if (string.IsNullOrWhiteSpace(topParent.Path))
  1279. {
  1280. return true;
  1281. }
  1282. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1283. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1284. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1285. {
  1286. return false;
  1287. }
  1288. }
  1289. return true;
  1290. }
  1291. /// <summary>
  1292. /// Gets a value indicating whether this instance is folder.
  1293. /// </summary>
  1294. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1295. [IgnoreDataMember]
  1296. public virtual bool IsFolder
  1297. {
  1298. get
  1299. {
  1300. return false;
  1301. }
  1302. }
  1303. public virtual string GetClientTypeName()
  1304. {
  1305. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1306. {
  1307. return "ChannelFolderItem";
  1308. }
  1309. return GetType().Name;
  1310. }
  1311. /// <summary>
  1312. /// Gets the linked child.
  1313. /// </summary>
  1314. /// <param name="info">The info.</param>
  1315. /// <returns>BaseItem.</returns>
  1316. protected BaseItem GetLinkedChild(LinkedChild info)
  1317. {
  1318. // First get using the cached Id
  1319. if (info.ItemId.HasValue)
  1320. {
  1321. if (info.ItemId.Value == Guid.Empty)
  1322. {
  1323. return null;
  1324. }
  1325. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1326. if (itemById != null)
  1327. {
  1328. return itemById;
  1329. }
  1330. }
  1331. var item = FindLinkedChild(info);
  1332. // If still null, log
  1333. if (item == null)
  1334. {
  1335. // Don't keep searching over and over
  1336. info.ItemId = Guid.Empty;
  1337. }
  1338. else
  1339. {
  1340. // Cache the id for next time
  1341. info.ItemId = item.Id;
  1342. }
  1343. return item;
  1344. }
  1345. private BaseItem FindLinkedChild(LinkedChild info)
  1346. {
  1347. if (!string.IsNullOrEmpty(info.Path))
  1348. {
  1349. var itemByPath = LibraryManager.FindByPath(info.Path, null);
  1350. if (itemByPath == null)
  1351. {
  1352. //Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1353. }
  1354. return itemByPath;
  1355. }
  1356. return null;
  1357. }
  1358. [IgnoreDataMember]
  1359. public virtual bool EnableRememberingTrackSelections
  1360. {
  1361. get
  1362. {
  1363. return true;
  1364. }
  1365. }
  1366. /// <summary>
  1367. /// Adds a studio to the item
  1368. /// </summary>
  1369. /// <param name="name">The name.</param>
  1370. /// <exception cref="System.ArgumentNullException"></exception>
  1371. public void AddStudio(string name)
  1372. {
  1373. if (string.IsNullOrWhiteSpace(name))
  1374. {
  1375. throw new ArgumentNullException("name");
  1376. }
  1377. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1378. {
  1379. Studios.Add(name);
  1380. }
  1381. }
  1382. /// <summary>
  1383. /// Adds a genre to the item
  1384. /// </summary>
  1385. /// <param name="name">The name.</param>
  1386. /// <exception cref="System.ArgumentNullException"></exception>
  1387. public void AddGenre(string name)
  1388. {
  1389. if (string.IsNullOrWhiteSpace(name))
  1390. {
  1391. throw new ArgumentNullException("name");
  1392. }
  1393. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1394. {
  1395. Genres.Add(name);
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// Marks the played.
  1400. /// </summary>
  1401. /// <param name="user">The user.</param>
  1402. /// <param name="datePlayed">The date played.</param>
  1403. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1404. /// <returns>Task.</returns>
  1405. /// <exception cref="System.ArgumentNullException"></exception>
  1406. public virtual async Task MarkPlayed(User user,
  1407. DateTime? datePlayed,
  1408. bool resetPosition)
  1409. {
  1410. if (user == null)
  1411. {
  1412. throw new ArgumentNullException();
  1413. }
  1414. var data = UserDataManager.GetUserData(user, this);
  1415. if (datePlayed.HasValue)
  1416. {
  1417. // Increment
  1418. data.PlayCount++;
  1419. }
  1420. // Ensure it's at least one
  1421. data.PlayCount = Math.Max(data.PlayCount, 1);
  1422. if (resetPosition)
  1423. {
  1424. data.PlaybackPositionTicks = 0;
  1425. }
  1426. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1427. data.Played = true;
  1428. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1429. }
  1430. /// <summary>
  1431. /// Marks the unplayed.
  1432. /// </summary>
  1433. /// <param name="user">The user.</param>
  1434. /// <returns>Task.</returns>
  1435. /// <exception cref="System.ArgumentNullException"></exception>
  1436. public virtual async Task MarkUnplayed(User user)
  1437. {
  1438. if (user == null)
  1439. {
  1440. throw new ArgumentNullException();
  1441. }
  1442. var data = UserDataManager.GetUserData(user, this);
  1443. //I think it is okay to do this here.
  1444. // if this is only called when a user is manually forcing something to un-played
  1445. // then it probably is what we want to do...
  1446. data.PlayCount = 0;
  1447. data.PlaybackPositionTicks = 0;
  1448. data.LastPlayedDate = null;
  1449. data.Played = false;
  1450. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1451. }
  1452. /// <summary>
  1453. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1454. /// </summary>
  1455. /// <returns>Task.</returns>
  1456. public virtual Task ChangedExternally()
  1457. {
  1458. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1459. return Task.FromResult(true);
  1460. }
  1461. /// <summary>
  1462. /// Gets an image
  1463. /// </summary>
  1464. /// <param name="type">The type.</param>
  1465. /// <param name="imageIndex">Index of the image.</param>
  1466. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1467. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1468. public bool HasImage(ImageType type, int imageIndex)
  1469. {
  1470. return GetImageInfo(type, imageIndex) != null;
  1471. }
  1472. public void SetImage(ItemImageInfo image, int index)
  1473. {
  1474. if (image.Type == ImageType.Chapter)
  1475. {
  1476. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1477. }
  1478. var existingImage = GetImageInfo(image.Type, index);
  1479. if (existingImage != null)
  1480. {
  1481. ImageInfos.Remove(existingImage);
  1482. }
  1483. ImageInfos.Add(image);
  1484. }
  1485. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1486. {
  1487. if (type == ImageType.Chapter)
  1488. {
  1489. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1490. }
  1491. var image = GetImageInfo(type, index);
  1492. if (image == null)
  1493. {
  1494. ImageInfos.Add(GetImageInfo(file, type));
  1495. }
  1496. else
  1497. {
  1498. var imageInfo = GetImageInfo(file, type);
  1499. image.Path = file.FullName;
  1500. image.DateModified = imageInfo.DateModified;
  1501. image.IsPlaceholder = false;
  1502. }
  1503. }
  1504. /// <summary>
  1505. /// Deletes the image.
  1506. /// </summary>
  1507. /// <param name="type">The type.</param>
  1508. /// <param name="index">The index.</param>
  1509. /// <returns>Task.</returns>
  1510. public Task DeleteImage(ImageType type, int index)
  1511. {
  1512. var info = GetImageInfo(type, index);
  1513. if (info == null)
  1514. {
  1515. // Nothing to do
  1516. return Task.FromResult(true);
  1517. }
  1518. // Remove it from the item
  1519. RemoveImage(info);
  1520. if (info.IsLocalFile)
  1521. {
  1522. // Delete the source file
  1523. var currentFile = new FileInfo(info.Path);
  1524. // Deletion will fail if the file is hidden so remove the attribute first
  1525. if (currentFile.Exists)
  1526. {
  1527. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1528. {
  1529. currentFile.Attributes &= ~FileAttributes.Hidden;
  1530. }
  1531. FileSystem.DeleteFile(currentFile.FullName);
  1532. }
  1533. }
  1534. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1535. }
  1536. public void RemoveImage(ItemImageInfo image)
  1537. {
  1538. ImageInfos.Remove(image);
  1539. }
  1540. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1541. {
  1542. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1543. }
  1544. /// <summary>
  1545. /// Validates that images within the item are still on the file system
  1546. /// </summary>
  1547. public bool ValidateImages(IDirectoryService directoryService)
  1548. {
  1549. var allFiles = ImageInfos
  1550. .Where(i => i.IsLocalFile)
  1551. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1552. .Distinct(StringComparer.OrdinalIgnoreCase)
  1553. .SelectMany(directoryService.GetFiles)
  1554. .Select(i => i.FullName)
  1555. .ToList();
  1556. var deletedImages = ImageInfos
  1557. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1558. .ToList();
  1559. if (deletedImages.Count > 0)
  1560. {
  1561. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1562. }
  1563. return deletedImages.Count > 0;
  1564. }
  1565. /// <summary>
  1566. /// Gets the image path.
  1567. /// </summary>
  1568. /// <param name="imageType">Type of the image.</param>
  1569. /// <param name="imageIndex">Index of the image.</param>
  1570. /// <returns>System.String.</returns>
  1571. /// <exception cref="System.InvalidOperationException">
  1572. /// </exception>
  1573. /// <exception cref="System.ArgumentNullException">item</exception>
  1574. public string GetImagePath(ImageType imageType, int imageIndex)
  1575. {
  1576. var info = GetImageInfo(imageType, imageIndex);
  1577. return info == null ? null : info.Path;
  1578. }
  1579. /// <summary>
  1580. /// Gets the image information.
  1581. /// </summary>
  1582. /// <param name="imageType">Type of the image.</param>
  1583. /// <param name="imageIndex">Index of the image.</param>
  1584. /// <returns>ItemImageInfo.</returns>
  1585. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1586. {
  1587. if (imageType == ImageType.Chapter)
  1588. {
  1589. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1590. if (chapter == null)
  1591. {
  1592. return null;
  1593. }
  1594. var path = chapter.ImagePath;
  1595. if (string.IsNullOrWhiteSpace(path))
  1596. {
  1597. return null;
  1598. }
  1599. return new ItemImageInfo
  1600. {
  1601. Path = path,
  1602. DateModified = chapter.ImageDateModified,
  1603. Type = imageType
  1604. };
  1605. }
  1606. return GetImages(imageType)
  1607. .ElementAtOrDefault(imageIndex);
  1608. }
  1609. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1610. {
  1611. if (imageType == ImageType.Chapter)
  1612. {
  1613. throw new ArgumentException("No image info for chapter images");
  1614. }
  1615. return ImageInfos.Where(i => i.Type == imageType);
  1616. }
  1617. /// <summary>
  1618. /// Adds the images.
  1619. /// </summary>
  1620. /// <param name="imageType">Type of the image.</param>
  1621. /// <param name="images">The images.</param>
  1622. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1623. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1624. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1625. {
  1626. if (imageType == ImageType.Chapter)
  1627. {
  1628. throw new ArgumentException("Cannot call AddImages with chapter images");
  1629. }
  1630. var existingImages = GetImages(imageType)
  1631. .ToList();
  1632. var newImageList = new List<FileSystemMetadata>();
  1633. var imageAdded = false;
  1634. foreach (var newImage in images)
  1635. {
  1636. if (newImage == null)
  1637. {
  1638. throw new ArgumentException("null image found in list");
  1639. }
  1640. var existing = existingImages
  1641. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1642. if (existing == null)
  1643. {
  1644. newImageList.Add(newImage);
  1645. imageAdded = true;
  1646. }
  1647. else
  1648. {
  1649. if (existing.IsLocalFile)
  1650. {
  1651. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1652. }
  1653. }
  1654. }
  1655. if (imageAdded || images.Count != existingImages.Count)
  1656. {
  1657. var newImagePaths = images.Select(i => i.FullName).ToList();
  1658. var deleted = existingImages
  1659. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1660. .ToList();
  1661. ImageInfos = ImageInfos.Except(deleted).ToList();
  1662. }
  1663. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1664. return newImageList.Count > 0;
  1665. }
  1666. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1667. {
  1668. return new ItemImageInfo
  1669. {
  1670. Path = file.FullName,
  1671. Type = type,
  1672. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1673. };
  1674. }
  1675. /// <summary>
  1676. /// Gets the file system path to delete when the item is to be deleted
  1677. /// </summary>
  1678. /// <returns></returns>
  1679. public virtual IEnumerable<string> GetDeletePaths()
  1680. {
  1681. return new[] { Path };
  1682. }
  1683. public bool AllowsMultipleImages(ImageType type)
  1684. {
  1685. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1686. }
  1687. public Task SwapImages(ImageType type, int index1, int index2)
  1688. {
  1689. if (!AllowsMultipleImages(type))
  1690. {
  1691. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1692. }
  1693. var info1 = GetImageInfo(type, index1);
  1694. var info2 = GetImageInfo(type, index2);
  1695. if (info1 == null || info2 == null)
  1696. {
  1697. // Nothing to do
  1698. return Task.FromResult(true);
  1699. }
  1700. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1701. {
  1702. // TODO: Not supported yet
  1703. return Task.FromResult(true);
  1704. }
  1705. var path1 = info1.Path;
  1706. var path2 = info2.Path;
  1707. FileSystem.SwapFiles(path1, path2);
  1708. // Refresh these values
  1709. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1710. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1711. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1712. }
  1713. public virtual bool IsPlayed(User user)
  1714. {
  1715. var userdata = UserDataManager.GetUserData(user, this);
  1716. return userdata != null && userdata.Played;
  1717. }
  1718. public bool IsFavoriteOrLiked(User user)
  1719. {
  1720. var userdata = UserDataManager.GetUserData(user, this);
  1721. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1722. }
  1723. public virtual bool IsUnplayed(User user)
  1724. {
  1725. if (user == null)
  1726. {
  1727. throw new ArgumentNullException("user");
  1728. }
  1729. var userdata = UserDataManager.GetUserData(user, this);
  1730. return userdata == null || !userdata.Played;
  1731. }
  1732. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1733. {
  1734. return GetItemLookupInfo<ItemLookupInfo>();
  1735. }
  1736. protected T GetItemLookupInfo<T>()
  1737. where T : ItemLookupInfo, new()
  1738. {
  1739. return new T
  1740. {
  1741. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1742. MetadataLanguage = GetPreferredMetadataLanguage(),
  1743. Name = Name,
  1744. ProviderIds = ProviderIds,
  1745. IndexNumber = IndexNumber,
  1746. ParentIndexNumber = ParentIndexNumber,
  1747. Year = ProductionYear,
  1748. PremiereDate = PremiereDate
  1749. };
  1750. }
  1751. /// <summary>
  1752. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1753. /// </summary>
  1754. public virtual bool BeforeMetadataRefresh()
  1755. {
  1756. _sortName = null;
  1757. var hasChanges = false;
  1758. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1759. {
  1760. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1761. hasChanges = true;
  1762. }
  1763. return hasChanges;
  1764. }
  1765. protected static string GetMappedPath(BaseItem item, string path, LocationType locationType)
  1766. {
  1767. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1768. {
  1769. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1770. }
  1771. return path;
  1772. }
  1773. public virtual Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user)
  1774. {
  1775. if (RunTimeTicks.HasValue)
  1776. {
  1777. double pct = RunTimeTicks.Value;
  1778. if (pct > 0)
  1779. {
  1780. pct = userData.PlaybackPositionTicks / pct;
  1781. if (pct > 0)
  1782. {
  1783. dto.PlayedPercentage = 100 * pct;
  1784. }
  1785. }
  1786. }
  1787. return Task.FromResult(true);
  1788. }
  1789. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1790. {
  1791. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1792. {
  1793. ImageRefreshMode = options.ImageRefreshMode,
  1794. MetadataRefreshMode = options.MetadataRefreshMode,
  1795. ReplaceAllMetadata = options.ReplaceAllMetadata
  1796. };
  1797. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1798. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1799. var video = LibraryManager.GetItemById(id) as Video;
  1800. if (video == null)
  1801. {
  1802. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1803. newOptions.ForceSave = true;
  1804. }
  1805. if (video == null)
  1806. {
  1807. return Task.FromResult(true);
  1808. }
  1809. return video.RefreshMetadata(newOptions, cancellationToken);
  1810. }
  1811. public string GetEtag(User user)
  1812. {
  1813. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1814. }
  1815. protected virtual List<string> GetEtagValues(User user)
  1816. {
  1817. return new List<string>
  1818. {
  1819. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1820. };
  1821. }
  1822. public virtual IEnumerable<Guid> GetAncestorIds()
  1823. {
  1824. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1825. }
  1826. public BaseItem GetTopParent()
  1827. {
  1828. if (IsTopParent)
  1829. {
  1830. return this;
  1831. }
  1832. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1833. }
  1834. [IgnoreDataMember]
  1835. public virtual bool IsTopParent
  1836. {
  1837. get
  1838. {
  1839. if (GetParent() is AggregateFolder || this is BasePluginFolder || this is Channel)
  1840. {
  1841. return true;
  1842. }
  1843. var view = this as UserView;
  1844. if (view != null && string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1845. {
  1846. return true;
  1847. }
  1848. if (view != null && string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1849. {
  1850. return true;
  1851. }
  1852. return false;
  1853. }
  1854. }
  1855. [IgnoreDataMember]
  1856. public virtual bool SupportsAncestors
  1857. {
  1858. get
  1859. {
  1860. return true;
  1861. }
  1862. }
  1863. [IgnoreDataMember]
  1864. public virtual bool StopRefreshIfLocalMetadataFound
  1865. {
  1866. get
  1867. {
  1868. return true;
  1869. }
  1870. }
  1871. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1872. {
  1873. return new[] { Id };
  1874. }
  1875. public virtual Task Delete(DeleteOptions options)
  1876. {
  1877. return LibraryManager.DeleteItem(this, options);
  1878. }
  1879. public virtual Task OnFileDeleted()
  1880. {
  1881. // Remove from database
  1882. return Delete(new DeleteOptions
  1883. {
  1884. DeleteFileLocation = false
  1885. });
  1886. }
  1887. public virtual List<ExternalUrl> GetRelatedUrls()
  1888. {
  1889. return new List<ExternalUrl>();
  1890. }
  1891. }
  1892. }