BaseItem.cs 59 KB

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