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