BaseItem.cs 70 KB

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