BaseItem.cs 56 KB

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