BaseItem.cs 60 KB

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