BaseItem.cs 59 KB

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