BaseItem.cs 59 KB

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