BaseItem.cs 59 KB

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