BaseItem.cs 56 KB

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