BaseItem.cs 61 KB

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