BaseItem.cs 60 KB

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