BaseItem.cs 59 KB

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