BaseItem.cs 57 KB

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