BaseItem.cs 60 KB

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