BaseItem.cs 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Localization;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Controller.Resolvers;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Runtime.Serialization;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Controller.Entities
  20. {
  21. /// <summary>
  22. /// Class BaseItem
  23. /// </summary>
  24. public abstract class BaseItem : IHasProviderIds
  25. {
  26. /// <summary>
  27. /// MusicAlbums in the library that are the soundtrack for this item
  28. /// </summary>
  29. public List<Guid> SoundtrackIds { get; set; }
  30. protected BaseItem()
  31. {
  32. Genres = new List<string>();
  33. Studios = new List<string>();
  34. People = new List<PersonInfo>();
  35. ScreenshotImagePaths = new List<string>();
  36. BackdropImagePaths = new List<string>();
  37. ProductionLocations = new List<string>();
  38. Images = new Dictionary<ImageType, string>();
  39. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  40. Tags = new List<string>();
  41. ThemeSongIds = new List<Guid>();
  42. ThemeVideoIds = new List<Guid>();
  43. SoundtrackIds = new List<Guid>();
  44. LocalTrailerIds = new List<Guid>();
  45. LockedFields = new List<MetadataFields>();
  46. Taglines = new List<string>();
  47. RemoteTrailers = new List<MediaUrl>();
  48. }
  49. /// <summary>
  50. /// The supported image extensions
  51. /// </summary>
  52. public static readonly string[] SupportedImageExtensions = new[] { ".png", ".jpg", ".jpeg" };
  53. /// <summary>
  54. /// The trailer folder name
  55. /// </summary>
  56. public const string TrailerFolderName = "trailers";
  57. public const string ThemeSongsFolderName = "theme-music";
  58. public const string ThemeSongFilename = "theme";
  59. public const string ThemeVideosFolderName = "backdrops";
  60. public const string XbmcTrailerFileSuffix = "-trailer";
  61. public bool IsInMixedFolder { get; set; }
  62. private string _name;
  63. /// <summary>
  64. /// Gets or sets the name.
  65. /// </summary>
  66. /// <value>The name.</value>
  67. public string Name
  68. {
  69. get
  70. {
  71. return _name;
  72. }
  73. set
  74. {
  75. _name = value;
  76. // lazy load this again
  77. _sortName = null;
  78. }
  79. }
  80. /// <summary>
  81. /// Gets or sets the id.
  82. /// </summary>
  83. /// <value>The id.</value>
  84. public Guid Id { get; set; }
  85. /// <summary>
  86. /// Gets or sets the budget.
  87. /// </summary>
  88. /// <value>The budget.</value>
  89. public double? Budget { get; set; }
  90. /// <summary>
  91. /// Gets or sets the taglines.
  92. /// </summary>
  93. /// <value>The taglines.</value>
  94. public List<string> Taglines { get; set; }
  95. /// <summary>
  96. /// Gets or sets the revenue.
  97. /// </summary>
  98. /// <value>The revenue.</value>
  99. public double? Revenue { get; set; }
  100. /// <summary>
  101. /// Gets or sets the critic rating.
  102. /// </summary>
  103. /// <value>The critic rating.</value>
  104. public float? CriticRating { get; set; }
  105. /// <summary>
  106. /// Gets or sets the critic rating summary.
  107. /// </summary>
  108. /// <value>The critic rating summary.</value>
  109. public string CriticRatingSummary { get; set; }
  110. /// <summary>
  111. /// Gets or sets the trailer URL.
  112. /// </summary>
  113. /// <value>The trailer URL.</value>
  114. public List<MediaUrl> RemoteTrailers { get; set; }
  115. /// <summary>
  116. /// Return the id that should be used to key display prefs for this item.
  117. /// Default is based on the type for everything except actual generic folders.
  118. /// </summary>
  119. /// <value>The display prefs id.</value>
  120. [IgnoreDataMember]
  121. public virtual Guid DisplayPreferencesId
  122. {
  123. get
  124. {
  125. var thisType = GetType();
  126. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  127. }
  128. }
  129. /// <summary>
  130. /// Gets or sets the path.
  131. /// </summary>
  132. /// <value>The path.</value>
  133. public virtual string Path { get; set; }
  134. [IgnoreDataMember]
  135. protected internal bool IsOffline { get; set; }
  136. /// <summary>
  137. /// Gets or sets the type of the location.
  138. /// </summary>
  139. /// <value>The type of the location.</value>
  140. public virtual LocationType LocationType
  141. {
  142. get
  143. {
  144. if (IsOffline)
  145. {
  146. return LocationType.Offline;
  147. }
  148. if (string.IsNullOrEmpty(Path))
  149. {
  150. return LocationType.Virtual;
  151. }
  152. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  153. }
  154. }
  155. /// <summary>
  156. /// This is just a helper for convenience
  157. /// </summary>
  158. /// <value>The primary image path.</value>
  159. [IgnoreDataMember]
  160. public string PrimaryImagePath
  161. {
  162. get { return GetImage(ImageType.Primary); }
  163. set { SetImage(ImageType.Primary, value); }
  164. }
  165. /// <summary>
  166. /// Gets or sets the images.
  167. /// </summary>
  168. /// <value>The images.</value>
  169. public Dictionary<ImageType, string> Images { get; set; }
  170. /// <summary>
  171. /// Gets or sets the date created.
  172. /// </summary>
  173. /// <value>The date created.</value>
  174. public DateTime DateCreated { get; set; }
  175. /// <summary>
  176. /// Gets or sets the date modified.
  177. /// </summary>
  178. /// <value>The date modified.</value>
  179. public DateTime DateModified { get; set; }
  180. /// <summary>
  181. /// The logger
  182. /// </summary>
  183. public static ILogger Logger { get; set; }
  184. public static ILibraryManager LibraryManager { get; set; }
  185. public static IServerConfigurationManager ConfigurationManager { get; set; }
  186. public static IProviderManager ProviderManager { get; set; }
  187. public static ILocalizationManager LocalizationManager { get; set; }
  188. public static IItemRepository ItemRepository { get; set; }
  189. /// <summary>
  190. /// Returns a <see cref="System.String" /> that represents this instance.
  191. /// </summary>
  192. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  193. public override string ToString()
  194. {
  195. return Name;
  196. }
  197. /// <summary>
  198. /// Returns true if this item should not attempt to fetch metadata
  199. /// </summary>
  200. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  201. public bool DontFetchMeta { get; set; }
  202. /// <summary>
  203. /// Gets or sets the locked fields.
  204. /// </summary>
  205. /// <value>The locked fields.</value>
  206. public List<MetadataFields> LockedFields { get; set; }
  207. /// <summary>
  208. /// Determines whether the item has a saved local image of the specified name (jpg or png).
  209. /// </summary>
  210. /// <param name="name">The name.</param>
  211. /// <returns><c>true</c> if [has local image] [the specified item]; otherwise, <c>false</c>.</returns>
  212. /// <exception cref="System.ArgumentNullException">name</exception>
  213. public bool HasLocalImage(string name)
  214. {
  215. if (string.IsNullOrEmpty(name))
  216. {
  217. throw new ArgumentNullException("name");
  218. }
  219. return ResolveArgs.ContainsMetaFileByName(name + ".jpg") ||
  220. ResolveArgs.ContainsMetaFileByName(name + ".png");
  221. }
  222. /// <summary>
  223. /// Should be overridden to return the proper folder where metadata lives
  224. /// </summary>
  225. /// <value>The meta location.</value>
  226. [IgnoreDataMember]
  227. public virtual string MetaLocation
  228. {
  229. get
  230. {
  231. return Path ?? "";
  232. }
  233. }
  234. /// <summary>
  235. /// The _provider data
  236. /// </summary>
  237. private Dictionary<Guid, BaseProviderInfo> _providerData;
  238. /// <summary>
  239. /// Holds persistent data for providers like last refresh date.
  240. /// Providers can use this to determine if they need to refresh.
  241. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  242. /// Keyed by a unique provider ID.
  243. /// </summary>
  244. /// <value>The provider data.</value>
  245. public Dictionary<Guid, BaseProviderInfo> ProviderData
  246. {
  247. get
  248. {
  249. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  250. }
  251. set
  252. {
  253. _providerData = value;
  254. }
  255. }
  256. /// <summary>
  257. /// Gets the type of the media.
  258. /// </summary>
  259. /// <value>The type of the media.</value>
  260. [IgnoreDataMember]
  261. public virtual string MediaType
  262. {
  263. get
  264. {
  265. return null;
  266. }
  267. }
  268. /// <summary>
  269. /// The _resolve args
  270. /// </summary>
  271. private ItemResolveArgs _resolveArgs;
  272. /// <summary>
  273. /// The _resolve args initialized
  274. /// </summary>
  275. private bool _resolveArgsInitialized;
  276. /// <summary>
  277. /// The _resolve args sync lock
  278. /// </summary>
  279. private object _resolveArgsSyncLock = new object();
  280. /// <summary>
  281. /// We attach these to the item so that we only ever have to hit the file system once
  282. /// (this includes the children of the containing folder)
  283. /// </summary>
  284. /// <value>The resolve args.</value>
  285. [IgnoreDataMember]
  286. public ItemResolveArgs ResolveArgs
  287. {
  288. get
  289. {
  290. try
  291. {
  292. LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs());
  293. }
  294. catch (IOException ex)
  295. {
  296. Logger.ErrorException("Error creating resolve args for {0}", ex, Path);
  297. IsOffline = true;
  298. throw;
  299. }
  300. return _resolveArgs;
  301. }
  302. set
  303. {
  304. _resolveArgs = value;
  305. _resolveArgsInitialized = value != null;
  306. }
  307. }
  308. /// <summary>
  309. /// Resets the resolve args.
  310. /// </summary>
  311. /// <param name="pathInfo">The path info.</param>
  312. public void ResetResolveArgs(FileSystemInfo pathInfo)
  313. {
  314. ResolveArgs = CreateResolveArgs(pathInfo);
  315. }
  316. /// <summary>
  317. /// Creates ResolveArgs on demand
  318. /// </summary>
  319. /// <param name="pathInfo">The path info.</param>
  320. /// <returns>ItemResolveArgs.</returns>
  321. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  322. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  323. {
  324. var path = Path;
  325. if (LocationType == LocationType.Remote || LocationType == LocationType.Virtual)
  326. {
  327. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager);
  328. }
  329. var isDirectory = false;
  330. if (UseParentPathToCreateResolveArgs)
  331. {
  332. path = System.IO.Path.GetDirectoryName(path);
  333. isDirectory = true;
  334. }
  335. pathInfo = pathInfo ?? (isDirectory ? new DirectoryInfo(path) : FileSystem.GetFileSystemInfo(path));
  336. if (pathInfo == null || !pathInfo.Exists)
  337. {
  338. throw new IOException("Unable to retrieve file system info for " + path);
  339. }
  340. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager)
  341. {
  342. FileInfo = pathInfo,
  343. Path = path,
  344. Parent = Parent
  345. };
  346. // Gather child folder and files
  347. if (args.IsDirectory)
  348. {
  349. var isPhysicalRoot = args.IsPhysicalRoot;
  350. // When resolving the root, we need it's grandchildren (children of user views)
  351. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  352. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  353. // Need to remove subpaths that may have been resolved from shortcuts
  354. // Example: if \\server\movies exists, then strip out \\server\movies\action
  355. if (isPhysicalRoot)
  356. {
  357. var paths = args.FileSystemDictionary.Keys.ToList();
  358. foreach (var subPath in paths
  359. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  360. {
  361. Logger.Info("Ignoring duplicate path: {0}", subPath);
  362. args.FileSystemDictionary.Remove(subPath);
  363. }
  364. }
  365. }
  366. //update our dates
  367. EntityResolutionHelper.EnsureDates(this, args, false);
  368. IsOffline = false;
  369. return args;
  370. }
  371. /// <summary>
  372. /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the
  373. /// original ones.
  374. /// </summary>
  375. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  376. [IgnoreDataMember]
  377. protected virtual bool UseParentPathToCreateResolveArgs
  378. {
  379. get
  380. {
  381. return false;
  382. }
  383. }
  384. /// <summary>
  385. /// Gets or sets the name of the forced sort.
  386. /// </summary>
  387. /// <value>The name of the forced sort.</value>
  388. public string ForcedSortName { get; set; }
  389. private string _sortName;
  390. /// <summary>
  391. /// Gets or sets the name of the sort.
  392. /// </summary>
  393. /// <value>The name of the sort.</value>
  394. [IgnoreDataMember]
  395. public string SortName
  396. {
  397. get
  398. {
  399. if (!string.IsNullOrEmpty(ForcedSortName))
  400. {
  401. return ForcedSortName;
  402. }
  403. return _sortName ?? (_sortName = CreateSortName());
  404. }
  405. }
  406. /// <summary>
  407. /// Creates the name of the sort.
  408. /// </summary>
  409. /// <returns>System.String.</returns>
  410. protected virtual string CreateSortName()
  411. {
  412. if (Name == null) return null; //some items may not have name filled in properly
  413. var sortable = Name.Trim().ToLower();
  414. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  415. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  416. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  417. {
  418. var searchLower = search.ToLower();
  419. // Remove from beginning if a space follows
  420. if (sortable.StartsWith(searchLower + " "))
  421. {
  422. sortable = sortable.Remove(0, searchLower.Length + 1);
  423. }
  424. // Remove from middle if surrounded by spaces
  425. sortable = sortable.Replace(" " + searchLower + " ", " ");
  426. // Remove from end if followed by a space
  427. if (sortable.EndsWith(" " + searchLower))
  428. {
  429. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  430. }
  431. }
  432. return sortable;
  433. }
  434. /// <summary>
  435. /// Gets or sets the parent.
  436. /// </summary>
  437. /// <value>The parent.</value>
  438. [IgnoreDataMember]
  439. public Folder Parent { get; set; }
  440. /// <summary>
  441. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  442. /// </summary>
  443. /// <value>The premiere date.</value>
  444. public DateTime? PremiereDate { get; set; }
  445. /// <summary>
  446. /// Gets or sets the end date.
  447. /// </summary>
  448. /// <value>The end date.</value>
  449. public DateTime? EndDate { get; set; }
  450. /// <summary>
  451. /// Gets or sets the display type of the media.
  452. /// </summary>
  453. /// <value>The display type of the media.</value>
  454. public string DisplayMediaType { get; set; }
  455. /// <summary>
  456. /// Gets or sets the backdrop image paths.
  457. /// </summary>
  458. /// <value>The backdrop image paths.</value>
  459. public List<string> BackdropImagePaths { get; set; }
  460. /// <summary>
  461. /// Gets or sets the screenshot image paths.
  462. /// </summary>
  463. /// <value>The screenshot image paths.</value>
  464. public List<string> ScreenshotImagePaths { get; set; }
  465. /// <summary>
  466. /// Gets or sets the official rating.
  467. /// </summary>
  468. /// <value>The official rating.</value>
  469. public string OfficialRating { get; set; }
  470. /// <summary>
  471. /// Gets or sets the official rating description.
  472. /// </summary>
  473. /// <value>The official rating description.</value>
  474. public string OfficialRatingDescription { get; set; }
  475. /// <summary>
  476. /// Gets or sets the custom rating.
  477. /// </summary>
  478. /// <value>The custom rating.</value>
  479. public string CustomRating { get; set; }
  480. /// <summary>
  481. /// Gets or sets the language.
  482. /// </summary>
  483. /// <value>The language.</value>
  484. public string Language { get; set; }
  485. /// <summary>
  486. /// Gets or sets the overview.
  487. /// </summary>
  488. /// <value>The overview.</value>
  489. public string Overview { get; set; }
  490. /// <summary>
  491. /// Gets or sets the people.
  492. /// </summary>
  493. /// <value>The people.</value>
  494. public List<PersonInfo> People { get; set; }
  495. /// <summary>
  496. /// Gets or sets the tags.
  497. /// </summary>
  498. /// <value>The tags.</value>
  499. public List<string> Tags { get; set; }
  500. /// <summary>
  501. /// Override this if you need to combine/collapse person information
  502. /// </summary>
  503. /// <value>All people.</value>
  504. [IgnoreDataMember]
  505. public virtual IEnumerable<PersonInfo> AllPeople
  506. {
  507. get { return People; }
  508. }
  509. [IgnoreDataMember]
  510. public virtual IEnumerable<string> AllStudios
  511. {
  512. get { return Studios; }
  513. }
  514. [IgnoreDataMember]
  515. public virtual IEnumerable<string> AllGenres
  516. {
  517. get { return Genres; }
  518. }
  519. /// <summary>
  520. /// Gets or sets the studios.
  521. /// </summary>
  522. /// <value>The studios.</value>
  523. public List<string> Studios { get; set; }
  524. /// <summary>
  525. /// Gets or sets the genres.
  526. /// </summary>
  527. /// <value>The genres.</value>
  528. public List<string> Genres { get; set; }
  529. /// <summary>
  530. /// Gets or sets the home page URL.
  531. /// </summary>
  532. /// <value>The home page URL.</value>
  533. public string HomePageUrl { get; set; }
  534. /// <summary>
  535. /// Gets or sets the production locations.
  536. /// </summary>
  537. /// <value>The production locations.</value>
  538. public List<string> ProductionLocations { get; set; }
  539. /// <summary>
  540. /// Gets or sets the community rating.
  541. /// </summary>
  542. /// <value>The community rating.</value>
  543. public float? CommunityRating { get; set; }
  544. /// <summary>
  545. /// Gets or sets the community rating vote count.
  546. /// </summary>
  547. /// <value>The community rating vote count.</value>
  548. public int? VoteCount { get; set; }
  549. /// <summary>
  550. /// Gets or sets the run time ticks.
  551. /// </summary>
  552. /// <value>The run time ticks.</value>
  553. public long? RunTimeTicks { get; set; }
  554. /// <summary>
  555. /// Gets or sets the original run time ticks.
  556. /// </summary>
  557. /// <value>The original run time ticks.</value>
  558. public long? OriginalRunTimeTicks { get; set; }
  559. /// <summary>
  560. /// Gets or sets the aspect ratio.
  561. /// </summary>
  562. /// <value>The aspect ratio.</value>
  563. public string AspectRatio { get; set; }
  564. /// <summary>
  565. /// Gets or sets the production year.
  566. /// </summary>
  567. /// <value>The production year.</value>
  568. public int? ProductionYear { get; set; }
  569. /// <summary>
  570. /// If the item is part of a series, this is it's number in the series.
  571. /// This could be episode number, album track number, etc.
  572. /// </summary>
  573. /// <value>The index number.</value>
  574. public int? IndexNumber { get; set; }
  575. /// <summary>
  576. /// For an episode this could be the season number, or for a song this could be the disc number.
  577. /// </summary>
  578. /// <value>The parent index number.</value>
  579. public int? ParentIndexNumber { get; set; }
  580. public List<Guid> ThemeSongIds { get; set; }
  581. public List<Guid> ThemeVideoIds { get; set; }
  582. public List<Guid> LocalTrailerIds { get; set; }
  583. [IgnoreDataMember]
  584. public virtual string OfficialRatingForComparison
  585. {
  586. get { return OfficialRating; }
  587. }
  588. [IgnoreDataMember]
  589. public virtual string CustomRatingForComparison
  590. {
  591. get { return CustomRating; }
  592. }
  593. /// <summary>
  594. /// Loads local trailers from the file system
  595. /// </summary>
  596. /// <returns>List{Video}.</returns>
  597. private IEnumerable<Trailer> LoadLocalTrailers()
  598. {
  599. ItemResolveArgs resolveArgs;
  600. try
  601. {
  602. resolveArgs = ResolveArgs;
  603. if (!resolveArgs.IsDirectory)
  604. {
  605. return new List<Trailer>();
  606. }
  607. }
  608. catch (IOException ex)
  609. {
  610. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  611. return new List<Trailer>();
  612. }
  613. var files = new List<FileSystemInfo>();
  614. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  615. // Path doesn't exist. No biggie
  616. if (folder != null)
  617. {
  618. try
  619. {
  620. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  621. }
  622. catch (IOException ex)
  623. {
  624. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  625. }
  626. }
  627. // Support xbmc trailers (-trailer suffix on video file names)
  628. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  629. {
  630. try
  631. {
  632. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  633. {
  634. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  635. {
  636. return true;
  637. }
  638. }
  639. }
  640. catch (IOException ex)
  641. {
  642. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  643. }
  644. return false;
  645. }));
  646. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  647. {
  648. // Try to retrieve it from the db. If we don't find it, use the resolved version
  649. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  650. if (dbItem != null)
  651. {
  652. dbItem.ResolveArgs = video.ResolveArgs;
  653. video = dbItem;
  654. }
  655. return video;
  656. }).ToList();
  657. }
  658. /// <summary>
  659. /// Loads the theme songs.
  660. /// </summary>
  661. /// <returns>List{Audio.Audio}.</returns>
  662. private IEnumerable<Audio.Audio> LoadThemeSongs()
  663. {
  664. ItemResolveArgs resolveArgs;
  665. try
  666. {
  667. resolveArgs = ResolveArgs;
  668. if (!resolveArgs.IsDirectory)
  669. {
  670. return new List<Audio.Audio>();
  671. }
  672. }
  673. catch (IOException ex)
  674. {
  675. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  676. return new List<Audio.Audio>();
  677. }
  678. var files = new List<FileSystemInfo>();
  679. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  680. // Path doesn't exist. No biggie
  681. if (folder != null)
  682. {
  683. try
  684. {
  685. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  686. }
  687. catch (IOException ex)
  688. {
  689. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  690. }
  691. }
  692. // Support plex/xbmc convention
  693. files.AddRange(resolveArgs.FileSystemChildren
  694. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  695. );
  696. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  697. {
  698. // Try to retrieve it from the db. If we don't find it, use the resolved version
  699. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  700. if (dbItem != null)
  701. {
  702. dbItem.ResolveArgs = audio.ResolveArgs;
  703. audio = dbItem;
  704. }
  705. return audio;
  706. }).ToList();
  707. }
  708. /// <summary>
  709. /// Loads the video backdrops.
  710. /// </summary>
  711. /// <returns>List{Video}.</returns>
  712. private IEnumerable<Video> LoadThemeVideos()
  713. {
  714. ItemResolveArgs resolveArgs;
  715. try
  716. {
  717. resolveArgs = ResolveArgs;
  718. if (!resolveArgs.IsDirectory)
  719. {
  720. return new List<Video>();
  721. }
  722. }
  723. catch (IOException ex)
  724. {
  725. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  726. return new List<Video>();
  727. }
  728. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  729. // Path doesn't exist. No biggie
  730. if (folder == null)
  731. {
  732. return new List<Video>();
  733. }
  734. IEnumerable<FileSystemInfo> files;
  735. try
  736. {
  737. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  738. }
  739. catch (IOException ex)
  740. {
  741. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  742. return new List<Video>();
  743. }
  744. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  745. {
  746. // Try to retrieve it from the db. If we don't find it, use the resolved version
  747. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  748. if (dbItem != null)
  749. {
  750. dbItem.ResolveArgs = item.ResolveArgs;
  751. item = dbItem;
  752. }
  753. return item;
  754. }).ToList();
  755. }
  756. /// <summary>
  757. /// Overrides the base implementation to refresh metadata for local trailers
  758. /// </summary>
  759. /// <param name="cancellationToken">The cancellation token.</param>
  760. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  761. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  762. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  763. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  764. /// <returns>true if a provider reports we changed</returns>
  765. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  766. {
  767. if (resetResolveArgs)
  768. {
  769. // Reload this
  770. ResolveArgs = null;
  771. }
  772. // Refresh for the item
  773. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  774. cancellationToken.ThrowIfCancellationRequested();
  775. var themeSongsChanged = false;
  776. var themeVideosChanged = false;
  777. var localTrailersChanged = false;
  778. if (LocationType == LocationType.FileSystem && Parent != null)
  779. {
  780. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  781. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  782. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  783. }
  784. cancellationToken.ThrowIfCancellationRequested();
  785. // Get the result from the item task
  786. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  787. var changed = updateReason.HasValue;
  788. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  789. {
  790. cancellationToken.ThrowIfCancellationRequested();
  791. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  792. }
  793. return changed;
  794. }
  795. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  796. {
  797. var newItems = LoadLocalTrailers().ToList();
  798. var newItemIds = newItems.Select(i => i.Id).ToList();
  799. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  800. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  801. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  802. LocalTrailerIds = newItemIds;
  803. return itemsChanged || results.Contains(true);
  804. }
  805. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  806. {
  807. var newThemeVideos = LoadThemeVideos().ToList();
  808. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  809. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  810. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  811. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  812. ThemeVideoIds = newThemeVideoIds;
  813. return themeVideosChanged || results.Contains(true);
  814. }
  815. /// <summary>
  816. /// Refreshes the theme songs.
  817. /// </summary>
  818. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  819. {
  820. var newThemeSongs = LoadThemeSongs().ToList();
  821. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  822. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  823. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  824. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  825. ThemeSongIds = newThemeSongIds;
  826. return themeSongsChanged || results.Contains(true);
  827. }
  828. /// <summary>
  829. /// Gets or sets the provider ids.
  830. /// </summary>
  831. /// <value>The provider ids.</value>
  832. public Dictionary<string, string> ProviderIds { get; set; }
  833. /// <summary>
  834. /// Override this to false if class should be ignored for indexing purposes
  835. /// </summary>
  836. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  837. [IgnoreDataMember]
  838. public virtual bool IncludeInIndex
  839. {
  840. get { return true; }
  841. }
  842. /// <summary>
  843. /// Override this to true if class should be grouped under a container in indicies
  844. /// The container class should be defined via IndexContainer
  845. /// </summary>
  846. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  847. [IgnoreDataMember]
  848. public virtual bool GroupInIndex
  849. {
  850. get { return false; }
  851. }
  852. /// <summary>
  853. /// Override this to return the folder that should be used to construct a container
  854. /// for this item in an index. GroupInIndex should be true as well.
  855. /// </summary>
  856. /// <value>The index container.</value>
  857. [IgnoreDataMember]
  858. public virtual Folder IndexContainer
  859. {
  860. get { return null; }
  861. }
  862. /// <summary>
  863. /// Gets the user data key.
  864. /// </summary>
  865. /// <returns>System.String.</returns>
  866. public virtual string GetUserDataKey()
  867. {
  868. return Id.ToString();
  869. }
  870. /// <summary>
  871. /// Determines if a given user has access to this item
  872. /// </summary>
  873. /// <param name="user">The user.</param>
  874. /// <param name="localizationManager">The localization manager.</param>
  875. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  876. /// <exception cref="System.ArgumentNullException">user</exception>
  877. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  878. {
  879. if (user == null)
  880. {
  881. throw new ArgumentNullException("user");
  882. }
  883. if (user.Configuration.MaxParentalRating == null)
  884. {
  885. return true;
  886. }
  887. var rating = CustomRatingForComparison;
  888. if (string.IsNullOrEmpty(rating))
  889. {
  890. rating = OfficialRatingForComparison;
  891. }
  892. if (string.IsNullOrEmpty(rating))
  893. {
  894. return !user.Configuration.BlockNotRated;
  895. }
  896. var value = localizationManager.GetRatingLevel(rating);
  897. // Could not determine the integer value
  898. if (!value.HasValue)
  899. {
  900. return true;
  901. }
  902. return value.Value <= user.Configuration.MaxParentalRating.Value;
  903. }
  904. /// <summary>
  905. /// Determines if this folder should be visible to a given user.
  906. /// Default is just parental allowed. Can be overridden for more functionality.
  907. /// </summary>
  908. /// <param name="user">The user.</param>
  909. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  910. /// <exception cref="System.ArgumentNullException">user</exception>
  911. public virtual bool IsVisible(User user)
  912. {
  913. if (user == null)
  914. {
  915. throw new ArgumentNullException("user");
  916. }
  917. return IsParentalAllowed(user, LocalizationManager);
  918. }
  919. /// <summary>
  920. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  921. /// </summary>
  922. /// <param name="id">The id.</param>
  923. /// <returns>BaseItem.</returns>
  924. /// <exception cref="System.ArgumentException"></exception>
  925. protected BaseItem FindParentItem(Guid id)
  926. {
  927. if (id == Guid.Empty)
  928. {
  929. throw new ArgumentException();
  930. }
  931. var parent = Parent;
  932. while (parent != null && !parent.IsRoot)
  933. {
  934. if (parent.Id == id) return parent;
  935. parent = parent.Parent;
  936. }
  937. return null;
  938. }
  939. /// <summary>
  940. /// Gets a value indicating whether this instance is folder.
  941. /// </summary>
  942. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  943. [IgnoreDataMember]
  944. public virtual bool IsFolder
  945. {
  946. get
  947. {
  948. return false;
  949. }
  950. }
  951. /// <summary>
  952. /// Determine if we have changed vs the passed in copy
  953. /// </summary>
  954. /// <param name="copy">The copy.</param>
  955. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  956. /// <exception cref="System.ArgumentNullException"></exception>
  957. public virtual bool HasChanged(BaseItem copy)
  958. {
  959. if (copy == null)
  960. {
  961. throw new ArgumentNullException();
  962. }
  963. var changed = copy.DateModified != DateModified;
  964. if (changed)
  965. {
  966. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  967. }
  968. return changed;
  969. }
  970. /// <summary>
  971. /// Determines if the item is considered new based on user settings
  972. /// </summary>
  973. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  974. /// <exception cref="System.ArgumentNullException"></exception>
  975. public bool IsRecentlyAdded()
  976. {
  977. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  978. }
  979. /// <summary>
  980. /// Adds a person to the item
  981. /// </summary>
  982. /// <param name="person">The person.</param>
  983. /// <exception cref="System.ArgumentNullException"></exception>
  984. public void AddPerson(PersonInfo person)
  985. {
  986. if (person == null)
  987. {
  988. throw new ArgumentNullException("person");
  989. }
  990. if (string.IsNullOrWhiteSpace(person.Name))
  991. {
  992. throw new ArgumentNullException();
  993. }
  994. // Normalize
  995. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  996. {
  997. person.Type = PersonType.GuestStar;
  998. }
  999. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  1000. {
  1001. person.Type = PersonType.Director;
  1002. }
  1003. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  1004. {
  1005. person.Type = PersonType.Producer;
  1006. }
  1007. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  1008. {
  1009. person.Type = PersonType.Writer;
  1010. }
  1011. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1012. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1013. {
  1014. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1015. if (existing != null)
  1016. {
  1017. existing.Type = PersonType.GuestStar;
  1018. return;
  1019. }
  1020. }
  1021. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1022. {
  1023. // If the actor already exists without a role and we have one, fill it in
  1024. 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)));
  1025. if (existing == null)
  1026. {
  1027. // Wasn't there - add it
  1028. People.Add(person);
  1029. }
  1030. else
  1031. {
  1032. // Was there, if no role and we have one - fill it in
  1033. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1034. }
  1035. }
  1036. else
  1037. {
  1038. // Check for dupes based on the combination of Name and Type
  1039. if (!People.Any(p => string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase)))
  1040. {
  1041. People.Add(person);
  1042. }
  1043. }
  1044. }
  1045. /// <summary>
  1046. /// Adds the tagline.
  1047. /// </summary>
  1048. /// <param name="item">The item.</param>
  1049. /// <param name="tagline">The tagline.</param>
  1050. /// <exception cref="System.ArgumentNullException">tagline</exception>
  1051. public void AddTagline(string tagline)
  1052. {
  1053. if (string.IsNullOrWhiteSpace(tagline))
  1054. {
  1055. throw new ArgumentNullException("tagline");
  1056. }
  1057. if (!Taglines.Contains(tagline, StringComparer.OrdinalIgnoreCase))
  1058. {
  1059. Taglines.Add(tagline);
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Adds a studio to the item
  1064. /// </summary>
  1065. /// <param name="name">The name.</param>
  1066. /// <exception cref="System.ArgumentNullException"></exception>
  1067. public void AddStudio(string name)
  1068. {
  1069. if (string.IsNullOrWhiteSpace(name))
  1070. {
  1071. throw new ArgumentNullException("name");
  1072. }
  1073. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1074. {
  1075. Studios.Add(name);
  1076. }
  1077. }
  1078. public void AddTag(string name)
  1079. {
  1080. if (string.IsNullOrWhiteSpace(name))
  1081. {
  1082. throw new ArgumentNullException("name");
  1083. }
  1084. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  1085. {
  1086. Tags.Add(name);
  1087. }
  1088. }
  1089. /// <summary>
  1090. /// Adds a genre to the item
  1091. /// </summary>
  1092. /// <param name="name">The name.</param>
  1093. /// <exception cref="System.ArgumentNullException"></exception>
  1094. public void AddGenre(string name)
  1095. {
  1096. if (string.IsNullOrWhiteSpace(name))
  1097. {
  1098. throw new ArgumentNullException("name");
  1099. }
  1100. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1101. {
  1102. Genres.Add(name);
  1103. }
  1104. }
  1105. /// <summary>
  1106. /// Adds the production location.
  1107. /// </summary>
  1108. /// <param name="location">The location.</param>
  1109. /// <exception cref="System.ArgumentNullException">location</exception>
  1110. public void AddProductionLocation(string location)
  1111. {
  1112. if (string.IsNullOrWhiteSpace(location))
  1113. {
  1114. throw new ArgumentNullException("location");
  1115. }
  1116. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1117. {
  1118. ProductionLocations.Add(location);
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// Marks the item as either played or unplayed
  1123. /// </summary>
  1124. /// <param name="user">The user.</param>
  1125. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  1126. /// <param name="userManager">The user manager.</param>
  1127. /// <returns>Task.</returns>
  1128. /// <exception cref="System.ArgumentNullException"></exception>
  1129. public virtual async Task SetPlayedStatus(User user, bool wasPlayed, IUserDataRepository userManager)
  1130. {
  1131. if (user == null)
  1132. {
  1133. throw new ArgumentNullException();
  1134. }
  1135. var key = GetUserDataKey();
  1136. var data = userManager.GetUserData(user.Id, key);
  1137. if (wasPlayed)
  1138. {
  1139. data.PlayCount = Math.Max(data.PlayCount, 1);
  1140. if (!data.LastPlayedDate.HasValue)
  1141. {
  1142. data.LastPlayedDate = DateTime.UtcNow;
  1143. }
  1144. }
  1145. else
  1146. {
  1147. //I think it is okay to do this here.
  1148. // if this is only called when a user is manually forcing something to un-played
  1149. // then it probably is what we want to do...
  1150. data.PlayCount = 0;
  1151. data.PlaybackPositionTicks = 0;
  1152. data.LastPlayedDate = null;
  1153. }
  1154. data.Played = wasPlayed;
  1155. await userManager.SaveUserData(user.Id, key, data, CancellationToken.None).ConfigureAwait(false);
  1156. }
  1157. /// <summary>
  1158. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1159. /// </summary>
  1160. /// <returns>Task.</returns>
  1161. public virtual Task ChangedExternally()
  1162. {
  1163. return RefreshMetadata(CancellationToken.None);
  1164. }
  1165. /// <summary>
  1166. /// Finds a parent of a given type
  1167. /// </summary>
  1168. /// <typeparam name="T"></typeparam>
  1169. /// <returns>``0.</returns>
  1170. public T FindParent<T>()
  1171. where T : Folder
  1172. {
  1173. var parent = Parent;
  1174. while (parent != null)
  1175. {
  1176. var result = parent as T;
  1177. if (result != null)
  1178. {
  1179. return result;
  1180. }
  1181. parent = parent.Parent;
  1182. }
  1183. return null;
  1184. }
  1185. /// <summary>
  1186. /// Gets an image
  1187. /// </summary>
  1188. /// <param name="type">The type.</param>
  1189. /// <returns>System.String.</returns>
  1190. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1191. public string GetImage(ImageType type)
  1192. {
  1193. if (type == ImageType.Backdrop)
  1194. {
  1195. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1196. }
  1197. if (type == ImageType.Screenshot)
  1198. {
  1199. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1200. }
  1201. string val;
  1202. Images.TryGetValue(type, out val);
  1203. return val;
  1204. }
  1205. /// <summary>
  1206. /// Gets an image
  1207. /// </summary>
  1208. /// <param name="type">The type.</param>
  1209. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1210. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1211. public bool HasImage(ImageType type)
  1212. {
  1213. if (type == ImageType.Backdrop)
  1214. {
  1215. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1216. }
  1217. if (type == ImageType.Screenshot)
  1218. {
  1219. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1220. }
  1221. return !string.IsNullOrEmpty(GetImage(type));
  1222. }
  1223. /// <summary>
  1224. /// Sets an image
  1225. /// </summary>
  1226. /// <param name="type">The type.</param>
  1227. /// <param name="path">The path.</param>
  1228. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1229. public void SetImage(ImageType type, string path)
  1230. {
  1231. if (type == ImageType.Backdrop)
  1232. {
  1233. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1234. }
  1235. if (type == ImageType.Screenshot)
  1236. {
  1237. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1238. }
  1239. var typeKey = type;
  1240. // If it's null remove the key from the dictionary
  1241. if (string.IsNullOrEmpty(path))
  1242. {
  1243. if (Images.ContainsKey(typeKey))
  1244. {
  1245. Images.Remove(typeKey);
  1246. }
  1247. }
  1248. else
  1249. {
  1250. Images[typeKey] = path;
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// Deletes the image.
  1255. /// </summary>
  1256. /// <param name="type">The type.</param>
  1257. /// <param name="index">The index.</param>
  1258. /// <returns>Task.</returns>
  1259. public Task DeleteImage(ImageType type, int? index)
  1260. {
  1261. if (type == ImageType.Backdrop)
  1262. {
  1263. if (!index.HasValue)
  1264. {
  1265. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1266. }
  1267. var file = BackdropImagePaths[index.Value];
  1268. BackdropImagePaths.Remove(file);
  1269. // Delete the source file
  1270. File.Delete(file);
  1271. }
  1272. else if (type == ImageType.Screenshot)
  1273. {
  1274. if (!index.HasValue)
  1275. {
  1276. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1277. }
  1278. var file = ScreenshotImagePaths[index.Value];
  1279. ScreenshotImagePaths.Remove(file);
  1280. // Delete the source file
  1281. File.Delete(file);
  1282. }
  1283. else
  1284. {
  1285. // Delete the source file
  1286. File.Delete(GetImage(type));
  1287. // Remove it from the item
  1288. SetImage(type, null);
  1289. }
  1290. // Refresh metadata
  1291. return RefreshMetadata(CancellationToken.None, forceSave: true);
  1292. }
  1293. /// <summary>
  1294. /// Validates that images within the item are still on the file system
  1295. /// </summary>
  1296. public void ValidateImages()
  1297. {
  1298. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1299. var deletedKeys = Images
  1300. .Where(image => !File.Exists(image.Value))
  1301. .Select(i => i.Key)
  1302. .ToList();
  1303. // Now remove them from the dictionary
  1304. foreach (var key in deletedKeys)
  1305. {
  1306. Images.Remove(key);
  1307. }
  1308. }
  1309. /// <summary>
  1310. /// Validates that backdrops within the item are still on the file system
  1311. /// </summary>
  1312. public void ValidateBackdrops()
  1313. {
  1314. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1315. var deletedImages = BackdropImagePaths
  1316. .Where(path => !File.Exists(path))
  1317. .ToList();
  1318. // Now remove them from the dictionary
  1319. foreach (var path in deletedImages)
  1320. {
  1321. BackdropImagePaths.Remove(path);
  1322. }
  1323. }
  1324. /// <summary>
  1325. /// Validates the screenshots.
  1326. /// </summary>
  1327. public void ValidateScreenshots()
  1328. {
  1329. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1330. var deletedImages = ScreenshotImagePaths
  1331. .Where(path => !File.Exists(path))
  1332. .ToList();
  1333. // Now remove them from the dictionary
  1334. foreach (var path in deletedImages)
  1335. {
  1336. ScreenshotImagePaths.Remove(path);
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Gets the image path.
  1341. /// </summary>
  1342. /// <param name="imageType">Type of the image.</param>
  1343. /// <param name="imageIndex">Index of the image.</param>
  1344. /// <returns>System.String.</returns>
  1345. /// <exception cref="System.InvalidOperationException">
  1346. /// </exception>
  1347. /// <exception cref="System.ArgumentNullException">item</exception>
  1348. public string GetImagePath(ImageType imageType, int imageIndex)
  1349. {
  1350. if (imageType == ImageType.Backdrop)
  1351. {
  1352. return BackdropImagePaths[imageIndex];
  1353. }
  1354. if (imageType == ImageType.Screenshot)
  1355. {
  1356. return ScreenshotImagePaths[imageIndex];
  1357. }
  1358. if (imageType == ImageType.Chapter)
  1359. {
  1360. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1361. }
  1362. return GetImage(imageType);
  1363. }
  1364. /// <summary>
  1365. /// Gets the image date modified.
  1366. /// </summary>
  1367. /// <param name="imagePath">The image path.</param>
  1368. /// <returns>DateTime.</returns>
  1369. /// <exception cref="System.ArgumentNullException">item</exception>
  1370. public DateTime GetImageDateModified(string imagePath)
  1371. {
  1372. if (string.IsNullOrEmpty(imagePath))
  1373. {
  1374. throw new ArgumentNullException("imagePath");
  1375. }
  1376. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1377. // If we didn't the metafile entry, check the Season
  1378. if (metaFileEntry == null)
  1379. {
  1380. var episode = this as Episode;
  1381. if (episode != null && episode.Season != null)
  1382. {
  1383. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  1384. }
  1385. }
  1386. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1387. return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.LastWriteTimeUtc;
  1388. }
  1389. }
  1390. }