BaseItem.cs 61 KB

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