BaseItem.cs 58 KB

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